forgedock 1.52.0 → 1.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -248,24 +248,157 @@ describe("account rotator and usage-limit holds (#5094)", () => {
248
248
  assert.deepEqual(starts, [t0]);
249
249
  });
250
250
 
251
- it("#5094 #5095 a limited pool account keeps its own hold under a rotator with headroom; the host account is never held", async () => {
251
+ it("#5094 #5095 #5203 a limited pool account rotates under a rotator with headroom (no pool hold); once every account was tried it keeps its own hold", async () => {
252
252
  const { c, now, sleep } = fakeClock();
253
253
  const t0 = c.t;
254
254
  const limits = openLimits(storeFile(), { now });
255
255
  const rotator = { accounts: [{ n: 1 }], headroom: () => true, resumeAt: () => now(), isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1" };
256
256
  const remote = { max: 2, fallbackLocal: true, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
257
- const runs = [];
257
+ const runs = [], pausedHolds = [];
258
258
  const rows = await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, identity: () => laneBackendId({}, rotator),
259
+ onUpdate: (u) => { if (u.outcome === "paused") pausedHolds.push(limits.holdUntil("remote:pool")); },
259
260
  runOne: async (n, _l, ctx) => {
260
261
  runs.push({ n, at: now(), where: ctx.placement?.where, poolHeld: limits.holdUntil("remote:pool"), hostHeld: limits.holdUntil("acct-1") });
261
- return n === 1 && runs.length === 1 ? limited("remote:pool", t0 + 600_000) : { terminalReason: "merged" };
262
+ return n === 1 && runs.filter((x) => x.n === 1).length <= 2 ? limited("remote:pool", t0 + 600_000) : { terminalReason: "merged" };
262
263
  } });
263
264
  assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
264
- const second = runs.find((x) => x.n === 2);
265
- assert.equal(runs[0].where, "remote");
266
- assert.equal(second.at, t0, "the host account is not held: admissions continue");
267
- assert.equal(second.poolHeld, t0 + 600_000, "the pool's own hold is recorded (#5095)");
268
- assert.ok(!(second.hostHeld > now()), "no host-wide hold while the rotator has headroom");
269
- assert.equal(second.where, "local", "hybrid falls back local while the pool is held");
265
+ const ones = runs.filter((x) => x.n === 1);
266
+ assert.equal(ones[0].where, "remote");
267
+ assert.equal(ones[1].at, t0, "the pool limit reruns at once (the router hands out another login, #5165)");
268
+ assert.equal(ones[1].poolHeld, null, "no pool hold while an account has headroom (#5203)");
269
+ assert.equal(ones[1].where, "remote");
270
+ assert.ok(runs.every((x) => !(x.hostHeld > x.at)), "no host-wide hold while the rotator has headroom");
271
+ // the second limit exhausted the one-account rotation budget: the pool's own hold applies again (#5095)
272
+ assert.deepEqual(pausedHolds, [null, t0 + 600_000], "only the second limit records the pool hold (#5095)");
273
+ });
274
+
275
+ it("#5203 a rate-limited pool lane with another usable account rotates and sets no batch-wide notBefore", async () => {
276
+ const { c, now, sleep } = fakeClock();
277
+ const t0 = c.t;
278
+ const limits = openLimits(storeFile(), { now });
279
+ const rotator = { accounts: [{ n: 1 }, { n: 3 }, { n: 5 }], headroom: () => true, resumeAt: () => now(), isAccount: (id) => /^acct-/.test(id), currentIdentity: () => "acct-1" };
280
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
281
+ let state = null;
282
+ const store = { load: () => state, save: (s) => { state = JSON.parse(JSON.stringify(s)); } };
283
+ const runs = [];
284
+ const rows = await orchestrate({ issues: [1, 2, 3], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, store, identity: () => laneBackendId({}, rotator),
285
+ runOne: async (n) => {
286
+ runs.push({ n, at: now(), poolHeld: limits.holdUntil("remote:pool"), notBefore: { ...(state?.notBefore ?? {}) }, quota: state?.quota?.[1] ?? null });
287
+ return n === 1 && runs.length === 1 ? limited("remote:pool", t0 + 2 * 3_600_000) : { terminalReason: "merged" };
288
+ } });
289
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged", "merged"]);
290
+ assert.ok(runs.every((x) => x.at === t0), "every lane starts at once: nothing waits for the limited account's reset");
291
+ const rerun = runs.filter((x) => x.n === 1)[1];
292
+ assert.equal(rerun.quota.rotations, 1, "rotations >= 1");
293
+ assert.equal(rerun.poolHeld, null, "no pool hold");
294
+ assert.ok(runs.every((x) => Object.values(x.notBefore).every((v) => !(v > t0))), "no batch-wide notBefore");
295
+ });
296
+
297
+ it("#5203 when every account is limited, the pool hold and notBefore are the earliest reset across accounts", async () => {
298
+ const { c, now, sleep } = fakeClock();
299
+ const t0 = c.t;
300
+ let everyLimited = false; // the rotator has headroom until the lane reports the limit
301
+ const earliest = t0 + 1_800_000, laneReset = t0 + 3 * 3_600_000;
302
+ const limits = openLimits(storeFile(), { now });
303
+ const rotator = { accounts: [{ n: 1 }, { n: 2 }], headroom: () => !everyLimited || now() >= earliest, resumeAt: () => Math.max(earliest, now()), isAccount: (id) => /^acct-/.test(id), currentIdentity: () => "acct-1" };
304
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
305
+ let poolHold = null;
306
+ const runs = [], log = [];
307
+ const rows = await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, identity: () => laneBackendId({}, rotator),
308
+ onUpdate: (u) => { log.push(u); if (u.outcome === "paused") poolHold = limits.holdUntil("remote:pool"); },
309
+ runOne: async (n) => {
310
+ runs.push({ n, at: now() });
311
+ if (n === 1 && runs.length === 1) { everyLimited = true; return limited("remote:pool", laneReset); }
312
+ return { terminalReason: "merged" };
313
+ } });
314
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
315
+ assert.equal(poolHold, earliest, "the pool hold (the notBefore of every remote-placed issue) is the earliest reset across accounts, not the lane's own");
316
+ assert.equal(runs.find((x) => x.n === 2).at, earliest, "the next lane starts at the earliest reset");
317
+ assert.match(log.find((u) => u.outcome === "paused").detail, new RegExp(`until ${new Date(earliest).toISOString()}`));
318
+ });
319
+
320
+ it("#5203 --requeue of a quota-paused pending issue clears its notBefore and the pool hold", async () => {
321
+ const { c, now, sleep } = fakeClock();
322
+ const t0 = c.t;
323
+ const limits = openLimits(storeFile(), { now });
324
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
325
+ let paused = false;
326
+ const runs = [], log = [];
327
+ const rows = await orchestrate({ issues: [1], parallel: 1, now, sleep, pollMs: 5000, readBody: async () => "", limits, remote, identity: () => "local", onUpdate: (u) => log.push(u),
328
+ getRequeued: () => (paused ? [{ issue: 1, reason: "accounts 1, 3, 5 usable", by: "operator", at: "2026-11-07T08:05:00Z" }] : []),
329
+ runOne: async (n) => {
330
+ runs.push({ n, at: now() });
331
+ if (runs.length === 1) { paused = true; return limited("remote:pool", t0 + 2 * 3_600_000); }
332
+ return { terminalReason: "merged" };
333
+ } });
334
+ assert.equal(rows[0].outcome, "merged");
335
+ assert.equal(runs.length, 2);
336
+ assert.ok(runs[1].at < t0 + 60_000, `the released issue runs on the next poll, not at the reset (ran at +${runs[1].at - t0}ms)`);
337
+ assert.equal(limits.holdUntil("remote:pool"), null, "the pool hold is cleared");
338
+ assert.ok(log.some((u) => u.issue === 1 && u.outcome === "requeued" && /quota pause released/.test(u.detail)));
339
+ });
340
+ });
341
+
342
+ describe("tokenbaton rotation holds (#5205)", () => {
343
+ const H = 3_600_000;
344
+ const memStore = () => { const states = []; return { states, load: () => null, save: (s) => states.push(JSON.parse(JSON.stringify(s))) }; };
345
+
346
+ it("#5205 all accounts limited: the hold lasts until tokenbaton's earliest reset, not the limited account's own; rotations summed", async () => {
347
+ const { c, now, sleep } = fakeClock();
348
+ const t0 = c.t, earliest = t0 + 2 * H, own = t0 + 5 * H;
349
+ const picks = [];
350
+ let exhausted = false; // every account limited once the first run returns
351
+ const rot = { accounts: [{ n: 1 }, { n: 2 }, { n: 3 }], headroom: () => !exhausted || now() >= earliest, resumeAt: () => t0 + 4 * H, isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1",
352
+ pick: ({ exclude }) => { picks.push([...exclude.keys()]); return now() >= earliest ? { account: 2, stale: false } : { account: null, earliestReset: earliest }; } };
353
+ const limits = openLimits(storeFile(), { now }), store = memStore(), updates = [], starts = [];
354
+ const rows = await orchestrate({ issues: [1], now, sleep, readBody: async () => "", rotator: rot, limits, identity: () => "acct-1", store, onUpdate: (u) => updates.push(u),
355
+ runOne: async () => { starts.push(now()); exhausted = true; return starts.length === 1 ? { ...limited("acct-1", own), rotations: 2, limited: [{ account: 1, until: own }, { account: 3, until: t0 + 3 * H }] } : { terminalReason: "merged" }; } });
356
+ assert.equal(rows[0].outcome, "merged");
357
+ assert.equal(limits.holdUntil("acct-1") ?? earliest, earliest, "the hold is tokenbaton's earliest reset");
358
+ const paused = updates.find((u) => u.outcome === "paused");
359
+ assert.equal(paused.quota.resumeAt, new Date(earliest).toISOString());
360
+ assert.equal(starts[1], earliest, "rerun at the earliest reset, not the account's own reset");
361
+ assert.deepEqual(picks[0]?.sort(), [1, 3], `lane-reported limited accounts are excluded: ${JSON.stringify({ picks, starts, u: updates.map((u) => u.outcome) })}`);
362
+ const st = store.states.find((s) => s.quota?.["1"]);
363
+ assert.equal(st.quota["1"].rotations, 2, "lane-reported rotations add to quota.rotations");
364
+ assert.deepEqual(Object.keys(st.limitedAccounts).sort(), ["1", "3"], "limited accounts persist with the batch");
365
+ });
366
+
367
+ it("#5236 a quota.exhausted lane result is held until the earliest reset and the batch log row names the code and reset", async () => {
368
+ const { c, now, sleep } = fakeClock();
369
+ const t0 = c.t, earliest = t0 + 3 * H;
370
+ const rot = { accounts: [{ n: 1 }, { n: 2 }], headroom: () => now() >= earliest, resumeAt: () => earliest, isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1",
371
+ pick: () => (now() >= earliest ? { account: 2, stale: false } : { account: null, earliestReset: earliest }) };
372
+ const limits = openLimits(storeFile(), { now }), updates = [], starts = [];
373
+ const rows = await orchestrate({ issues: [1], now, sleep, readBody: async () => "", rotator: rot, limits, identity: () => "acct-1", store: memStore(), onUpdate: (u) => updates.push(u),
374
+ runOne: async () => { starts.push(now()); return starts.length === 1 ? { terminalReason: "deferred", code: "quota.exhausted", backendId: "acct-1", resetAtEpochMs: earliest, detail: "quota exhausted: no account has capacity" } : { terminalReason: "merged" }; } });
375
+ assert.equal(rows[0].outcome, "merged");
376
+ assert.equal(starts[1], earliest, "rerun at the earliest reset");
377
+ const paused = updates.find((u) => u.outcome === "paused");
378
+ assert.equal(paused.quota.resumeAt, new Date(earliest).toISOString());
379
+ assert.match(paused.detail, /quota\.exhausted/);
380
+ const evt = updates.find((u) => u.event === "quota.exhausted");
381
+ assert.ok(evt, "batch-level quota.exhausted event");
382
+ assert.equal(evt.resumeAt, new Date(earliest).toISOString());
383
+ });
384
+
385
+ it("#5205 a lane-reported limited account is excluded from headroom until its reset", async () => {
386
+ const { c, now, sleep } = fakeClock();
387
+ const t0 = c.t, seen = [];
388
+ const rot = { accounts: [{ n: 1 }, { n: 2 }], headroom: (ex) => { seen.push(ex ? [...ex.keys()] : []); return !(ex?.has(1) && ex?.has(2)); }, resumeAt: () => t0 + H, isAccount: () => true, currentIdentity: () => "acct-1", pick: () => ({ account: null, earliestReset: t0 + H }) };
389
+ let runs = 0;
390
+ await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", rotator: rot, limits: openLimits(storeFile(), { now }), identity: () => "acct-1",
391
+ runOne: async (n) => { runs++; return n === 1 ? { terminalReason: "merged", rotations: 1, limited: [{ account: 1, until: t0 + H }] } : { terminalReason: "merged" }; } });
392
+ assert.equal(runs, 2);
393
+ assert.ok(seen.some((x) => x.includes(1)), `headroom saw the limited account excluded: ${JSON.stringify(seen)}`);
394
+ });
395
+
396
+ it("#5205 no rotator: the hold is now + the reset delay, as before", async () => {
397
+ const { c, now, sleep } = fakeClock();
398
+ const limits = openLimits(storeFile(), { now });
399
+ const until = c.t + H;
400
+ await orchestrate({ issues: [1], now, sleep, readBody: async () => "", limits, identity: () => "A",
401
+ runOne: async () => { if (now() < until) { const r = limited("A", until); setImmediate(() => {}); return r; } return { terminalReason: "merged" }; },
402
+ onUpdate: (u) => { if (u.outcome === "paused") assert.equal(limits.holdUntil("A"), until); } });
270
403
  });
271
404
  });
@@ -0,0 +1,143 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5241: --cancel --stop-remote confirms or reports each lane, releases its lease; dead-lease requeue; active-batch skip.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+ import { openBatch, activeBatchOf, cancelledOwners } from "./batch.mjs";
9
+ import { clearLease } from "./lanelock.mjs";
10
+ import { providerLanes } from "./execution.mjs";
11
+ import { orchestrateFromCli } from "../engine-cli.mjs";
12
+
13
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("cancel-sched-");
14
+ const until = async (cond, ms = 5000) => {
15
+ const end = Date.now() + ms;
16
+ while (!cond()) { if (Date.now() > end) throw new Error("timed out waiting"); await new Promise((r) => setTimeout(r, 5)); }
17
+ };
18
+ const clock = () => { const c = { t: 1_000_000 }; return { now: () => c.t, tick: (ms) => { c.t += ms; } }; };
19
+
20
+ describe("cancel --stop-remote teardown (#5241)", () => {
21
+ it("retries a stop that was not accepted, reports a lane still running after the timeout, then releases its lease when it ends", async () => {
22
+ let cancel = null, saved = null, release;
23
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
24
+ const gate = new Promise((r) => { release = r; });
25
+ const { now, tick } = clock();
26
+ const tries = [], released = [], rows = [];
27
+ const done = orchestrate({ issues: [7], parallel: 1, pollMs: 5, now, stopRetryMs: 1000, stopTimeoutMs: 5000, readBody: async () => "", store, getCancelled: () => cancel, onUpdate: (r) => rows.push(r),
28
+ stopLane: (n, rec) => { tries.push(n); rec.stopNote = "the pool does not support stop (404/405)"; return false; },
29
+ releaseLease: async (n) => { released.push(n); },
30
+ runOne: async (n, _l, ctx) => { ctx.onStart?.({ remote: true, handle: { id: "sbx" } }); await gate; return { terminalReason: "deferred", code: "run.interrupted" }; } });
31
+ await until(() => saved?.running?.[7]);
32
+ cancel = { at: "2026-01-01T00:00:00Z", reason: "operator", stopRemote: true };
33
+ await until(() => tries.length >= 1);
34
+ tick(1500); await until(() => tries.length >= 2); // retried: the first stop was refused
35
+ tick(6000); await until(() => rows.some((r) => /#7 not confirmed stopped/.test(r.detail ?? "")));
36
+ assert.match(rows.find((r) => /not confirmed stopped/.test(r.detail ?? "")).detail, /404\/405/);
37
+ assert.deepEqual(released, [], "a lane still running keeps its lease");
38
+ release(); await done;
39
+ assert.deepEqual(released, [7], "the ended lane's lease is released");
40
+ });
41
+
42
+ it("stopLane records why a lane could not be stopped on its record", async () => {
43
+ const provider = { name: "p", idFor: (n) => `s${n}`, stop: async () => false, stopReason: () => "the pool does not support stop (404/405)" };
44
+ const lanes = providerLanes({ provider, laneArgs: () => [], ledgerFor: () => null });
45
+ const rec = { handle: { id: "s1" } };
46
+ assert.equal(await lanes.stopLane(1, rec), false);
47
+ assert.match(rec.stopNote, /404\/405/);
48
+ });
49
+ });
50
+
51
+ describe("clearLease (#5241)", () => {
52
+ const mk = (lease) => { const st = { lease, phase: "x" }; return { st, projector: { readState: async () => st, writeState: async (_n, s) => { Object.assign(st, s); } } }; };
53
+ it("clears a lease the guard accepts, keeps one it refuses, and no-ops without one", async () => {
54
+ const a = mk({ by: "core_a", until: 9e15 });
55
+ assert.equal(await clearLease({ projector: a.projector, issue: 1 }), true);
56
+ assert.equal(a.st.lease, null);
57
+ const b = mk({ by: "core_b", until: 9e15 });
58
+ assert.equal(await clearLease({ projector: b.projector, issue: 1, shouldClear: () => false }), false);
59
+ assert.equal(b.st.lease.by, "core_b");
60
+ assert.equal(await clearLease({ projector: mk(null).projector, issue: 1 }), false);
61
+ });
62
+ });
63
+
64
+ describe("dead-lease requeue and active-batch lookup (#5241)", () => {
65
+ const seed = (root, id, { repo = "o/r", order = [5], running = {}, pending = [], notBefore = {}, cancelled = false, report = false } = {}) => {
66
+ const b = openBatch(root, id);
67
+ b.writePlan({ v: 1, id, repo });
68
+ b.store.save({ order, running, pending, results: {}, notBefore });
69
+ if (cancelled) b.requestCancel({});
70
+ if (report) b.writeReport({ done: true });
71
+ return b;
72
+ };
73
+ it("requeue accepts a pending issue deferred on a lease whose holder is a cancelled batch, and still refuses an ordinary deferral", () => {
74
+ const root = tmpDir("cancel-requeue-");
75
+ seed(root, "bcancel", { cancelled: true, running: { 5: { remote: true } } });
76
+ const live = seed(root, "blive", { pending: [5, 6], order: [5, 6], notBefore: { 5: Date.now() + 1e6, 6: Date.now() + 1e6 } });
77
+ const r = live.requeue([5, 6]);
78
+ assert.deepEqual(r.requeued, [5]);
79
+ assert.deepEqual(r.refused, [{ issue: 6, reason: "not terminal" }]);
80
+ });
81
+ it("is refused while a live batch runs the issue, or when no cancelled batch owns it", () => {
82
+ const root = tmpDir("cancel-requeue2-");
83
+ seed(root, "bcancel", { cancelled: true });
84
+ seed(root, "bother", { running: { 5: {} } });
85
+ const live = seed(root, "blive", { pending: [5], notBefore: { 5: Date.now() + 1e6 } });
86
+ assert.deepEqual(cancelledOwners(root, "o/r", 5, "blive"), []);
87
+ assert.equal(live.requeue([5]).refused[0].reason, "not terminal");
88
+ });
89
+ it("activeBatchOf names an unfinished, uncancelled batch of the same repo; not a finished, cancelled, stale or other-repo one", () => {
90
+ const root = tmpDir("cancel-active-");
91
+ seed(root, "bpend", { pending: [5] });
92
+ assert.equal(activeBatchOf(root, "o/r", 5), "bpend");
93
+ assert.equal(activeBatchOf(root, "o/other", 5), null);
94
+ assert.equal(activeBatchOf(root, "o/r", 5, { now: Date.now() + 4 * 3600e3 }), null, "stale");
95
+ openBatch(root, "bpend").writeReport({ done: true });
96
+ assert.equal(activeBatchOf(root, "o/r", 5), null, "finished");
97
+ const root2 = tmpDir("cancel-active2-");
98
+ seed(root2, "bc", { pending: [5], cancelled: true });
99
+ assert.equal(activeBatchOf(root2, "o/r", 5), null, "cancelled");
100
+ });
101
+ });
102
+
103
+ describe("orchestrate start skips issues of another active batch (#5241)", () => {
104
+ const mkDeps = (root, batchId, ran) => ({ dir: tmpDir("active-run-"), batchRoot: root, batchId, allowTmpfs: true, emitTelemetry: async () => {}, io: { gh: async () => "o/r\n" }, sched: null,
105
+ leanIo: { gh: async (a) => (a.includes("milestone") ? JSON.stringify({ milestone: null }) : JSON.stringify({ body: "" })), git: async (a) => (a[0] === "ls-remote" ? "abc\trefs/heads/staging\n" : "") },
106
+ decide: () => {}, orchestration: { breaker: null, maxDeferrals: 3, globalParallel: null },
107
+ leanModule: { runCore: async (o) => { ran.push(o.issue); return { terminalReason: "merged", pr: 50 + o.issue }; } } });
108
+ const run = async (argv, deps) => { const lines = []; const l = console.log; console.log = (...a) => lines.push(a.join(" ")); try { return { res: await orchestrateFromCli(argv, deps), lines }; } finally { console.log = l; } };
109
+
110
+ it("skips the issue naming the batch, runs the rest, and --force starts it anyway", async () => {
111
+ const root = tmpDir("active-cli-");
112
+ const other = openBatch(root, "bother");
113
+ other.writePlan({ v: 1, id: "bother", repo: "o/r" });
114
+ other.store.save({ order: [1], running: { 1: { pid: 1 } }, pending: [], results: {} });
115
+ const ran = [];
116
+ const a = await run(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], mkDeps(root, "bnew", ran));
117
+ assert.match(a.lines.join("\n"), /skipped: #1 is already in active batch bother/);
118
+ assert.deepEqual(ran, [2]);
119
+ assert.deepEqual(openBatch(root, "bnew").readPlan().argv, ["2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"]);
120
+ const ran2 = [];
121
+ await run(["1", "--parallel", "1", "--repo", "o/r", "--no-prefilter", "--force", "sibling batch is dead"], mkDeps(root, "bforce", ran2));
122
+ assert.deepEqual(ran2, [1]);
123
+ await assert.rejects(run(["1", "--repo", "o/r", "--no-prefilter"], mkDeps(root, "bnone", [])), /every issue is already in an active batch \(bother\)/);
124
+ });
125
+ });
126
+
127
+ describe("--requeue of a lease-deferred pending issue (#5241)", () => {
128
+ it("releases the deferral wait so the next pass relaunches it at once", async () => {
129
+ let saved = null, entries = [];
130
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
131
+ const runs = [];
132
+ const done = orchestrate({ issues: [9], parallel: 1, pollMs: 5, readBody: async () => "", store, getRequeued: () => entries,
133
+ runOne: async (n) => {
134
+ runs.push(n);
135
+ return runs.length === 1 ? { terminalReason: "deferred", code: "lease-held", detail: `issue 9 leased by core_x until ${new Date(Date.now() + 3600e3).toISOString()}` } : { terminalReason: "merged", pr: 1 };
136
+ } });
137
+ await until(() => Number.isFinite(saved?.notBefore?.[9]));
138
+ entries = [{ issue: 9, reason: "dead lease", by: "operator", at: "2026-01-01T00:00:00Z" }];
139
+ const rows = await done;
140
+ assert.deepEqual(runs, [9, 9]);
141
+ assert.equal(rows.find((r) => r.issue === 9).outcome, "merged");
142
+ });
143
+ });
@@ -21,7 +21,7 @@
21
21
  * before scheduling, so a live lane does not hold up the others.
22
22
  * `deferred` is a scheduling fact, not an end: each typed code is requeued with its retry-at (`deferPolicy`), a usage
23
23
  * limit (and #5168 a claude login failure, `backend.auth`) holds admissions for that account until its reset, and deferrals other than a wait (`host.busy`,
24
- * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168) stop after `maxDeferrals`.
24
+ * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168; `quota.exhausted`, #5236) stop after `maxDeferrals`.
25
25
  * #5161: an engine-error whose detail is a transport/gateway failure (`isTransientEngineError`) is requeued with backoff
26
26
  * (`transientRetryDelayMs`) up to `transientRetries` times, not counted against `ENGINE_ERROR_RELAUNCHES`; then it ends engine-error.
27
27
  * #5112: with `remote.offlineFallback` (`execution.fallback_local`), an issue deferred `remote.capacityFallbackAfter` times (default
@@ -30,7 +30,10 @@
30
30
  * host; in memory when absent): admission checks the hold of `identity()`, the account the next lane would use. While held, the
31
31
  * batch re-reads the store every `pollMs` (#4446), so `forgedock limits clear` admits on the next poll, not at the reset.
32
32
  * #5095: `remote.identity()` names the pool's account (execution.mjs `remoteHoldId`); while it is held, a remote-placed lane
33
- * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. An `engine-error` is
33
+ * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. #5203: under a
34
+ * rotator with headroom a pool usage limit reruns at once (`quotaRequeue` `poolId`) and records no pool hold; with no headroom the
35
+ * hold lasts until `rotator.resumeAt()` (the earliest reset). `--requeue` of a quota-paused pending issue clears its notBefore
36
+ * and the pool hold (`drainRequeues`). An `engine-error` is
34
37
  * relaunched once; `breaker` ({errors, window_min}) stops admissions after a burst and lets running lanes finish, the
35
38
  * rest stay pending (outcome `held`) for a resume. `getParallel()` is read on every pass, so K can change live.
36
39
  * #5138: `remote.max`, `remote.fallbackLocal` and `remote.place` are read on every grant too (engine-cli puts live getters on
@@ -235,7 +238,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
235
238
  const code = r?.code ?? null;
236
239
  if (UNCAPPED_DEFERRALS.has(code)) return { delayMs: (posNum(r?.retryInSeconds) ?? HOST_BUSY_RETRY_S) * 1000, host: true };
237
240
  // #4784: a usage limit is a known-time wait gated by the account hold, never capped.
238
- if (code === "rate_limited") {
241
+ if (code === "rate_limited" || code === "quota.exhausted") { // #5236: no account has capacity: held until the earliest reset
239
242
  const at = posNum(r?.resetAtEpochMs) && r.resetAtEpochMs > now ? r.resetAtEpochMs : now + (posNum(r?.retryInSeconds) ?? RATE_LIMIT_FALLBACK_S) * 1000;
240
243
  return { delayMs: at - now, hold: true };
241
244
  }
@@ -251,6 +254,10 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
251
254
  return { delayMs: Math.min(DEFER_BACKOFF_S * 2 ** (k - 1), DEFER_BACKOFF_MAX_S) * 1000 };
252
255
  }
253
256
 
257
+ // #5241: a cancel re-sends a stop that was not accepted every STOP_RETRY_MS and reports a lane still running after STOP_TIMEOUT_MS.
258
+ const STOP_RETRY_MS = 15 * 1000;
259
+ const STOP_TIMEOUT_MS = 120 * 1000;
260
+
254
261
  const cancellableSleep = (ms, signal) => new Promise((res) => {
255
262
  const t = setTimeout(res, ms);
256
263
  signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
@@ -302,9 +309,9 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
302
309
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), onUpdate = () => {}, onCrossLane = () => {},
303
310
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
304
311
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
305
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null,
312
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
306
313
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
307
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null }) {
314
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
308
315
  const saved = store?.load?.() ?? null;
309
316
  const order = saved ? [...saved.order] : [];
310
317
  const set = new Set(order);
@@ -330,10 +337,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
330
337
  let errorTimes = [...(saved?.errorTimes ?? [])];
331
338
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
332
339
  const holds = limits ?? memoryLimits(now);
340
+ // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
341
+ const limitedAccounts = toMap(saved?.limitedAccounts);
342
+ const excluded = () => { for (const [k, u] of limitedAccounts) if (!(Number(u) > now())) limitedAccounts.delete(k); return limitedAccounts; };
343
+ const noteLimited = (r) => { for (const l of Array.isArray(r?.limited) ? r.limited : []) { const a = Number(l?.account), u = Number(l?.until); if (Number.isInteger(a) && a > 0 && Number.isFinite(u)) limitedAccounts.set(a, Math.max(u, Number(limitedAccounts.get(a)) || 0)); } };
333
344
  // #5094: with an account rotator, admissions stop only when no account has headroom, and resume when the first one resets.
334
345
  const rotatorHold = () => {
335
346
  if (!rotator) return undefined;
336
- try { if (rotator.headroom()) return null; const u = rotator.resumeAt(); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
347
+ try { if (rotator.headroom(excluded())) return null; const u = rotator.resumeAt(excluded()); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
337
348
  };
338
349
  const heldUntil = () => {
339
350
  const r = rotatorHold();
@@ -391,6 +402,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
391
402
  const recoveryMax = Number.isInteger(recovery?.maxAttempts) && recovery.maxAttempts > 0 ? recovery.maxAttempts : 0;
392
403
  // #4725: mechanical/env codes recover on their own budget (>= the conformance one); 0 maxAttempts still turns recovery off.
393
404
  const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
405
+ const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
406
+ const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
394
407
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
395
408
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
396
409
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
@@ -407,8 +420,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
407
420
  let halted = false; // #4454: stopped by `signal`; the batch's state is no longer this process's to write
408
421
  const save = () => {
409
422
  if (!store || halted) return;
410
- store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
411
- pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
423
+ store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), engineVersion: version, order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
424
+ pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
412
425
  prefilter: toObj(checked), errorTimes, breaker: tripped, ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
413
426
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
414
427
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
@@ -705,6 +718,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
705
718
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
706
719
  const settle = async (n, r, rec, pf) => {
707
720
  if (halted) return; // #4454: a resume adopts the lane and settles it
721
+ if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
708
722
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
709
723
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
710
724
  const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}),
@@ -717,7 +731,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
717
731
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
718
732
  ...(r?.conformance && typeof r.conformance === "object" ? { conformance: r.conformance } : {}), // #4398
719
733
  ...(rec?.placement ? { placement: rec.placement } : {}), ...(estimates.has(n) ? { est_minutes: Math.round(estimates.get(n) * 10) / 10 } : {}) }; // #4409
720
- const quotaPause = row.outcome === "deferred" && r?.code === "rate_limited" && !cancelled;
734
+ noteLimited(r); // #5205
735
+ const quotaPause = row.outcome === "deferred" && (r?.code === "rate_limited" || r?.code === "quota.exhausted") && !cancelled;
721
736
  if (!quotaPause && quota.has(n)) { // #5094: the paused attempts' cost, added once
722
737
  const q = quota.get(n); quota.delete(n);
723
738
  row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(q.cost_usd) || 0)) * 1e6) / 1e6;
@@ -797,21 +812,33 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
797
812
  let delayMs = pol.delayMs;
798
813
  if (pol.hold) {
799
814
  // #5094: an account rotator with headroom means another account runs the next call, so no host hold is recorded.
800
- const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs });
815
+ // #5203: a usage limit on the pool account rotates like a rotator account (the router hands the next sandbox the
816
+ // lowest-usage login, #5165), so it sets no pool hold and no batch-wide notBefore while any account has headroom.
817
+ const usage = r?.code === "rate_limited" || r?.code === "quota.exhausted";
818
+ let poolId = null;
819
+ if (usage) { try { poolId = remote?.identity?.() ?? null; } catch { poolId = null; } }
820
+ const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs, exclude: excluded(), poolId });
821
+ // #5205: no account with room: hold until the rotator's earliest reset (tokenbaton's, over every account), not now+delay
822
+ let rotAt = null;
823
+ if (!rq && rotator && (!r?.backendId || (poolId && r.backendId === poolId) || (() => { try { return rotator.isAccount(r.backendId); } catch { return false; } })())) { // a remote credential keeps its own reset
824
+ try { const p = typeof rotator.pick === "function" ? rotator.pick({ exclude: excluded() }) : null; rotAt = p && p.account === null && Number.isFinite(p.earliestReset) ? p.earliestReset : rotator.resumeAt(excluded()); } catch { rotAt = null; }
825
+ if (!(Number.isFinite(rotAt) && rotAt > now())) rotAt = null;
826
+ }
827
+ // #5203: no account has headroom: the hold lasts until the earliest reset across accounts, not this lane's own reset.
828
+ const holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
801
829
  if (rq) {
802
830
  delayMs = rq.delayMs;
803
831
  // #5095 + #5094: the pool account's own hold (not the host's) still routes hybrid lanes local until its reset.
804
832
  try { const pool = remote?.identity?.(); if (!rq.rotated && pool && r?.backendId === pool) holds.set(pool, now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); } catch { /* fail-open */ }
805
- } else try { holds.set(r?.backendId ?? identity(), now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
833
+ } else try { holds.set(r?.backendId ?? identity(), rotAt ?? now() + holdMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
806
834
  const q = quota.get(n) ?? { cost_usd: 0, minutes: 0, rotations: 0 };
807
- let rotAt = null;
808
- if (!rq && rotator) { try { rotAt = rotator.resumeAt(); } catch { rotAt = null; } }
809
- const resumeAt = Math.max(now() + (rq ? rq.delayMs : pol.delayMs), Number.isFinite(rotAt) ? rotAt : 0);
835
+ const resumeAt = usage ? now() + (rq ? rq.delayMs : holdMs) : Math.max(now() + (rq ? rq.delayMs : pol.delayMs), rotAt ?? 0);
810
836
  quota.set(n, { cost_usd: Math.round(((Number(q.cost_usd) || 0) + (Number(row.cost_usd) || 0)) * 1e6) / 1e6, minutes: Math.round(((Number(q.minutes) || 0) + (Number(row.minutes) || 0)) * 10) / 10,
811
- resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) });
837
+ resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) + (Number(r?.rotations) || 0) }); // #5205: plus the lane's own in-phase rotations
812
838
  requeue(n, delayMs); done(); save();
813
839
  const iso = new Date(resumeAt).toISOString();
814
840
  update({ ...row, outcome: "paused", quota: { resumeAt: iso }, detail: `paused (${r?.code === "backend.auth" ? "backend.auth" : "quota"}) until ${iso}: ${r?.code ?? "deferred"}${r?.detail ? ` ${r.detail}` : ""}` });
841
+ if (r?.code === "quota.exhausted") { const ev = { event: "quota.exhausted", issue: n, batch: batchId ?? null, resumeAt: iso, detail: `quota.exhausted: no account has capacity; resuming ${iso}` }; try { store?.log?.(ev); } catch { /* best effort */ } onUpdate(ev); } // #5236: batch-level event supervisors see
815
842
  return;
816
843
  }
817
844
  requeue(n, capGated ? 0 : delayMs); done(); save();
@@ -875,7 +902,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
875
902
  const facts = { ...row, issueEdited: r?.issueEdited === true, quoteMismatch: r?.quoteMismatch === true, conflicting: isConflicting };
876
903
  if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.attempt)); } // state saved before #4725 has no class counts
877
904
  const cls = recoveryClassOf(facts), max = maxFor(cls), used = classUsed.get(`${n}:${cls}`) ?? 0;
878
- if (classifyNeedsHuman(facts) === "recoverable" && used < max) {
905
+ // #5232: a deterministic env defect of the frozen command that a recovery attempt repeated verbatim is not rebuilt again
906
+ const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && sigOf(prior.detail) === sigOf(row.detail);
907
+ if (repeatEnv) {
908
+ row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
909
+ decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
910
+ }
911
+ if (!repeatEnv && classifyNeedsHuman(facts) === "recoverable" && used < max) {
879
912
  const code = recoveryCodeOf(facts), attempt = used + 1;
880
913
  classUsed.set(`${n}:${cls}`, attempt);
881
914
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
@@ -977,12 +1010,24 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
977
1010
  // Lanes launched by an earlier dispatcher: re-attach to the live ones, queue the rest again (no result was recorded).
978
1011
  // #4504: every adopt starts at once and races its `onLive` signal, so a live lane never holds up the others: one that
979
1012
  // already ended is settled from its result (or requeued without one) before scheduling; a live one is awaited in the background.
980
- const requeueLost = (n) => { runRecs.delete(n); if (!pending.includes(n) && !results.has(n)) { pending.unshift(n); enqueued.set(n, now()); } };
1013
+ // #5204: a requeue is never silent: one `deferred`/`run.interrupted` row names the cause (an upgrade or a plain restart)
1014
+ // and `onInterrupted` reconciles the issue's labels. It consumes no deferral, engine-error or recovery attempt.
1015
+ const interruptCause = saved?.engineVersion && version && saved.engineVersion !== version ? `upgrade v${saved.engineVersion}→v${version}` : "dispatcher restart";
1016
+ const requeueLost = (n, why) => {
1017
+ runRecs.delete(n);
1018
+ if (pending.includes(n) || results.has(n)) return;
1019
+ pending.unshift(n); enqueued.set(n, now());
1020
+ update({ issue: n, outcome: "deferred", code: "run.interrupted", pr: null, cost_usd: 0, minutes: 0, detail: `interrupted: ${interruptCause}; ${why}; requeued` });
1021
+ decided({ issue: n, what: "requeued (interrupted)", why, alternative: "leave it pending silently" });
1022
+ try { Promise.resolve(onInterrupted?.(n, { cause: interruptCause, why })).catch(() => {}); } catch { /* best effort */ }
1023
+ };
1024
+ const adoptErrors = new Map(); // #5204: issue -> adopt error message, kept for the interrupted row
981
1025
  const adopting = [...runRecs].map(([n, rec]) => {
982
- if (!adopt || !(rec?.pid || rec?.handle)) return { n, rec, live: false, p: Promise.resolve(null) };
1026
+ // #5204: a remote record that lost its handle still adopts: the remote seam finds the sandbox through its ledger.
1027
+ if (!adopt || !(rec?.pid || rec?.handle || rec?.remote)) return { n, rec, live: false, p: Promise.resolve(null) };
983
1028
  let onLive;
984
1029
  const isLive = new Promise((r) => { onLive = () => r(true); });
985
- const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch(() => null);
1030
+ const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
986
1031
  return { n, rec, p, first: Promise.race([p.then(() => false), isLive]) };
987
1032
  });
988
1033
  for (const a of adopting) a.live = a.first ? await a.first : false;
@@ -993,12 +1038,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
993
1038
  track(n, p.then((r) => {
994
1039
  if (r) return settle(n, r, rec, checked.get(n) ?? null);
995
1040
  if (halted) return; // #4454: kept for the next resume
996
- running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n); save(); // ended without a result after all
1041
+ running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
997
1042
  }));
998
1043
  continue;
999
1044
  }
1000
1045
  const r = await p;
1001
- if (!r) { requeueLost(n); continue; }
1046
+ if (!r) {
1047
+ const why = adoptErrors.get(n) ?? (!adopt || !(rec?.pid || rec?.handle || rec?.remote) ? "no adoptable pid or handle" : "the lane ended without a result");
1048
+ requeueLost(n, why); continue;
1049
+ }
1002
1050
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1003
1051
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); } // released by the settle
1004
1052
  track(n, Promise.resolve(r).then((x) => settle(n, x, rec, checked.get(n) ?? null)));
@@ -1101,6 +1149,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1101
1149
  for (const e of fresh) {
1102
1150
  requeueApplied.add(requeueKey(e));
1103
1151
  const row = results.get(e.issue);
1152
+ // #5203: a quota-paused issue (pending, no row) is released: its notBefore and the pool hold go, so the next grant admits it.
1153
+ // #5241: so is an issue waiting out a deferral (e.g. lease-held by a cancelled batch's lane): the next pass admits it.
1154
+ if (!row && pending.includes(e.issue) && (quota.has(e.issue) || notBefore.has(e.issue)) && !running.has(e.issue)) {
1155
+ notBefore.delete(e.issue);
1156
+ if (!quota.has(e.issue)) { deferrals.delete(e.issue); update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (deferral released)` }); n++; continue; }
1157
+ try { const pool = remote?.identity?.(); if (pool) holds.clear(pool); } catch { /* fail-open */ }
1158
+ decided({ issue: e.issue, what: `released quota pause of #${e.issue} by ${e.by ?? "operator"} (forgedock orchestrate --requeue)`, why: e.reason || "operator decision", alternative: "wait for the account reset" });
1159
+ update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (quota pause released)` });
1160
+ n++;
1161
+ continue;
1162
+ }
1104
1163
  if (!row || !REQUEUABLE(row.outcome) || running.has(e.issue)) continue;
1105
1164
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1106
1165
  results.delete(e.issue);
@@ -1140,11 +1199,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1140
1199
  return n;
1141
1200
  };
1142
1201
  // #4376: one SIGTERM per running local lane (their teardown saves the work); remote lanes run to their result unless the cancel carries `stopRemote` (#4612).
1143
- const stopSent = new Set();
1202
+ // #5241: a stop not accepted is retried and, once the lane outlives the teardown timeout, reported (never silent).
1203
+ const stopSent = new Map(); // issue -> {at, accepted, since, reported}
1144
1204
  function stop(n, rec) {
1145
- if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true) || stopSent.has(n)) return; // #4612: remote lanes only when the cancel asked for it
1146
- stopSent.add(n);
1147
- try { Promise.resolve(stopLane(n, rec)).catch(() => {}); } catch { /* best effort */ }
1205
+ if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true)) return; // #4612: remote lanes only when the cancel asked for it
1206
+ const t = now(), s = stopSent.get(n) ?? { at: null, accepted: false, since: t, reported: false };
1207
+ stopSent.set(n, s);
1208
+ if (!s.reported && t - s.since >= stopTimeoutMs) {
1209
+ s.reported = true;
1210
+ const why = rec?.stopNote ?? (s.accepted ? "stop sent, the lane has not exited" : "stop not accepted");
1211
+ update({ issue: null, outcome: "cancelled", detail: `#${n} not confirmed stopped after ${Math.round(stopTimeoutMs / 1000)}s: ${why}; its lease stays held until it exits` });
1212
+ decided({ issue: n, what: `#${n} not confirmed stopped by the cancel`, why, alternative: "stop the lane by hand" });
1213
+ }
1214
+ if (s.accepted || (s.at !== null && t - s.at < stopRetryMs)) return;
1215
+ s.at = t;
1216
+ try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
1148
1217
  }
1149
1218
  // #4592: re-read the hold set; one decision and one row when it changes.
1150
1219
  const refreshHeld = () => {
@@ -1462,6 +1531,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1462
1531
  if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
1463
1532
  if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
1464
1533
  if ((getAdded || getRequeued || (getChildren && addsEpicChildren(autoChildren?.mode))) && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4408/#4550: an add or requeue while only lanes run
1534
+ if (getRequeued && pending.some((n) => quota.has(n) || notBefore.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5203: a --requeue releasing a quota pause
1465
1535
  if ((pfAll || pfRemote) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4866
1466
1536
  if (baseWait && pending.length && baseHeld.size) wake = Math.min(wake ?? pollMs, pollMs); // #5031: a landed commit releases on the next tick
1467
1537
  if (getBlocked && pending.length && blockedHit.size) wake = Math.min(wake ?? pollMs, pollMs); // #4773: a removed label releases on the next tick
@@ -1469,7 +1539,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1469
1539
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1470
1540
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1471
1541
  if (tripped) wake = null;
1472
- if (getCancelled && running.size && !cancelled) wake = Math.min(wake ?? pollMs, pollMs); // #4376: notice a cancel while lanes run
1542
+ if (getCancelled && running.size && (!cancelled || [...running.keys()].some((n) => { const x = stopSent.get(n); return x && !(x.accepted && x.reported); }))) wake = Math.min(wake ?? pollMs, pollMs); // #5241: a cancel keeps polling a lane whose stop is unconfirmed // #4376: notice a cancel while lanes run
1473
1543
  if (running.size) {
1474
1544
  if (wake === null) await race(running.values());
1475
1545
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }