Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Work a loop fire's batch through a bounded pool (maxConcurrentItems) (#2091)

Paul Capriolo110b7d61c87b
diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.ts
index acc365b2c..046ff9933 100644
--- a/src/api/routes/loops.ts
+++ b/src/api/routes/loops.ts
@@ -166,7 +166,7 @@ function governorFromBody(value: unknown): NumericBody<Loop["governor"]> {
function capsFromBody(value: unknown): NumericBody<Loop["caps"]> {
if (value === undefined) return {};
if (!isObj(value)) return { invalidField: "caps" };
- const numbers = ["maxItemsPerFire", "maxOpenOutputs", "maxItemAttempts"] as const;
+ const numbers = ["maxItemsPerFire", "maxConcurrentItems", "maxOpenOutputs", "maxItemAttempts"] as const;
const caps: NonNullable<Loop["caps"]> = {};
for (const key of numbers) {
const raw = value[key];
diff --git a/src/loops/loop-fire.ts b/src/loops/loop-fire.ts
index b9caecf1d..506f953eb 100644
--- a/src/loops/loop-fire.ts
+++ b/src/loops/loop-fire.ts
@@ -100,6 +100,10 @@ function loopFireThreadRef(loopId: string, fireKey: string): string {
return `loop:${loopId}:fire:${hashId([fireKey], 12)}`;
}
+function loopFireItemThreadRef(loopId: string, fireKey: string, itemId: string): string {
+ return `${loopFireThreadRef(loopId, fireKey)}:item:${hashId([itemId], 12)}`;
+}
+
function loopItemThreadRef(loopId: string, itemId: string): string {
return `loop:${loopId}:item:${hashId([itemId], 12)}`;
}
@@ -685,7 +689,7 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
const maxAttempts = loop.caps?.maxItemAttempts ?? DEFAULT_MAX_ATTEMPTS;
const grants = await deps.grants.byLoop(loopId);
const workReplies = new Map<string, string>();
- let members: LoopItem[] | undefined;
+ let members: Promise<LoopItem[]> | undefined;
let held: Set<string> | undefined;
let summary: FireSummary;
@@ -704,13 +708,14 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
},
triage: () => triage(loop, fireKey, threadRef),
work: async ({ item, guidance }) => {
- members ??= consolidates(loop) ? await deps.items.byLoop(loop.id) : [];
- const heldIds = (held ??= heldMembers(loop, members));
- const similar = members.filter((member) => heldIds.has(member.id) && member.triage?.groupId === item.id);
+ const all = await (members ??= consolidates(loop) ? deps.items.byLoop(loop.id) : Promise.resolve([]));
+ const heldIds = (held ??= heldMembers(loop, all));
+ const itemThreadRef = loopFireItemThreadRef(loopId, fireKey, item.id);
+ const similar = all.filter((member) => heldIds.has(member.id) && member.triage?.groupId === item.id);
const outcome = await stageTurn(
loop,
`${fireKey}:work:${item.id}:${item.attempts}`,
- threadRef,
+ itemThreadRef,
workPrompt(loop, item, guidance, similar),
);
const failure = stageFailure("work", outcome);
@@ -727,14 +732,14 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
{ expectedClaimToken: item.claimToken! },
);
workReplies.set(item.id, outcome.reply ?? "");
- return { runId: outcome.sessionId ?? `${threadRef}:work:${item.id}` };
+ return { runId: outcome.sessionId ?? `${itemThreadRef}:work` };
},
captureOutputs: async ({ item }) => parseOutputs(workReplies.get(item.id) ?? ""),
evaluate: async ({ item, attempt }) => {
const outcome = await stageTurn(
loop,
`${fireKey}:judge:${item.id}:${attempt}`,
- threadRef,
+ loopFireItemThreadRef(loopId, fireKey, item.id),
judgePrompt(loop, item),
);
const failure = stageFailure("judge", outcome);
diff --git a/src/loops/runner.ts b/src/loops/runner.ts
index b24b49696..f7b9c0ff1 100644
--- a/src/loops/runner.ts
+++ b/src/loops/runner.ts
@@ -73,6 +73,36 @@ export function fireNeedsAttention(summary: FireSummary): boolean {
);
}
+class ReviewBudget {
+ private inFlight = 0;
+ private readonly cap: number | undefined;
+ private open: number;
+
+ constructor(cap: number | undefined, open: number) {
+ this.cap = cap;
+ this.open = open;
+ }
+
+ get full(): boolean {
+ return this.cap !== undefined && this.open + this.inFlight >= this.cap;
+ }
+
+ admit(): boolean {
+ if (this.full) return false;
+ this.inFlight += 1;
+ return true;
+ }
+
+ release(opened: number): void {
+ this.inFlight -= 1;
+ this.open += opened;
+ }
+
+ reason(): string {
+ return `${this.open} outputs waiting for review`;
+ }
+}
+
export async function runLoopFire(
loop: Loop,
stores: LoopStores,
@@ -83,9 +113,12 @@ export async function runLoopFire(
if (!summary.ran) return summary;
const effectiveMaxAttempts = loop.caps?.maxItemAttempts ?? DEFAULT_MAX_ATTEMPTS;
- const openOutputs = (await stores.outputs.byLoop(loop.id)).filter(unresolvedOutput).length;
- if (loop.caps?.maxOpenOutputs !== undefined && openOutputs >= loop.caps.maxOpenOutputs) {
- summary.throttled = `${openOutputs} outputs waiting for review`;
+ const budget = new ReviewBudget(
+ loop.caps?.maxOpenOutputs,
+ (await stores.outputs.byLoop(loop.id)).filter(unresolvedOutput).length,
+ );
+ if (budget.full) {
+ summary.throttled = budget.reason();
await stores.loops.recordFireOutcome(loop.id, false);
return summary;
}
@@ -107,116 +140,155 @@ export async function runLoopFire(
loop.caps?.maxItemsPerFire,
);
const batch = loop.throttle ? queued.slice(0, Math.max(1, Math.floor(queued.length / 2))) : queued;
- for (const queued of batch) {
- const item = await stores.items.claim(queued.id, undefined, loop.id);
- if (!item) continue;
- const claimToken = item.claimToken!;
- summary.worked += 1;
-
- let autoShippedCount = 0;
- let autoOutputCount = 0;
- try {
- const { runId } = await effects.work({
- loop,
- item,
- ...(item.guidance !== undefined ? { guidance: item.guidance } : {}),
- });
- if (!(await stores.items.recordRun(item.id, runId, claimToken))) continue;
- const artifacts = await effects.captureOutputs({ loop, item, runId });
- const captured: LoopOutput[] = [];
- for (const [ordinal, artifact] of artifacts.entries()) {
- captured.push(
- await stores.outputs.capture({ ...artifact, loopId: loop.id, itemId: item.id, attemptId: runId, ordinal }),
- );
- }
+ const remaining = batch.values();
+ let capped = false;
+ let drained = false;
+ const workers = await Promise.allSettled(
+ Array.from({ length: Math.min(loop.caps?.maxConcurrentItems ?? 1, batch.length) }, async () => {
+ for (;;) {
+ if (!budget.admit()) {
+ capped = true;
+ break;
+ }
+ const next = remaining.next();
+ if (next.done) {
+ budget.release(0);
+ drained = true;
+ break;
+ }
+ const queued = next.value;
+ let item: LoopItem | null;
+ try {
+ item = await stores.items.claim(queued.id, undefined, loop.id);
+ } catch (error) {
+ budget.release(0);
+ throw error;
+ }
+ if (!item) {
+ budget.release(0);
+ continue;
+ }
+ const claimToken = item.claimToken!;
+ summary.worked += 1;
- const held = await stores.items.get(item.id);
- if (held?.status !== "in_progress" || held.claimToken !== claimToken) {
- await stores.outputs.supersedeAttempt(item.id, runId);
- continue;
- }
+ let autoShippedCount = 0;
+ let autoOutputCount = 0;
+ let openedOutputs = 0;
+ try {
+ const { runId } = await effects.work({
+ loop,
+ item,
+ ...(item.guidance !== undefined ? { guidance: item.guidance } : {}),
+ });
+ if (!(await stores.items.recordRun(item.id, runId, claimToken))) continue;
+ const artifacts = await effects.captureOutputs({ loop, item, runId });
+ const captured: LoopOutput[] = [];
+ for (const [ordinal, artifact] of artifacts.entries()) {
+ captured.push(
+ await stores.outputs.capture({
+ ...artifact,
+ loopId: loop.id,
+ itemId: item.id,
+ attemptId: runId,
+ ordinal,
+ }),
+ );
+ }
- const undeclared = undeclaredShipActions(loop, captured);
- if (undeclared.length > 0) {
- summary.undeclaredShipActions.push(...undeclared);
- await stores.outputs.supersedeAttempt(item.id, runId);
- await stores.items.park(item.id, `undeclared ship action: ${undeclared.join(", ")}`, claimToken);
- summary.parked.push(item.id);
- continue;
- }
+ const held = await stores.items.get(item.id);
+ if (held?.status !== "in_progress" || held.claimToken !== claimToken) {
+ await stores.outputs.supersedeAttempt(item.id, runId);
+ continue;
+ }
- const verdict = await effects.evaluate({ loop, item, attempt: item.attempts, runId });
- if (verdict.outcome === "park") {
- await stores.outputs.supersedeAttempt(item.id, runId);
- await stores.items.park(item.id, verdict.reason, claimToken);
- summary.parked.push(item.id);
- continue;
- }
- if (verdict.outcome === "continue") {
- await stores.outputs.supersedeAttempt(item.id, runId);
- await stores.items.returnToWork(item.id, verdict.reason, claimToken);
- summary.continued.push(item.id);
- continue;
- }
+ const undeclared = undeclaredShipActions(loop, captured);
+ if (undeclared.length > 0) {
+ summary.undeclaredShipActions.push(...undeclared);
+ await stores.outputs.supersedeAttempt(item.id, runId);
+ await stores.items.park(item.id, `undeclared ship action: ${undeclared.join(", ")}`, claimToken);
+ summary.parked.push(item.id);
+ continue;
+ }
- if (captured.length === 0) {
- if ((await stores.items.get(item.id))?.proposal) {
- if (await stores.items.markReady(item.id, [], claimToken)) summary.ready.push(item.id);
- } else if (await stores.items.markShipped(item.id, claimToken)) summary.shipped.push(item.id);
- continue;
- }
+ const verdict = await effects.evaluate({ loop, item, attempt: item.attempts, runId });
+ if (verdict.outcome === "park") {
+ await stores.outputs.supersedeAttempt(item.id, runId);
+ await stores.items.park(item.id, verdict.reason, claimToken);
+ summary.parked.push(item.id);
+ continue;
+ }
+ if (verdict.outcome === "continue") {
+ await stores.outputs.supersedeAttempt(item.id, runId);
+ await stores.items.returnToWork(item.id, verdict.reason, claimToken);
+ summary.continued.push(item.id);
+ continue;
+ }
- const markedReady = await stores.items.markReady(
- item.id,
- captured.map((output) => output.id),
- claimToken,
- );
- if (!markedReady) {
- await stores.outputs.supersedeAttempt(item.id, runId);
- continue;
- }
- const ready = await stores.outputs.promoteAttempt(item.id, runId);
- const autoShipped: string[] = [];
- autoOutputCount = ready.filter(
- (output) => decideShip(loop, outputCandidate(output), grants).outcome === "auto",
- ).length;
- for (const output of ready) {
- if (decideShip(loop, outputCandidate(output), grants).outcome !== "auto") continue;
- const currentLoop = effects.authorizeAutoShip ? await effects.authorizeAutoShip(output) : loop;
- if (!currentLoop) continue;
- const shipped = await effects.ship({ loop: currentLoop, output });
- if (shipped?.state === "shipped") {
- autoShipped.push(output.id);
- autoShippedCount += 1;
+ if (captured.length === 0) {
+ if ((await stores.items.get(item.id))?.proposal) {
+ if (await stores.items.markReady(item.id, [], claimToken)) summary.ready.push(item.id);
+ } else if (await stores.items.markShipped(item.id, claimToken)) summary.shipped.push(item.id);
+ continue;
+ }
+
+ const markedReady = await stores.items.markReady(
+ item.id,
+ captured.map((output) => output.id),
+ claimToken,
+ );
+ if (!markedReady) {
+ await stores.outputs.supersedeAttempt(item.id, runId);
+ continue;
+ }
+ const ready = await stores.outputs.promoteAttempt(item.id, runId);
+ openedOutputs = ready.length;
+ autoOutputCount = ready.filter(
+ (output) => decideShip(loop, outputCandidate(output), grants).outcome === "auto",
+ ).length;
+ for (const output of ready) {
+ if (decideShip(loop, outputCandidate(output), grants).outcome !== "auto") continue;
+ const currentLoop = effects.authorizeAutoShip ? await effects.authorizeAutoShip(output) : loop;
+ if (!currentLoop) continue;
+ const shipped = await effects.ship({ loop: currentLoop, output });
+ if (shipped?.state === "shipped") {
+ autoShippedCount += 1;
+ openedOutputs -= 1;
+ }
+ }
+ if (openedOutputs === 0) {
+ await stores.items.markShipped(item.id);
+ summary.shipped.push(item.id);
+ } else {
+ summary.ready.push(item.id);
+ }
+ } catch (error) {
+ if (autoShippedCount === 0) openedOutputs = 0;
+ const reason = error instanceof Error ? error.message : String(error);
+ summary.failures.push(`${item.sourceKey}: ${reason}`);
+ if (autoShippedCount > 0) {
+ const partialReason = `partial auto-ship: ${autoShippedCount} of ${autoOutputCount} actions completed before failure — needs human review`;
+ await stores.items.park(item.id, partialReason);
+ summary.parked.push(item.id);
+ continue;
+ }
+ const latestRunId = (await stores.items.get(item.id))?.runIds.at(-1);
+ if (latestRunId) await stores.outputs.supersedeAttempt(item.id, latestRunId);
+ const exhausted = item.attempts >= effectiveMaxAttempts;
+ if (exhausted) {
+ await stores.items.park(item.id, reason, claimToken);
+ summary.parked.push(item.id);
+ } else {
+ await stores.items.returnToWork(item.id, reason, claimToken);
+ summary.continued.push(item.id);
+ }
+ } finally {
+ budget.release(openedOutputs);
}
}
- if (autoShipped.length === ready.length) {
- await stores.items.markShipped(item.id);
- summary.shipped.push(item.id);
- } else {
- summary.ready.push(item.id);
- }
- } catch (error) {
- const reason = error instanceof Error ? error.message : String(error);
- summary.failures.push(`${item.sourceKey}: ${reason}`);
- if (autoShippedCount > 0) {
- const partialReason = `partial auto-ship: ${autoShippedCount} of ${autoOutputCount} actions completed before failure — needs human review`;
- await stores.items.park(item.id, partialReason);
- summary.parked.push(item.id);
- continue;
- }
- const latestRunId = (await stores.items.get(item.id))?.runIds.at(-1);
- if (latestRunId) await stores.outputs.supersedeAttempt(item.id, latestRunId);
- const exhausted = item.attempts >= effectiveMaxAttempts;
- if (exhausted) {
- await stores.items.park(item.id, reason, claimToken);
- summary.parked.push(item.id);
- } else {
- await stores.items.returnToWork(item.id, reason, claimToken);
- summary.continued.push(item.id);
- }
- }
- }
+ }),
+ );
+ for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
+ if (capped && !drained) summary.throttled ??= budget.reason();
await stores.loops.recordFireOutcome(loop.id, summary.failures.length > 0);
return summary;
diff --git a/src/types.ts b/src/types.ts
index eb959e3eb..2962a85c3 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -343,6 +343,7 @@ export interface ShipActionPolicy {
export interface LoopCaps {
maxItemsPerFire?: number;
+ maxConcurrentItems?: number;
maxOpenOutputs?: number;
maxItemAttempts?: number;
}
diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.ts
index 1f8641c4b..ab1456d1c 100644
--- a/test/loop-fire.test.ts
+++ b/test/loop-fire.test.ts
@@ -1071,6 +1071,29 @@ test("a triage dry run regroups every open item with draft instructions and writ
assert.deepEqual(await s.items.byLoop(loop.id), before);
});
+test("parallel items stage work and judge on their own conversation, never colliding", async () => {
+ const active = new Set<string>();
+ const busy: string[] = [];
+ const s = service(async (req) => {
+ const ref = req.conversation.threadRef!;
+ if (active.has(ref)) busy.push(ref);
+ active.add(ref);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active.delete(ref);
+ if (stage(req) === "intake")
+ return '```json\n[{"sourceKey": "A", "sourceSummary": "a"}, {"sourceKey": "B", "sourceSummary": "b"}]\n```';
+ return HAPPY(req);
+ });
+ const loop = await makeLoop(s.loops, { caps: { maxConcurrentItems: 2 } });
+ const result = await s.fire.fire(loop.id, "f1");
+ assert.equal(result.status, "ok");
+ assert.deepEqual(busy, []);
+ const refs = (kind: string) => s.turns.filter((t) => stage(t) === kind).map((t) => t.conversation.threadRef);
+ assert.equal(new Set(refs("work")).size, 2);
+ assert.deepEqual(new Set(refs("judge")), new Set(refs("work")));
+ assert.ok(!refs("work").includes(refs("intake")[0]!));
+});
+
test("Slack work and follow-up prompts preserve message images without repeating profile cosmetics", async () => {
const s = service((req) => {
if (stage(req) === "work") return '```json\n{"proposal":{"body":"Draft reply"},"outputs":[]}\n```';
diff --git a/test/loop-routes.test.ts b/test/loop-routes.test.ts
index c1b35f477..8d78db976 100644
--- a/test/loop-routes.test.ts
+++ b/test/loop-routes.test.ts
@@ -187,6 +187,7 @@ test("create validates the essentials", async () => {
test("create and patch reject invalid operational numbers and accept their boundaries", async () => {
const invalid = [
["caps", "maxItemsPerFire", 1.5],
+ ["caps", "maxConcurrentItems", 0],
["caps", "maxOpenOutputs", 0],
["caps", "maxItemAttempts", Number.POSITIVE_INFINITY],
["governor", "maxConsecutiveFailedFires", 0],
@@ -207,7 +208,7 @@ test("create and patch reject invalid operational numbers and accept their bound
const deps = services();
const created = await call(deps, "POST", "/v1/loops", {
...CREATE,
- caps: { maxItemsPerFire: 1, maxOpenOutputs: 1, maxItemAttempts: 1 },
+ caps: { maxItemsPerFire: 1, maxConcurrentItems: 1, maxOpenOutputs: 1, maxItemAttempts: 1 },
governor: {
maxConsecutiveFailedFires: 1,
returnRateMinDecisions: 1,
@@ -219,6 +220,12 @@ test("create and patch reject invalid operational numbers and accept their bound
});
assert.equal(created.status, 200);
const id = (created.body as { loop: { id: string } }).loop.id;
+ assert.equal((created.body as { loop: Loop }).loop.caps?.maxConcurrentItems, 1);
+ const patchedCap = await call(deps, "PATCH", `/v1/loops/${id}`, {
+ caps: { maxItemsPerFire: 1, maxConcurrentItems: 2 },
+ });
+ assert.equal(patchedCap.status, 200);
+ assert.equal((patchedCap.body as { loop: Loop }).loop.caps?.maxConcurrentItems, 2);
const patched = await call(deps, "PATCH", `/v1/loops/${id}`, {
caps: { maxItemsPerFire: 1 },
governor: { maxReturnRate: Number.NEGATIVE_INFINITY },
diff --git a/test/loop-runner.test.ts b/test/loop-runner.test.ts
index 376665995..b6b22692c 100644
--- a/test/loop-runner.test.ts
+++ b/test/loop-runner.test.ts
@@ -394,3 +394,203 @@ test("a quiet fire that needs nobody says so", async () => {
const summary = await runLoopFire(loop, s, effects(s));
assert.equal(fireNeedsAttention(summary), false);
});
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 50; i++) await new Promise((resolve) => setImmediate(resolve));
+}
+
+function heldWork(started: string[], release: Map<string, () => void>): LoopRunnerEffects["work"] {
+ return async ({ item }) => {
+ started.push(item.sourceKey);
+ await new Promise<void>((resolve) => release.set(item.sourceKey, resolve));
+ return { runId: `run-${item.sourceKey}` };
+ };
+}
+
+test("a concurrency cap of 2 starts a second item while the first still runs, and the third only once one finishes", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxConcurrentItems: 2 } });
+ const started: string[] = [];
+ const release = new Map<string, () => void>();
+ const fire = runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }],
+ work: heldWork(started, release),
+ }),
+ );
+ await settle();
+ assert.equal(started.length, 2);
+ release.get(started[1]!)!();
+ await settle();
+ assert.equal(started.length, 3);
+ release.get(started[0]!)!();
+ release.get(started[2]!)!();
+ const summary = await fire;
+ assert.deepEqual([...started].sort(), ["A", "B", "C"]);
+ assert.equal(summary.worked, 3);
+ assert.equal(summary.ready.length, 3);
+});
+
+test("an unset concurrency cap still starts the next item only after the previous one finishes", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxItemsPerFire: 3 } });
+ const started: string[] = [];
+ const release = new Map<string, () => void>();
+ const fire = runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }],
+ work: heldWork(started, release),
+ }),
+ );
+ await settle();
+ assert.equal(started.length, 1);
+ release.get(started[0]!)!();
+ await settle();
+ assert.equal(started.length, 2);
+ release.get(started[1]!)!();
+ await settle();
+ assert.equal(started.length, 3);
+ release.get(started[2]!)!();
+ const summary = await fire;
+ assert.deepEqual([...started].sort(), ["A", "B", "C"]);
+ assert.equal(summary.worked, 3);
+});
+
+test("an undeclared ship action parks its own item and leaves the item running beside it untouched", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxConcurrentItems: 2 } });
+ const started: string[] = [];
+ const release = new Map<string, () => void>();
+ const fire = runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }],
+ work: heldWork(started, release),
+ captureOutputs: async ({ item }) => [
+ {
+ shipAction: item.sourceKey === "A" ? "merge_pr" : "open_pr",
+ title: item.sourceKey,
+ capturedBy: "ledger",
+ externalRef: `pr-${item.sourceKey}`,
+ },
+ ],
+ }),
+ );
+ await settle();
+ assert.equal(started.length, 2);
+ release.get("A")!();
+ await settle();
+ release.get("B")!();
+ const summary = await fire;
+ const idOf = new Map((await s.items.byLoop(loop.id)).map((item) => [item.sourceKey, item.id]));
+ assert.deepEqual(summary.undeclaredShipActions, ["merge_pr"]);
+ assert.deepEqual(summary.parked, [idOf.get("A")]);
+ assert.deepEqual(summary.ready, [idOf.get("B")]);
+ assert.equal((await s.outputs.awaitingReview(loop.id)).length, 1);
+});
+
+test("a cap far larger than the batch sizes the pool to the work there is, not to the cap", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxConcurrentItems: Number.MAX_SAFE_INTEGER } });
+ const summary = await runLoopFire(loop, s, effects(s));
+ assert.equal(summary.worked, 1);
+ assert.equal(summary.ready.length, 1);
+});
+
+test("a failed claim does not reject the fire while a sibling item is still in flight", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxConcurrentItems: 2 } });
+ const started: string[] = [];
+ const release = new Map<string, () => void>();
+ const claim = s.items.claim.bind(s.items);
+ let claims = 0;
+ s.items.claim = async (id, claimedAt, expectedLoopId) => {
+ claims += 1;
+ if (claims === 2) throw new Error("ledger unavailable");
+ return claim(id, claimedAt, expectedLoopId);
+ };
+ let fireSettled = false;
+ const outcome = runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }],
+ work: heldWork(started, release),
+ }),
+ )
+ .then(
+ () => "resolved",
+ (error: Error) => error.message,
+ )
+ .finally(() => {
+ fireSettled = true;
+ });
+ await settle();
+ assert.equal(started.length, 1);
+ assert.equal(fireSettled, false);
+ release.get(started[0]!)!();
+ await settle();
+ assert.equal(started.length, 2);
+ assert.equal(fireSettled, false);
+ release.get(started[1]!)!();
+ assert.equal(await outcome, "ledger unavailable");
+});
+
+test("concurrent items stop at the unreviewed-output cap instead of sailing past it", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxOpenOutputs: 2, maxConcurrentItems: 4 } });
+ const summary = await runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }, { sourceKey: "D" }],
+ captureOutputs: async ({ item }) => [
+ { shipAction: "open_pr", title: item.sourceKey, capturedBy: "ledger", externalRef: `pr-${item.sourceKey}` },
+ ],
+ }),
+ );
+ assert.equal(summary.worked, 2);
+ assert.equal((await s.outputs.awaitingReview(loop.id)).length, 2);
+ assert.equal(summary.throttled, "2 outputs waiting for review");
+ assert.equal((await s.items.queued(loop.id)).length, 2);
+});
+
+test("an item that leaves nothing for review hands its review slot straight back", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxOpenOutputs: 1, maxConcurrentItems: 3 } });
+ const summary = await runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }],
+ evaluate: async () => ({ outcome: "continue", reason: "not done yet", checks: [], judged: true }),
+ }),
+ );
+ assert.equal(summary.worked, 3);
+ assert.equal(summary.continued.length, 3);
+ assert.equal(summary.throttled, undefined);
+ assert.equal((await s.outputs.awaitingReview(loop.id)).length, 0);
+});
+
+test("with no output cap set, concurrency is limited only by the pool", async () => {
+ const s = stores();
+ const loop = await loopIn(s, { caps: { maxConcurrentItems: 3 } });
+ const summary = await runLoopFire(
+ loop,
+ s,
+ effects(s, {
+ enumerate: async () => [{ sourceKey: "A" }, { sourceKey: "B" }, { sourceKey: "C" }],
+ captureOutputs: async ({ item }) => [
+ { shipAction: "open_pr", title: item.sourceKey, capturedBy: "ledger", externalRef: `pr-${item.sourceKey}` },
+ ],
+ }),
+ );
+ assert.equal(summary.worked, 3);
+ assert.equal(summary.throttled, undefined);
+ assert.equal((await s.outputs.awaitingReview(loop.id)).length, 3);
+});