From e481b546d536b9c37aeafe110bfd3d816928a180 Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:17:16 +0000 Subject: [PATCH 1/6] bl-188: build gate, a first in first out cap on concurrent builds --- .../loop/core/orchestrator/BuildGate.kt | 93 ++++++++++ .../loop/core/orchestrator/BuildGateTest.kt | 169 ++++++++++++++++++ 2 files changed, 262 insertions(+) create mode 100644 spec-core/src/main/kotlin/loop/core/orchestrator/BuildGate.kt create mode 100644 spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt diff --git a/spec-core/src/main/kotlin/loop/core/orchestrator/BuildGate.kt b/spec-core/src/main/kotlin/loop/core/orchestrator/BuildGate.kt new file mode 100644 index 0000000..308f77c --- /dev/null +++ b/spec-core/src/main/kotlin/loop/core/orchestrator/BuildGate.kt @@ -0,0 +1,93 @@ +package loop.core.orchestrator + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import loop.core.log.LogContext + +/** + * The build gate of a project (bl-188): at most [capacity] verification builds and merge check builds run at once, + * whoever started them, an attempt's verification, a merge check or the rerun of a restored `verify` wait. A build that + * finds no room waits in a first in, first out queue. [capacity] is read on every admission, so a reload changes what + * starts next and never stops a build already running; a raised capacity admits queued builds at the next [admit]. + * Agent slots are a separate matter: a restored wait still takes none (bl-173), only its build passes here. + * + * [onQueued] is told once when a build has to wait, with the number of builds ahead of it, running or queued. + */ +internal class BuildGate( + private val capacity: () -> Int, + private val onQueued: (LogContext, Int) -> Unit = { _, _ -> }, +) { + private val lock = Any() + private val queue = ArrayDeque>() + + private var builds = 0 + + /** The builds running now. */ + val running: Int + get() = synchronized(lock) { builds } + + /** The builds waiting for room now. */ + val queued: Int + get() = synchronized(lock) { queue.size } + + /** + * Runs [block] once the gate has room for it, after every build queued before it. Waiting can be cancelled, which + * leaves the queue; the room is given back when [block] ends, also on an exception or a cancellation. + */ + suspend fun withBuild( + context: LogContext, + block: suspend () -> T, + ): T { + acquire(context) + try { + return block() + } finally { + release() + } + } + + /** Admits the queued builds the capacity has room for now, oldest first, for a capacity raised since. */ + fun admit() { + synchronized(lock) { admitLocked() } + } + + private suspend fun acquire(context: LogContext) { + val ticket = CompletableDeferred() + val ahead = + synchronized(lock) { + if (queue.isEmpty() && builds < capacity()) { + builds++ + return + } + queue.addLast(ticket) + builds + queue.size - 1 + } + onQueued(context, ahead) + try { + ticket.await() + } catch (e: CancellationException) { + synchronized(lock) { + // Admitted just before the cancel came: the room it was given goes to the next build. + if (!queue.remove(ticket)) { + builds-- + admitLocked() + } + } + throw e + } + } + + private fun release() { + synchronized(lock) { + builds-- + admitLocked() + } + } + + private fun admitLocked() { + while (queue.isNotEmpty() && builds < capacity()) { + builds++ + queue.removeFirst().complete(Unit) + } + } +} diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt new file mode 100644 index 0000000..a9f7657 --- /dev/null +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt @@ -0,0 +1,169 @@ +package loop.core.orchestrator + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import loop.core.log.LogContext +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** The build gate on its own (bl-188): first in, first out, a live capacity, cancels and failures. */ +@OptIn(ExperimentalCoroutinesApi::class) +class BuildGateTest { + private val context = LogContext() + + @Test + fun `with capacity 1 three concurrent builds run one at a time in arrival order`() = + runTest { + val gate = BuildGate({ 1 }) + val log = mutableListOf() + var running = 0 + var most = 0 + val ends = List(3) { CompletableDeferred() } + val jobs = + (0 until 3).map { n -> + launch { + gate.withBuild(context) { + running++ + most = maxOf(most, running) + log += "start $n" + ends[n].await() + log += "end $n" + running-- + } + }.also { runCurrent() } + } + assertEquals(listOf("start 0"), log) + assertEquals(2, gate.queued) + ends.forEach { end -> + end.complete(Unit) + runCurrent() + } + jobs.forEach { it.join() } + + assertEquals(listOf("start 0", "end 0", "start 1", "end 1", "start 2", "end 2"), log) + assertEquals(1, most) + } + + @Test + fun `lowering the capacity from 2 to 1 while two builds run admits no queued build until both have ended`() = + runTest { + var capacity = 2 + val gate = BuildGate({ capacity }) + val started = mutableListOf() + val ends = List(3) { CompletableDeferred() } + val jobs = + (0 until 3).map { n -> + launch { + gate.withBuild(context) { + started += n + ends[n].await() + } + }.also { runCurrent() } + } + assertEquals(listOf(0, 1), started) + + capacity = 1 + ends[0].complete(Unit) + runCurrent() + gate.admit() + runCurrent() + assertEquals(listOf(0, 1), started) + + ends[1].complete(Unit) + runCurrent() + assertEquals(listOf(0, 1, 2), started) + ends[2].complete(Unit) + jobs.forEach { it.join() } + } + + @Test + fun `raising the capacity then calling admit starts a queued build`() = + runTest { + var capacity = 1 + val gate = BuildGate({ capacity }) + val started = mutableListOf() + val ends = List(2) { CompletableDeferred() } + val jobs = + (0 until 2).map { n -> + launch { + gate.withBuild(context) { + started += n + ends[n].await() + } + }.also { runCurrent() } + } + assertEquals(listOf(0), started) + + capacity = 2 + gate.admit() + runCurrent() + + assertEquals(listOf(0, 1), started) + ends.forEach { it.complete(Unit) } + jobs.forEach { it.join() } + } + + @Test + fun `a cancelled waiter leaves the queue and takes no capacity`() = + runTest { + val gate = BuildGate({ 1 }) + val started = mutableListOf() + val ends = List(3) { CompletableDeferred() } + val jobs = + (0 until 3).map { n -> + launch { + gate.withBuild(context) { + started += n + ends[n].await() + } + }.also { runCurrent() } + } + assertEquals(2, gate.queued) + + jobs[1].cancel() + runCurrent() + assertEquals(1, gate.queued) + + ends[0].complete(Unit) + runCurrent() + assertEquals(listOf(0, 2), started) + assertEquals(0, gate.queued) + ends[2].complete(Unit) + jobs.forEach { it.join() } + assertEquals(0, gate.running) + } + + @Test + fun `a block that throws still releases its capacity`() = + runTest { + val gate = BuildGate({ 1 }) + + assertFailsWith { gate.withBuild(context) { error("the build broke") } } + + assertEquals(0, gate.running) + var ran = false + gate.withBuild(context) { ran = true } + assertTrue(ran) + } + + @Test + fun `a build that has to wait is reported once with the builds ahead of it`() = + runTest { + val queued = mutableListOf() + val gate = BuildGate({ 1 }) { _, ahead -> queued += ahead } + val ends = List(3) { CompletableDeferred() } + val jobs = + (0 until 3).map { n -> + launch { gate.withBuild(context) { ends[n].await() } }.also { runCurrent() } + } + + assertEquals(listOf(1, 2), queued) + ends.forEach { it.complete(Unit) } + jobs.forEach { it.join() } + } +} From 43cf1a8f27935f46b1a65c987338d465f905ef48 Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:18:18 +0000 Subject: [PATCH 2/6] bl-188: agent.max_concurrent_verifications, falling back to max_concurrent_agents --- .../loop/core/workflow/WorkflowConfig.kt | 16 +++- .../kotlin/loop/core/workflow/WorkflowFile.kt | 1 + .../VerificationConcurrencyConfigTest.kt | 84 +++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt diff --git a/spec-core/src/main/kotlin/loop/core/workflow/WorkflowConfig.kt b/spec-core/src/main/kotlin/loop/core/workflow/WorkflowConfig.kt index 1f4e4f6..b97b78b 100644 --- a/spec-core/src/main/kotlin/loop/core/workflow/WorkflowConfig.kt +++ b/spec-core/src/main/kotlin/loop/core/workflow/WorkflowConfig.kt @@ -634,7 +634,10 @@ data class HooksConfig( val onHumanNeeded: String? = null, ) -/** Spec 5.3.5, plus Loop's `agent.env` (bl-01), `agent.max_wake_turns` (m4-03) and `agent.max_concurrent_agents_by_tracker` (m4-15). */ +/** + * Spec 5.3.5, plus Loop's `agent.env` (bl-01), `agent.max_wake_turns` (m4-03), `agent.max_concurrent_agents_by_tracker` + * (m4-15) and `agent.max_concurrent_verifications` (bl-188). + */ data class AgentConfig( val maxConcurrentAgents: Int = 10, val maxTurns: Int = 20, @@ -658,7 +661,16 @@ data class AgentConfig( * `max_wake_turns`, so a chatty background task cannot keep it alive forever. */ val maxWakeTurns: Int = 30, -) + /** + * `agent.max_concurrent_verifications` (bl-188): the verification builds and merge check builds that run at once, + * a positive integer. Null, the default, falls back to [maxConcurrentAgents], see [buildCapacity]. + */ + val maxConcurrentVerifications: Int? = null, +) { + /** The capacity of the build gate: [maxConcurrentVerifications], else [maxConcurrentAgents]. */ + val buildCapacity: Int + get() = maxConcurrentVerifications ?: maxConcurrentAgents +} /** * Loop's spend budgets (m2-20) and token thresholds (m1-38). Each budget is opt in: null, the default, is no diff --git a/spec-core/src/main/kotlin/loop/core/workflow/WorkflowFile.kt b/spec-core/src/main/kotlin/loop/core/workflow/WorkflowFile.kt index 485405b..cf3f19d 100644 --- a/spec-core/src/main/kotlin/loop/core/workflow/WorkflowFile.kt +++ b/spec-core/src/main/kotlin/loop/core/workflow/WorkflowFile.kt @@ -406,6 +406,7 @@ class WorkflowLoader( maxConcurrentAgents = agent.positiveInt("agent.max_concurrent_agents", "max_concurrent_agents") ?: defaults.maxConcurrentAgents, + maxConcurrentVerifications = agent.positiveInt("agent.max_concurrent_verifications", "max_concurrent_verifications"), maxTurns = agent.positiveInt("agent.max_turns", "max_turns") ?: defaults.maxTurns, maxWakeTurns = agent.positiveInt("agent.max_wake_turns", "max_wake_turns") ?: defaults.maxWakeTurns, maxRetryBackoffMs = diff --git a/spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt b/spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt new file mode 100644 index 0000000..d535701 --- /dev/null +++ b/spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt @@ -0,0 +1,84 @@ +package loop.core.workflow + +import kotlinx.coroutines.runBlocking +import loop.core.template.TemplateEngine +import java.nio.file.Path +import kotlin.io.path.createTempDirectory +import kotlin.io.path.writeText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * bl-188: `agent.max_concurrent_verifications`, the verification and merge check builds that run at once. Absent, the + * build gate takes `agent.max_concurrent_agents`; a value that is not a positive integer fails preflight. + */ +class VerificationConcurrencyConfigTest { + private val folder: Path = createTempDirectory("loop-verification-concurrency").toRealPath() + private val loader = WorkflowLoader(env = emptyMap()) + + private fun write(agent: String): Path = + folder.resolve("WORKFLOW.md").also { + it.writeText( + """ + |--- + |tracker: + | kind: files + |runner: + | kind: command + |runners: + | command: + | command: ./agent.sh + |agent: + |$agent + |--- + |Prompt + """.trimMargin(), + ) + } + + private fun agent(agent: String): AgentConfig = + loader + .load(write(agent)) + .getOrThrow() + .config.agent + + private fun refusal(agent: String): String { + val failed = + assertIs(runBlocking { Preflight(loader, write(agent), TemplateEngine(), { null }).check() }) + assertEquals("invalid_config", failed.code) + return failed.message + } + + @Test + fun `an absent key falls back to max_concurrent_agents`() { + val config = agent(" max_concurrent_agents: 3") + + assertNull(config.maxConcurrentVerifications) + assertEquals(3, config.buildCapacity) + assertEquals(10, AgentConfig().buildCapacity) + } + + @Test + fun `max_concurrent_verifications 1 parses beside max_concurrent_agents`() { + val config = agent(" max_concurrent_agents: 3\n max_concurrent_verifications: 1") + + assertEquals(1, config.maxConcurrentVerifications) + assertEquals(1, config.buildCapacity) + assertEquals(3, config.maxConcurrentAgents) + assertEquals(2, agent(" max_concurrent_verifications: \"2\"").maxConcurrentVerifications) + } + + @Test + fun `preflight refuses 0 and a value that is no integer, naming the key`() { + assertEquals( + "agent.max_concurrent_verifications must be a positive integer, got 0", + refusal(" max_concurrent_verifications: 0"), + ) + assertEquals( + "agent.max_concurrent_verifications must be a positive integer, got \"one\"", + refusal(" max_concurrent_verifications: one"), + ) + } +} From 3a6f68cfece682b68cb03a330cda95929e59d7cc Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:21:29 +0000 Subject: [PATCH 3/6] bl-188: attempts, merge checks and restored reruns build through the build gate --- .../loop/core/orchestrator/Orchestrator.kt | 24 ++- .../orchestrator/BuildGateOrchestratorTest.kt | 184 ++++++++++++++++++ .../loop/core/orchestrator/HeldBuilds.kt | 49 +++++ 3 files changed, 254 insertions(+), 3 deletions(-) create mode 100644 spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt create mode 100644 spec-core/src/test/kotlin/loop/core/orchestrator/HeldBuilds.kt diff --git a/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt b/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt index 9af7973..7e96147 100644 --- a/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt +++ b/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt @@ -594,6 +594,16 @@ class Orchestrator( */ private val waits = Waits(waiting, projectId) + /** + * bl-188: every verification build and merge check build passes here first, an attempt's, a merge check's and a + * restored wait's rerun, so at most `agent.max_concurrent_verifications` (else `agent.max_concurrent_agents`) run at + * once. Read from [effective] on every admission, so a reload applies to the builds that have not started yet. + */ + private val buildGate = + BuildGate({ effective.config.agent.buildCapacity }) { context, ahead -> + log.log(LogLevel.INFO, BUILD_GATE, LogOutcome.SCHEDULED, context, mapOf("ahead" to ahead), "verification waits for a build slot ($ahead ahead)") + } + /** True once [restoreWaiting] resumed the waits a previous process left. */ private var waitingRestored = false @@ -804,6 +814,8 @@ class Orchestrator( // bl-101: before the preflight, so a slot whose release failed is not held while config.yaml stays malformed. machineGate.retryReleases(pollContext) if (!passesPreflight()) return Dispatched(candidates = 0, attempts = emptyList()) + // bl-188: a reload that raised the build capacity starts the queued builds it now has room for. + buildGate.admit() // m4-13: each tracker polled with its own active states; one that fails is skipped this tick, the others go on. val polled = trackers.poll(effective.trackers) polled.failures.forEach { (id, error) -> @@ -2434,7 +2446,7 @@ class Orchestrator( } val wait = Wait.verify(projectId, issue.id, issue.identifier, attemptId, runId, clock.now(), to, kind?.name) return waitingFor(wait, write = true, endOnCancel = { executions[issue.id]?.stop != null }) { - val passed = verification.verify().also { submitted = it } + val passed = buildGate.withBuild(logContext()) { verification.verify() }.also { submitted = it } progress.verified(verification.failingChecks) verdicts = true refuted = verification.findings @@ -4801,7 +4813,9 @@ class Orchestrator( verification.prepare() if (!verification.hasChecks) return RecheckOutcome.Skipped } - if (verification.verify()) return RecheckOutcome.Passed + // bl-188: the full rerun is a build and waits for the build gate; the diff policy pass alone builds nothing. + val passed = if (diffPolicyOnly) verification.verify() else buildGate.withBuild(context) { verification.verify() } + if (passed) return RecheckOutcome.Passed return RecheckOutcome.Failed(verification.unverified, verification.findings?.text) } @@ -4966,7 +4980,8 @@ class Orchestrator( try { waitingFor(wait, write = false, endOnCancel = { false }) { record(ResultSubmitted, mapOf(Results.TO to checkNotNull(to), Results.RESTORED to "true")) - val failure = if (verification.verify()) verification.deliver(to) else null + val passed = buildGate.withBuild(context) { verification.verify() } + val failure = if (passed) verification.deliver(to) else null // A refuted rerun hands its findings to the issue's next attempt, like an attempt's (m2-06). verification.findings?.let { verifyFindings[wait.issueId] = it.text } // An unverified rerun parks the issue before its wait ends, like an attempt's (m2-08). @@ -5164,6 +5179,9 @@ class Orchestrator( /** The operator log event of a pause of the delivery queue and its resume (bl-175). */ const val DELIVERY_QUEUE = "delivery_queue" + /** bl-188: a build that waits for room in the build gate. */ + const val BUILD_GATE = "build_gate" + /** The values of the verdict that ends each verification (m2-05). */ const val VERIFIED = Verification.VERIFIED const val REFUTED = Verification.REFUTED diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt new file mode 100644 index 0000000..d643044 --- /dev/null +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt @@ -0,0 +1,184 @@ +package loop.core.orchestrator + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import loop.api.AttemptContext +import loop.api.ProjectId +import loop.api.Redactor +import loop.api.RunId +import loop.api.SecretRedactor +import loop.core.log.KeyValueLog +import loop.core.workflow.AgentConfig +import loop.core.workflow.CheckConfig +import loop.core.workflow.DeliveryConfig +import loop.core.workflow.DeliveryPolicy +import loop.core.workflow.HooksConfig +import loop.core.workflow.KindConfig +import loop.core.workflow.KindsConfig +import loop.core.workflow.PreflightCheck +import loop.core.workflow.PreflightResult +import loop.core.workflow.WorkflowConfig +import loop.core.workflow.WorkflowFile +import loop.core.workflow.commandRunner +import loop.core.workflow.workflowHash +import loop.core.workspace.WorkspaceManager +import loop.core.workspace.Workspaces +import java.nio.file.Path +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * bl-188: the attempts' verification builds pass the build gate, so two attempts that hold agent slots never build at + * once beyond `agent.max_concurrent_verifications`, and a reload that lowers the cap holds the builds not started yet. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class BuildGateOrchestratorTest { + private val root: Path = createTempDirectory("loop-build-gate").toRealPath() + private val logLines = mutableListOf() + + private fun workflow( + maxConcurrentAgents: Int, + maxConcurrentVerifications: Int? = null, + ): WorkflowFile { + // The text only gives each config its own hash, so a changed one reloads. + val text = "agents $maxConcurrentAgents, verifications $maxConcurrentVerifications" + return WorkflowFile( + config = + WorkflowConfig( + agent = + AgentConfig( + maxConcurrentAgents = maxConcurrentAgents, + maxConcurrentVerifications = maxConcurrentVerifications, + maxTurns = 1, + ), + kinds = + KindsConfig( + KindConfig(listOf(CheckConfig.Command("./gradlew build")), delivery = DeliveryConfig(DeliveryPolicy.Auto)), + ), + ), + path = root.resolve("WORKFLOW.md"), + trackerKind = "files", + trackerDir = root.resolve(".loop/issues"), + activeStates = listOf("todo", "in_progress"), + terminalStates = listOf("done", "canceled"), + requiredLabels = listOf("ready-for-agent"), + workspaceRoot = root.resolve("workspaces"), + runner = commandRunner("./agent.sh"), + pollingIntervalMs = POLL_MS, + promptTemplate = "Work on {{ issue.identifier }}", + sourceHash = workflowHash(text), + sourceText = text, + ) + } + + private fun TestScope.orchestrator( + tracker: FakeTracker, + runner: FakeRunner, + checks: HeldBuilds, + workflow: () -> WorkflowFile, + ): Orchestrator { + var next = 0 + val clock = SchedulerClock(testScheduler) + return Orchestrator( + workflow = workflow(), + tracker = tracker, + runner = runner, + sink = FakeSink(), + log = KeyValueLog(out = { logLines += it }, clock = clock, redactor = Redactor.NONE), + clock = clock, + workspaces = WorkspaceManager(Workspaces(workflow().workspaceRoot), HooksConfig(), FakeHookRunner()), + newId = { "a${++next}" }, + runId = RunId("r1"), + projectId = PROJECT, + launcher = root.resolve("install/bin/loop"), + loopHome = root.resolve("home"), + hostPath = "/usr/bin", + preflight = PreflightCheck { PreflightResult.Ok(workflow()) }, + parked = FakeParkedIssues(), + redactor = SecretRedactor(), + secretsOf = { emptyMap() }, + checkRunnerFor = { checks }, + ) + } + + /** A runner whose one turn queues `loop tool move review`, once [ready] lets the issue's turn go on. */ + private fun submitting(ready: (AttemptContext) -> CompletableDeferred? = { null }): FakeRunner = + FakeRunner { ctx, _ -> + flow { + ready(ctx)?.await() + ToolRequestQueue(Path.of(checkNotNull(ctx.env["LOOP_TOOL_CONFIG"])).parent).enqueue(ToolRequest.Move("review")) + emitAll(succeedingTurn()) + } + } + + private fun HeldBuilds.issues(): List = started.map { it.fileName.toString() } + + @Test + fun `with two agent slots and one verification slot two attempts that submit at once never build together`() = + runTest { + val tracker = FakeTracker(listOf(issue("bl-1"), issue("bl-2"))) + val runner = submitting() + val checks = HeldBuilds() + val job = launch { orchestrator(tracker, runner, checks) { workflow(2, maxConcurrentVerifications = 1) }.runUntilCancelled() } + runCurrent() + + assertEquals(2, runner.calls.size, "both attempts hold an agent slot") + assertEquals(listOf("bl-1"), checks.issues()) + assertTrue(logLines.any { "event=build_gate" in it && "issue_identifier=bl-2" in it && "1 ahead" in it }, logLines.joinToString("\n")) + + checks.releaseNext() + runCurrent() + assertEquals(listOf("bl-1", "bl-2"), checks.issues()) + + checks.releaseNext() + runCurrent() + assertEquals(1, checks.most) + assertEquals(setOf("id-bl-1" to "review", "id-bl-2" to "review"), tracker.moves.toSet()) + job.cancelAndJoin() + } + + @Test + fun `a reload that lowers the cap during one build holds a build submitted afterwards until the first ends`() = + runTest { + var current = workflow(2) + val tracker = FakeTracker(listOf(issue("bl-1"), issue("bl-2"))) + val second = CompletableDeferred() + val runner = submitting { ctx -> second.takeIf { ctx.issue.identifier == "bl-2" } } + val checks = HeldBuilds() + val job = launch { orchestrator(tracker, runner, checks) { current }.runUntilCancelled() } + runCurrent() + assertEquals(2, runner.calls.size, "both attempts launched under the cap of 2") + assertEquals(listOf("bl-1"), checks.issues()) + + current = workflow(1) + advanceTimeBy(POLL_MS) + runCurrent() + second.complete(Unit) + runCurrent() + assertEquals(listOf("bl-1"), checks.issues(), "the lowered cap holds the second build") + + checks.releaseNext() + runCurrent() + assertEquals(listOf("bl-1", "bl-2"), checks.issues()) + checks.releaseNext() + runCurrent() + assertEquals(1, checks.most) + assertEquals(setOf("id-bl-1" to "review", "id-bl-2" to "review"), tracker.moves.toSet()) + job.cancelAndJoin() + } + + private companion object { + const val POLL_MS = 1000L + val PROJECT = ProjectId("p1") + } +} diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/HeldBuilds.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/HeldBuilds.kt new file mode 100644 index 0000000..2c823c5 --- /dev/null +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/HeldBuilds.kt @@ -0,0 +1,49 @@ +package loop.core.orchestrator + +import kotlinx.coroutines.CompletableDeferred +import loop.core.verify.CheckResult +import loop.core.verify.CheckRunner +import loop.core.workflow.CheckConfig +import java.nio.file.Path + +/** + * bl-188: a check runner that holds each run until a test releases it, and counts the runs in flight at once, so a test + * can see whether the build gate ever let two builds overlap. Every run passes with [exitCode]. + */ +class HeldBuilds( + private val exitCode: Int = 0, +) : CheckRunner { + /** The workspace of each run, in the order the runs started. */ + val started = mutableListOf() + + /** The runs in flight now, and the most ever in flight at once. */ + var running = 0 + private set + var most = 0 + private set + + private val held = ArrayDeque>() + + override suspend fun run( + check: CheckConfig, + cwd: Path, + env: Map, + ): CheckResult { + val release = CompletableDeferred() + held.addLast(release) + started.add(cwd) + running++ + most = maxOf(most, running) + try { + release.await() + } finally { + running-- + } + return CheckResult(exitCode, timedOut = false, durationMs = 1200) + } + + /** Lets the oldest held run end. */ + fun releaseNext() { + held.removeFirst().complete(Unit) + } +} From faa13624c633cb4fabac879beb2832f18baab54c Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:23:44 +0000 Subject: [PATCH 4/6] bl-188: a restored verify rerun and a merge check share the build gate --- .../MergeCheckOrchestratorTest.kt | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt index 607132f..8569365 100644 --- a/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy @@ -2863,6 +2864,50 @@ class MergeCheckOrchestratorTest { assertEquals(0, runner.calls.size, "no attempt without the parked read") } + @Test + fun `a restored verify rerun and a merge check never build at the same time with capacity 1 (bl-188)`() = + runTest { + val verified = verifiedWorktree() + secondWorktree() + val base = baseCommit() + val tracker = FakeTracker(listOf(issue("t-1"), issue("t-2"))) + val remote = + FakeRemote().apply { + bases += base + pulls["loop/t-1"] = PullRequest(7, "https://github.com/acme/widgets/pull/7", created = false, headSha = verified) + } + val verify = + WaitingIssue( + projectId = PROJECT, + issueId = "id-t-2", + identifier = "t-2", + reason = WaitReason.Verify, + attemptId = AttemptId("dead2"), + runId = RunId("r0"), + since = FIXED_NOW, + data = mapOf(WaitKeys.TO to "review"), + ) + val waiting = FakeWaitingIssues(mergeWait(clean(verified)), verify) + val checks = HeldBuilds() + val sink = FakeSink() + val job = launch { orchestrator(tracker, remote, waiting, sink, workflow(maxAgents = 1), checks).runUntilCancelled() } + runCurrent() + + assertEquals(1, sink.all(MergeCheckStarted.name).size, "the merge check started beside the restored rerun") + assertEquals(1, checks.started.size, "only one of the two builds runs") + checks.releaseNext() + runCurrent() + assertEquals(2, checks.started.size, "the other build starts once the first ended") + assertEquals(setOf(workspace, secondWorkspace), checks.started.toSet()) + checks.releaseNext() + runCurrent() + + assertEquals(1, checks.most) + assertEquals(1, remote.merges.size, "the merge check passed and merged") + assertEquals(WaitReason.Approval, waiting.records.values.single().reason, "the rerun verified t-2, which waits for approval") + job.cancelAndJoin() + } + private companion object { val PROJECT = ProjectId("p1") const val HUMAN_TOUCH_MOVE = "move" From 34933a629d098fd3ba06db99cc7ff6046cae58ba Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:25:05 +0000 Subject: [PATCH 5/6] bl-188: restored verify waits rerun their builds one at a time after a restart --- .../loop/core/orchestrator/Orchestrator.kt | 9 ++- .../orchestrator/BuildGateOrchestratorTest.kt | 5 +- .../MergeCheckOrchestratorTest.kt | 10 ++- .../orchestrator/OrchestratorRestartTest.kt | 70 +++++++++++++++++++ 4 files changed, 90 insertions(+), 4 deletions(-) diff --git a/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt b/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt index 7e96147..2bbe499 100644 --- a/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt +++ b/spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt @@ -601,7 +601,14 @@ class Orchestrator( */ private val buildGate = BuildGate({ effective.config.agent.buildCapacity }) { context, ahead -> - log.log(LogLevel.INFO, BUILD_GATE, LogOutcome.SCHEDULED, context, mapOf("ahead" to ahead), "verification waits for a build slot ($ahead ahead)") + log.log( + LogLevel.INFO, + BUILD_GATE, + LogOutcome.SCHEDULED, + context, + mapOf("ahead" to ahead), + "verification waits for a build slot ($ahead ahead)", + ) } /** True once [restoreWaiting] resumed the waits a previous process left. */ diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt index d643044..276d5b6 100644 --- a/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateOrchestratorTest.kt @@ -134,7 +134,10 @@ class BuildGateOrchestratorTest { assertEquals(2, runner.calls.size, "both attempts hold an agent slot") assertEquals(listOf("bl-1"), checks.issues()) - assertTrue(logLines.any { "event=build_gate" in it && "issue_identifier=bl-2" in it && "1 ahead" in it }, logLines.joinToString("\n")) + assertTrue( + logLines.any { "event=build_gate" in it && "issue_identifier=bl-2" in it && "1 ahead" in it }, + logLines.joinToString("\n"), + ) checks.releaseNext() runCurrent() diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt index 8569365..bc8ab15 100644 --- a/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/MergeCheckOrchestratorTest.kt @@ -6,9 +6,9 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy @@ -2904,7 +2904,13 @@ class MergeCheckOrchestratorTest { assertEquals(1, checks.most) assertEquals(1, remote.merges.size, "the merge check passed and merged") - assertEquals(WaitReason.Approval, waiting.records.values.single().reason, "the rerun verified t-2, which waits for approval") + assertEquals( + WaitReason.Approval, + waiting.records.values + .single() + .reason, + "the rerun verified t-2, which waits for approval", + ) job.cancelAndJoin() } diff --git a/spec-core/src/test/kotlin/loop/core/orchestrator/OrchestratorRestartTest.kt b/spec-core/src/test/kotlin/loop/core/orchestrator/OrchestratorRestartTest.kt index 00c3be7..b5cbe05 100644 --- a/spec-core/src/test/kotlin/loop/core/orchestrator/OrchestratorRestartTest.kt +++ b/spec-core/src/test/kotlin/loop/core/orchestrator/OrchestratorRestartTest.kt @@ -21,8 +21,16 @@ import loop.api.RetryState import loop.api.RunId import loop.api.RunnerEvent import loop.api.SecretRedactor +import loop.api.WaitReason +import loop.api.WaitingIssue import loop.core.log.KeyValueLog +import loop.core.verify.CheckRunner import loop.core.workflow.AgentConfig +import loop.core.workflow.CheckConfig +import loop.core.workflow.DeliveryConfig +import loop.core.workflow.DeliveryPolicy +import loop.core.workflow.KindConfig +import loop.core.workflow.KindsConfig import loop.core.workflow.RetriesConfig import loop.core.workflow.WorkflowConfig import loop.core.workflow.WorkflowFile @@ -30,6 +38,7 @@ import loop.core.workflow.commandRunner import loop.core.workspace.WorkspaceManager import loop.core.workspace.Workspaces import java.io.IOException +import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.createTempDirectory import kotlin.test.Test @@ -81,6 +90,8 @@ class OrchestratorRestartTest { runId: RunId = RunId("r1"), idPrefix: String = "a", parked: FakeParkedIssues = FakeParkedIssues(), + checks: CheckRunner = CheckRunner.NONE, + waiting: FakeWaitingIssues = FakeWaitingIssues(), ): Orchestrator { var next = 0 val clock = SchedulerClock(testScheduler) @@ -103,6 +114,8 @@ class OrchestratorRestartTest { secretsOf = { emptyMap() }, retryStates = retryStates, claims = claims, + checkRunnerFor = { checks }, + waiting = waiting, ) } @@ -110,6 +123,63 @@ class OrchestratorRestartTest { private fun FakeSink.ofKind(kind: String): List = events.filter { it.kind == kind } + @Test + fun `three restored verify waits with max_concurrent_agents 1 rerun their builds one at a time in stored order (bl-188)`() = + runTest { + val identifiers = listOf("bl-3", "bl-1", "bl-2") + val tracker = FakeTracker(identifiers.map { issue(it) }) + val stored = + identifiers.mapIndexed { n, identifier -> + Files.createDirectories(root.resolve("workspaces/$identifier")) + WaitingIssue( + projectId = PROJECT, + issueId = "id-$identifier", + identifier = identifier, + reason = WaitReason.Verify, + attemptId = AttemptId("dead$n"), + runId = RunId("r0"), + since = FIXED_NOW, + data = mapOf("to" to "review"), + ) + } + val waiting = FakeWaitingIssues(*stored.toTypedArray()) + val checks = HeldBuilds() + val base = workflow() + val workflow = + base.copy( + config = + base.config.copy( + agent = base.config.agent.copy(maxConcurrentAgents = 1), + kinds = + KindsConfig( + KindConfig( + listOf(CheckConfig.Command("./gradlew build")), + delivery = DeliveryConfig(DeliveryPolicy.Auto), + ), + ), + ), + ) + val job = + launch { + orchestrator(tracker, failingRunner(), FakeRetryStates(), workflow = workflow, checks = checks, waiting = waiting) + .runUntilCancelled() + } + runCurrent() + + for (count in 1..3) { + assertEquals(count, checks.started.size, "build $count runs alone") + assertEquals(1, checks.running) + checks.releaseNext() + runCurrent() + } + + assertEquals(identifiers, checks.started.map { it.fileName.toString() }) + assertEquals(1, checks.most) + assertEquals(identifiers.map { "id-$it" }, tracker.moves.map { it.first }, "each rerun verified and applied its move") + assertEquals(emptyMap(), waiting.records) + job.cancelAndJoin() + } + @Test fun `a failure writes the queued retry and the failure count to the store`() = runTest { From ad80768afd6b61ec355454d4d3c8c7f4442926bf Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:25:54 +0000 Subject: [PATCH 6/6] bl-188: document the build gate and max_concurrent_verifications --- docs/self-hosting.md | 2 +- docs/spec-decisions.md | 18 +++++++++++++++++- .../kotlin/loop/core/orchestrator/SlotPlan.kt | 8 +++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/self-hosting.md b/docs/self-hosting.md index cd4aefa..c23f9b3 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -177,7 +177,7 @@ What the `code` kind does: - **Readiness.** `ready: { require_sections: [Acceptance criteria] }`. An issue with no `## Acceptance criteria` section, or an empty one, is not dispatched: Loop comments once and adds `needs-info`. - **Checks.** `diff_policy` (the guards below), `./gradlew --no-daemon build` and `acceptance_commands`, the runnable criteria of the issue (see [`agents/issue-tracker.md`](agents/issue-tracker.md#runnable-criteria)). `--no-daemon` keeps host side checks off every agent's Gradle daemon (bl-01). - **Delivery.** Conditional auto merge (m2-28): Loop pushes the verified commit to `loop/`, opens a pull request on `soulesidibe/Loop` with the evidence summary, merges the current `main` into the branch and reruns the checks on the result (the merge check), waits for the GitHub Actions runs of the merged head (see [the CI wait](#the-ci-wait)), then asks `claude-sonnet-5-5` for a merge risk review. It merges and moves the issue to `done` only when every hard condition holds and the band is `low`. Otherwise it comments why and the issue waits as `Waiting(approval)`: run `loop approve ` to merge after a fresh merge check, or `loop send-back --reason ""` (m4-32) to send it back. The send back comments the reason, the next attempt runs in the same workspace with the reason as its verify findings, the pull request stays open and the next delivery updates it. It takes no `max_attempts` slot, so no `loop resume` follows. A red CI lands in the same unapproved wait, and `loop send-back` sends it back the same way. -- **Slots.** `agent.max_concurrent_agents` caps the agent Attempts and the merge checks, not the merge risk reviewer. Since bl-173 the reviewer's model session runs in the merge phase, which holds no agent slot, so it can run while Attempts hold every agent slot. Only a machine slot, when `machine.max_concurrent_agents` is set in `/config.yaml`, and the delivery queue, which merges one pull request at a time, bound it. +- **Slots.** `agent.max_concurrent_agents` caps the agent Attempts and the merge checks, not the merge risk reviewer. Since bl-188 the builds have their own cap: at most `agent.max_concurrent_verifications` verification and merge check builds run at once, `agent.max_concurrent_agents` when it is unset, whether an Attempt submitted, a merge check started or a restart resumed a stored `verify` wait. The others wait their turn, oldest first, and a reload that lowers the cap holds the builds not started yet. Since bl-173 the reviewer's model session runs in the merge phase, which holds no agent slot, so it can run while Attempts hold every agent slot. Only a machine slot, when `machine.max_concurrent_agents` is set in `/config.yaml`, and the delivery queue, which merges one pull request at a time, bound it. `loop trace ` shows the path: the verdict, `pull_request_opened`, `merge_risk_assessed`, then `pull_request_merged` or `auto_merge_fallback` with the failed conditions. diff --git a/docs/spec-decisions.md b/docs/spec-decisions.md index 4f53e2d..3793236 100644 --- a/docs/spec-decisions.md +++ b/docs/spec-decisions.md @@ -439,6 +439,7 @@ Both behave like the spec's workflow file errors: they block dispatch until fixe - `polling.interval_ms` - `hooks.timeout_ms` - `agent.max_concurrent_agents` + - `agent.max_concurrent_verifications` (bl-188, optional, see [Build gate](#build-gate-extension-bl-188)) - `agent.max_turns` - `agent.max_wake_turns` (m4-03, see [Wake turns](#wake-turns-extension-m4-03)) - `agent.max_retry_backoff_ms` @@ -455,7 +456,7 @@ Both behave like the spec's workflow file errors: they block dispatch until fixe - **Per state concurrency:** in `agent.max_concurrent_agents_by_state`, state names are trimmed and lowercased, and entries that are not positive integers are ignored, not rejected (17.1). - **Per tracker concurrency (m4-15):** `agent.max_concurrent_agents_by_tracker` is a map of tracker id to a positive integer. Unlike the per state caps, a key that is no tracker id of the workflow, a value below 1 or not an integer, and a key that is not a map fail preflight with `invalid_config`: `agent.max_concurrent_agents_by_tracker.gh names no tracker of this workflow, use one of local, side`. See [per tracker concurrency limit](#per-tracker-concurrency-limit-and-a-quieter-retry-requeue-extension-m4-15). - **`codex.command`:** kept as the raw shell string, never expanded and not checked in M1, so `codex.command: ""` passes. The command of the selected runner is checked instead (see [preflight](#preflight-on-each-tick-clarification-of-63-m1-03)). -- **Defaults:** a missing optional key takes the spec default: `polling.interval_ms` 30000, `agent.max_concurrent_agents` 10, `agent.max_turns` 20, `agent.max_wake_turns` 30 (m4-03), `agent.max_retry_backoff_ms` 300000, `hooks.timeout_ms` 60000, `codex.stall_timeout_ms` 300000, `codex.turn_timeout_ms` 3600000, `codex.read_timeout_ms` 5000, `codex.command` `codex app-server`, `budgets.token_threshold_every` 10000000, `context.soft_limit` 0.20, `context.hard_limit` 0.21 (0.25 before m4-02, see [default limits and unknown windows](#default-limits-and-unknown-windows-extension-m4-02)), `context.prompt_limit` 0.05, `context.tool_output_tokens` 2000, `context.max_rotations` 5, `context.windows` `anthropic/claude-opus-5-5: 1000000` and, since m4-02, `openai/gpt-6.1-sol: 475000`, `observability.retention_days` 90. `budgets.per_attempt_tokens` has no default: absent means no ceiling (m1-38). No other spend budget has one either (m2-20): absent means no budget. +- **Defaults:** a missing optional key takes the spec default: `polling.interval_ms` 30000, `agent.max_concurrent_agents` 10, `agent.max_concurrent_verifications` unset, which caps builds at `agent.max_concurrent_agents` (bl-188), `agent.max_turns` 20, `agent.max_wake_turns` 30 (m4-03), `agent.max_retry_backoff_ms` 300000, `hooks.timeout_ms` 60000, `codex.stall_timeout_ms` 300000, `codex.turn_timeout_ms` 3600000, `codex.read_timeout_ms` 5000, `codex.command` `codex app-server`, `budgets.token_threshold_every` 10000000, `context.soft_limit` 0.20, `context.hard_limit` 0.21 (0.25 before m4-02, see [default limits and unknown windows](#default-limits-and-unknown-windows-extension-m4-02)), `context.prompt_limit` 0.05, `context.tool_output_tokens` 2000, `context.max_rotations` 5, `context.windows` `anthropic/claude-opus-5-5: 1000000` and, since m4-02, `openai/gpt-6.1-sol: 475000`, `observability.retention_days` 90. `budgets.per_attempt_tokens` has no default: absent means no ceiling (m1-38). No other spend budget has one either (m2-20): absent means no budget. - **Hooks:** `hooks.*` are parsed and validated in m1-03 and run from m1-04. `hooks.on_token_threshold` (m1-38) and `hooks.on_budget_warning` (m2-20) are Loop's own optional hooks. ### Command runner shell (deviation from 10.1, m1-02) @@ -1727,6 +1728,8 @@ kinds: The phase a background run starts in decides its slot. A run started in phase `check` keeps its slot through the merge that follows it in the same run under `ci: none`, and through a new round on a moved base. A run started in phase `merge`, after a green CI wait or a merge tried again, holds none, and when the base moved it stops at the new round's phase `check`, which a later tick starts on a free slot. +Since bl-188 the merge check's rerun of the checks also passes the [build gate](#build-gate-extension-bl-188) before it builds, so it waits there behind other verification builds while it holds its agent slot. + So `agent.max_concurrent_agents` caps the agent attempts and the merge checks, not the auto merge reviewer. The reviewer's model session runs in phase `merge`, which asks for no agent slot of its own, so it is bounded only by the machine slot of m3-16, when a machine cap is set, and by the delivery queue below, whose head alone advances. The machine slot is claimed for phase `check` and for a merge phase approved by the auto policy, whose gate runs the merge risk reviewer; a merge phase approved by a human claims none. The machine slot and the running check are taken before the background job is created, so the job starts atomically (bl-180): on a scope cancelled between the claim and the start, its body still runs, stops at once, and its `finally` releases the machine slot and ends the running check, instead of leaving the slot row until the pid liveness rule clears it. @@ -3482,6 +3485,19 @@ Story 138, PLAN 10.4. Lane A, not gating the M4 exit. It calls the verification Tests: `cli/src/test/kotlin/loop/cli/ReplayCommandTest.kt` (a kept workspace verified on a copy, unchanged afterwards, with the store's events compared before and after; a gone workspace rebuilt as a worktree and removed; a changed workspace with uncommitted changes and a gone `tree:` folder, exit 4 naming both fingerprints; no verdict; both modes; a SIGTERM during a check through the launcher, which stops the check, removes the copy and its worktree registration and records nothing; a `resource:` check that does not run), `spec-core/src/test/kotlin/loop/core/replay/ReplaySitesTest.kt`, `VerificationReplayTest.kt` and `RecordedVerdictTest.kt`. +### Build gate (extension, bl-188) + +Seen on Loop's own run of 2026-11-23: the agent slots capped the launches of attempts and merge checks, not the builds they ran. An attempt kept its slot while it verified, so a reload that lowered `agent.max_concurrent_agents` left three Gradle builds running at once, a resubmit after a killed build verified again at once beside the others, and a restart resumed every stored `verify` wait at the same tick, since a restored wait takes no slot (bl-173). One restart ran four builds with the cap at 1. + +- **The gate.** Every verification build and merge check build passes the project's build gate (`loop.core.orchestrator.BuildGate`) before it runs: an attempt's verification once its agent submitted, the merge check's rerun of the checks, and the rerun of a restored `verify` wait. A verification with no checks, which gives `unverified` at once, and the `diff_policy` only pass of a merge check whose base is already in the branch (bl-32) build nothing and skip it. +- **Capacity.** `agent.max_concurrent_verifications`, a positive integer, else `agent.max_concurrent_agents`. A separate key, since agent turns are mostly model time and run well in parallel while builds do not; unset, a workflow behaves as before with its builds capped at the agent cap. A value that is not a positive integer fails preflight with `invalid_config`: `agent.max_concurrent_verifications must be a positive integer, got 0`. +- **Queue.** A build that finds no room waits, first in, first out, and logs one INFO line, `event=build_gate outcome=scheduled ahead=` with the issue context and the reason `verification waits for a build slot ( ahead)`, `` counting the builds running and queued before it. No event is recorded and `loop status` shows nothing new. +- **Live capacity.** The capacity is read from the effective workflow on every admission. A reload that lowers it starts no new build until the running ones end below it, and never stops a build already running. A reload that raises it admits queued builds at the start of the next `dispatch`. +- **Cancel and failure.** Waiting in the gate can be cancelled, by a reconciliation stop or `loop stop`; the waiter leaves the queue and takes no room. The room of a build is given back when it ends, on an exception or a cancellation too. +- **Agent slots unchanged.** A restored wait still takes no agent slot and no per tracker slot (bl-173), only its build passes the gate. A merge check keeps its agent slot while it waits in the gate, which cannot deadlock, since no build needs an agent slot to end. The gate is per project: the machine slots of `/config.yaml` do not count builds. + +Tests: `spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt` (order, a lowered and a raised capacity, a cancelled waiter, a failed build), `BuildGateOrchestratorTest.kt` (two attempts with one verification slot, a reload that lowers the cap during a build), in `OrchestratorRestartTest.kt` `three restored verify waits with max_concurrent_agents 1 rerun their builds one at a time in stored order (bl-188)`, in `MergeCheckOrchestratorTest.kt` `a restored verify rerun and a merge check never build at the same time with capacity 1 (bl-188)`, and `spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt`. + ## Spec changes log Each change of the pinned spec commit adds one entry, newest first: the date, the old and new commits, what changed upstream, and what Loop changed in response. diff --git a/spec-core/src/main/kotlin/loop/core/orchestrator/SlotPlan.kt b/spec-core/src/main/kotlin/loop/core/orchestrator/SlotPlan.kt index b9edf14..ec83b07 100644 --- a/spec-core/src/main/kotlin/loop/core/orchestrator/SlotPlan.kt +++ b/spec-core/src/main/kotlin/loop/core/orchestrator/SlotPlan.kt @@ -8,8 +8,9 @@ import kotlin.time.Instant /** * What holds an agent slot of the project now: the normalized state of each running attempt, as reconciliation * last read it, and the number of running merge checks, phase `check` work only. A restored wait's checks and a - * delivery's merge phase take no slot (bl-173). [attemptTrackers] holds the tracker id of each running attempt, for the - * per tracker limits (m4-15); an attempt of no tracker of the workflow is left out. + * delivery's merge phase take no slot (bl-173). The builds are capped apart: every verification build and merge check + * build, a restored wait's included, passes the [BuildGate] (bl-188). [attemptTrackers] holds the tracker id of each + * running attempt, for the per tracker limits (m4-15); an attempt of no tracker of the workflow is left out. */ internal data class SlotUse( val attemptStates: List, @@ -36,7 +37,8 @@ internal data class AttemptSlots( * `agent.max_concurrent_agents_by_tracker` ([TrackerSlots]) cap attempt launches only, and at most one merge check runs * at a time. Step one, [mergeCheckFits], runs first in the tick, so a * merge check takes the last free slot ahead of due retries and candidates. Step two, [attempts], fills what is left. - * A delivery's merge phase asks neither step: it holds no agent slot (bl-173). + * A delivery's merge phase asks neither step: it holds no agent slot (bl-173). A slot is checked when work starts only, + * so the builds an attempt or a merge check runs later are capped by the [BuildGate] instead (bl-188). */ internal object SlotPlan { /** Step one: whether a merge check, phase `check` work, may start now. */