forgedock 1.65.0 → 1.67.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.
- package/bin/config-schema.mjs +2 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +143 -19
- package/bin/forgedock.mjs +7 -0
- package/bin/help-text.mjs +3 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/advisory.test.mjs +49 -0
- package/bin/lean/amendment-schema.mjs +31 -0
- package/bin/lean/attempts.mjs +159 -0
- package/bin/lean/attempts.test.mjs +127 -0
- package/bin/lean/basered.mjs +55 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +13 -5
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +62 -0
- package/bin/lean/batch.test.mjs +119 -3
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/commentstate.mjs +41 -0
- package/bin/lean/commentstate.test.mjs +32 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +4 -2
- package/bin/lean/conformance.mjs +35 -3
- package/bin/lean/conformance.test.mjs +52 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/execution.mjs +31 -13
- package/bin/lean/execution.test.mjs +46 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/lean.mjs +130 -30
- package/bin/lean/lean.test.mjs +138 -47
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +74 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +84 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +202 -28
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/prompts.mjs +6 -10
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +38 -2
- package/bin/lean/recurrence.test.mjs +56 -1
- package/bin/lean/sandbox-remote.mjs +33 -2
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +19 -0
- package/bin/lean/schedd.mjs +97 -10
- package/bin/lean/schedd.test.mjs +138 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +37 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/verify.mjs +2 -1
- package/bin/pool/agent.mjs +46 -8
- package/bin/pool/cache-sweep.mjs +41 -4
- package/bin/pool/cli.mjs +28 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/lane-tools.mjs +21 -0
- package/bin/pool/mirror-seed.mjs +21 -2
- package/bin/pool/router.mjs +6 -2
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +1 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +2 -1
- package/scripts/check-devdocs-freshness.sh +1 -1
package/bin/lean/prompts.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { capText, FIX_CAPS, FIX_PROMPT_MAX, NARROW_CAPS, NARROW_PROMPT_MAX } fro
|
|
|
10
10
|
import { SPLIT_MIN_FILES, SPLIT_MIN_LINES } from "./decompose.mjs";
|
|
11
11
|
import { relaxationBlock } from "./relaxation.mjs";
|
|
12
12
|
import { visualReviewCheck } from "./ui-quality.mjs";
|
|
13
|
+
import { amendmentPromptLines, AMEND_KINDS } from "./amendment-schema.mjs"; // #5979
|
|
13
14
|
import { stampRule } from "./stagestamp.mjs";
|
|
14
15
|
import { FINDING_PITFALLS, PLANNER_TIGHTENING } from "./selfreview.mjs";
|
|
15
16
|
import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
|
|
@@ -262,12 +263,7 @@ export function builderImplementPrompt(mode = "local", { toolchain = null, spars
|
|
|
262
263
|
${HOST_RULES}${toolchainRule(toolchain)}${sparseRule(sparse)}${factsRule(facts)}${stampRule(stamp)}${remote ? `\n\n${VERIFY_RULES[mode]}` : ""}
|
|
263
264
|
|
|
264
265
|
The contract changes only through typed amendments in ${RESULT_FILE}, each with a why:
|
|
265
|
-
|
|
266
|
-
- {"kind":"add-requirement","requirement":{"id":"R9","quote":"<verbatim from the issue>","disposition":"deliver|defer|post-deploy"},"why":""}: a missed requirement.
|
|
267
|
-
- {"kind":"defer|post-deploy","requirement":"R#","why":"","check":"<id>"}: separate work or a post-deploy check, filed as a follow-up. Not "type"; unknown kinds are rejected. One requirement id per row. An impossible deliverable is a defer, not a new kind.
|
|
268
|
-
- {"kind":"amend-requirement","requirement":"R#","text":"<revised wording>","why":""}: reworded.
|
|
269
|
-
- {"kind":"supersedes","guard":"#N","why":""}: overrides a guard_broken failure; {"kind":"supersedes","mechanism":"<name>","why":""} retires every guard whose test this lane deletes.
|
|
270
|
-
- {"kind":"decision","decision":{"choice":"","anchors":["<base path>"],"supersedes":"<id>"},"why":""}: supersedes changes an H-row.
|
|
266
|
+
${amendmentPromptLines()}
|
|
271
267
|
New keys: translate, never copy English; status entries in place.
|
|
272
268
|
Never report a deliver requirement as "deferred" or "follow-up" without an amendment.
|
|
273
269
|
Never name or number migration files by hand; use the generator.
|
|
@@ -276,7 +272,7 @@ A [type:e2e] requirement needs a validate that runs a real e2e check (repo e2e s
|
|
|
276
272
|
A new keyword/regex classifier ships negative examples (inputs it must not match).
|
|
277
273
|
A forge.yaml outcome_evidence area change needs result outcome_evidence [{area,metric,corpus,before,after,better}] measured on recorded real inputs; its post-deploy checks get a numeric baseline.
|
|
278
274
|
A new workspace-package dependency in a package.json no deliverable names is blocked by the engine: add it through add-deliverable with a why naming the package, or do not add it.
|
|
279
|
-
If scripts/check-devdocs-freshness.sh exists, a behaviour change under its paths
|
|
275
|
+
If scripts/check-devdocs-freshness.sh exists, a behaviour change under its paths adds a new devdocs/decisions/<issue>-<slug>.md in the same change (a new file never conflicts with parallel lanes); run it against the base first.
|
|
280
276
|
|
|
281
277
|
Before writing ${RESULT_FILE}, after your last edit, run \`node ${FORGEDOCK_CLI} check\` in the worktree and fix until it passes; if it cannot pass, report the problem as blocked.
|
|
282
278
|
A \`FAIL review\` line from check is a finding the reviewer would raise; fix it. Also:
|
|
@@ -432,7 +428,7 @@ export function contractCorrectionPrompt(problems) {
|
|
|
432
428
|
|
|
433
429
|
/** #5089: the builder's amendments name an unknown kind or miss a field; one correction before the conformance gate. */
|
|
434
430
|
export function amendmentCorrectionPrompt(problems) {
|
|
435
|
-
return `The amendments in ${RESULT_FILE} are not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nRewrite them with a valid kind
|
|
431
|
+
return `The amendments in ${RESULT_FILE} are not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nRewrite them with a valid kind (${AMEND_KINDS.join(", ")}). A validate-row id (G2) is never a supersedes guard: use {"kind":"substitute-validate","validate":"G2","command":"<runnable equivalent>","why":""}. A deliverable that is impossible on this platform is {"kind":"defer","requirement":"R#","why":""}, not a changed deliverable. Edit only ${RESULT_FILE} (commit nothing else) and stop. Do not push or touch GitHub.`;
|
|
436
432
|
}
|
|
437
433
|
|
|
438
434
|
/** The one bounded correction round, in the builder's own session. */
|
|
@@ -448,9 +444,9 @@ export function structurePrompt(edges, mode = "local") {
|
|
|
448
444
|
return `This change adds dependencies between workspace packages that the frozen contract does not name:\n${edges.slice(0, 30).map((e) => `- ${e.from} -> ${e.to} (${e.kind}, ${e.manifest})`).join("\n")}\n\nFor each one, add it to the contract with a reason, or remove it: either record {"kind":"add-deliverable","path":"<that package.json>","why":"<names the package and why this dependency is right>"} in ${RESULT_FILE}, or drop the dependency from the package.json and the code that needs it. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
|
|
449
445
|
}
|
|
450
446
|
|
|
451
|
-
/** The repo's devdocs freshness rule failed on the committed change:
|
|
447
|
+
/** The repo's devdocs freshness rule failed on the committed change: add a decision record (conflict-free) and commit. */
|
|
452
448
|
export function docsPrompt(output, mode = "local") {
|
|
453
|
-
return `The repository's docs freshness check (scripts/check-devdocs-freshness.sh) fails on this change:\n${String(output ?? "").slice(0, 4000)}\n\
|
|
449
|
+
return `The repository's docs freshness check (scripts/check-devdocs-freshness.sh) fails on this change:\n${String(output ?? "").slice(0, 4000)}\n\nAdd a new devdocs/decisions/<issue>-<slug>.md describing the behaviour you changed in a few lines (a new file never conflicts with parallel lanes; edit a shared dossier only when the check accepts nothing else). ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
|
|
454
450
|
}
|
|
455
451
|
|
|
456
452
|
/**
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5978: standing orders. A batch started with `--select <query>` keeps owning every open issue the selector matches:
|
|
4
|
+
// matching issues join, closed or moved ones leave, and an issue that ended deferred / held / engine-error / conformance-failed is
|
|
5
|
+
// re-admitted by policy instead of by an operator. Pure helpers; the runner (orchestrate.mjs) feeds the results through its
|
|
6
|
+
// existing add/requeue seams (the query is issue-watch's `search` selector, handed to gh unchanged, K2; no import, so batch.mjs can use this module), so the DAG, priority and lane rules are the ones a `--add` already gets (K1).
|
|
7
|
+
|
|
8
|
+
/** How often the runner re-reads the selector ("every few minutes"). */
|
|
9
|
+
export const RECONCILE_MS = 3 * 60 * 1000;
|
|
10
|
+
/** Deferred issues retry with exponential backoff from this base, capped at DEFER_CAP_MS. */
|
|
11
|
+
export const DEFER_BASE_MS = 5 * 60 * 1000;
|
|
12
|
+
export const DEFER_CAP_MS = 2 * 60 * 60 * 1000;
|
|
13
|
+
/** A held / engine-error issue is a fresh attempt after this cooldown even if no version moved. */
|
|
14
|
+
export const HELD_COOLDOWN_MS = 6 * 60 * 60 * 1000;
|
|
15
|
+
/** The breaker auto-resets after this cooldown when its failures were environmental. */
|
|
16
|
+
export const BREAKER_COOLDOWN_MS = 15 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
/** gh args listing the open issues `select` matches (a GitHub search query: `no:milestone`, `milestone:X`, `label:Y`). */
|
|
19
|
+
export const selectArgs = (repo, select) => ["issue", "list", "-R", repo, "--state", "open", "--search", String(select), "--limit", "500", "--json", "number,labels,milestone,title"];
|
|
20
|
+
|
|
21
|
+
/** Open issue numbers (and labels) from the `gh issue list --json` output; null when it cannot be read (nobody leaves on a failed read). */
|
|
22
|
+
export function parseSelected(text) {
|
|
23
|
+
let v;
|
|
24
|
+
try { v = JSON.parse(text); } catch { return null; }
|
|
25
|
+
if (!Array.isArray(v)) return null;
|
|
26
|
+
return v.filter((x) => Number.isSafeInteger(x?.number) && x.number > 0).map((x) => ({ number: x.number, labels: (x.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean) }));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Diff the selector result against batch membership.
|
|
31
|
+
* @returns {{join:number[], leave:number[]}} join: open matches not in the batch; leave: pending members (not running, no result row) no longer open/matching
|
|
32
|
+
*/
|
|
33
|
+
export function diffSelection({ open, members, pending, running, results, matched = null }) {
|
|
34
|
+
const have = new Set(members), now = new Set(open.map((o) => o.number));
|
|
35
|
+
const join = [...now].filter((n) => !have.has(n)).sort((a, b) => a - b);
|
|
36
|
+
// #6022: only an issue the selector matched can leave it; env.* issues, children, --add and argv members never did
|
|
37
|
+
const leave = pending.filter((n) => (!matched || matched.has(n)) && !now.has(n) && !running.has(n) && !results.has(n));
|
|
38
|
+
return { join, leave };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Human codes (credentials, spend, customer, promotion, product decision): the only reasons an issue may stay unscheduled. */
|
|
42
|
+
const HUMAN = /\b(credentials?|secrets?\b.*\b(needed|missing|required)|api[ -]?keys?|spend|billing|payment|budget approval|customers?|promotion|promote|product decision|needs?[- ]decision|human[- ]code)\b/i;
|
|
43
|
+
export const HUMAN_LABEL = /^(human[:/-].+|needs?-(credentials|spend|customer|promotion|product-decision))$/i;
|
|
44
|
+
export const humanCode = (row, labels = []) => labels.some((l) => HUMAN_LABEL.test(l)) || (row?.outcome === "needs-human" && !row?.conformance && HUMAN.test(String(row?.detail ?? "")));
|
|
45
|
+
|
|
46
|
+
/** Failure details that are environmental (VM restart, mirror, network): a breaker tripped by them may close itself (#5947 classes). */
|
|
47
|
+
export const environmentalDetail = (detail) => /\b(vm (restart|reboot)|restart(ed|ing)|mirror|network|dns|econn(reset|refused)|etimedout|connection (reset|refused|timed out)|net\.transient|sandbox\.lost|unreachable)\b/i.test(String(detail ?? ""));
|
|
48
|
+
|
|
49
|
+
/** @returns {number} ms to wait before deferred attempt number `n` (0-based) is retried */
|
|
50
|
+
export const backoffMs = (n) => Math.min(DEFER_CAP_MS, DEFER_BASE_MS * 2 ** Math.max(0, Math.min(n, 16)));
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Re-admission policy for rows that ended without success. `state` is `Map<issue, {n, since, version, base, conformanceTried}>`
|
|
54
|
+
* (kept in batch state); it is updated in place. Returns the issues to requeue with the reason, and the parked "needs decision" list.
|
|
55
|
+
* @param {{results:Map<number,object>, state:Map<number,object>, now:number, version:string|null, base:string|null, labels?:(n:number)=>string[]}} p
|
|
56
|
+
*/
|
|
57
|
+
export function readmitDue({ results, state, now, version = null, base = null, labels = () => [] }) {
|
|
58
|
+
const requeue = [], parked = [];
|
|
59
|
+
for (const [n, row] of results) {
|
|
60
|
+
const o = row?.outcome;
|
|
61
|
+
const isConf = Boolean(row?.conformance) && o === "needs-human";
|
|
62
|
+
if (!["deferred", "held", "engine-error"].includes(o) && !isConf) { state.delete(n); continue; }
|
|
63
|
+
if (humanCode(row, labels(n))) continue;
|
|
64
|
+
let s = state.get(n);
|
|
65
|
+
if (!s || s.outcome !== o) { s = { n: s?.n ?? 0, since: now, version, base, outcome: o, conformanceTried: s?.conformanceTried ?? 0 }; state.set(n, s); }
|
|
66
|
+
if (o === "deferred") {
|
|
67
|
+
if (now - s.since >= backoffMs(s.n)) { requeue.push({ issue: n, reason: `deferred: retry ${s.n + 1} after backoff (cap ${DEFER_CAP_MS / 3600000} h)` }); state.set(n, { ...s, n: s.n + 1, since: now, outcome: null }); }
|
|
68
|
+
} else if (isConf) {
|
|
69
|
+
if (s.conformanceTried >= 1) { parked.push({ issue: n, why: "conformance failed after one retry on a moved base" }); continue; }
|
|
70
|
+
if (base && s.base && base !== s.base) { requeue.push({ issue: n, reason: "conformance: one more attempt, the base moved" }); state.set(n, { ...s, conformanceTried: s.conformanceTried + 1, since: now, outcome: null, base }); }
|
|
71
|
+
else if (!s.base && base) state.set(n, { ...s, base });
|
|
72
|
+
} else {
|
|
73
|
+
const moved = version && s.version && version !== s.version;
|
|
74
|
+
if (moved || now - s.since >= HELD_COOLDOWN_MS) { requeue.push({ issue: n, reason: moved ? `${o}: agent/lane-image version changed` : `${o}: cooldown elapsed, fresh attempt` }); state.set(n, { ...s, since: now, version, outcome: null }); }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { requeue, parked };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The breaker may close itself: an environmental failure signature, the cooldown elapsed and the pool healthy again.
|
|
82
|
+
* (Lives in clear-breaker.mjs as `decideAutoReset`; re-exported here for the policy tests.)
|
|
83
|
+
*/
|
|
84
|
+
export { decideAutoReset } from "./clear-breaker.mjs";
|
|
85
|
+
|
|
86
|
+
/** One "needs decision" digest for the parked issues: a single decision body, empty string when nothing is parked. */
|
|
87
|
+
export const needsDecisionDigest = (parked) => (parked.length ? `needs decision (${parked.length}): ${parked.map((p) => `#${p.issue} (${p.why})`).join("; ")}` : "");
|
|
88
|
+
|
|
89
|
+
/** Whether a merge into `lane` leaves the issue open on GitHub (`Closes` only fires on the default branch): staging / milestone lanes. */
|
|
90
|
+
export const closesManually = (lane, defaultBranch = "main") => Boolean(lane) && lane !== defaultBranch && /^(staging|milestone\/|release\/|lane\/)/.test(String(lane));
|
package/bin/lean/recurrence.mjs
CHANGED
|
@@ -54,9 +54,20 @@ export function pathsOverlap(a, b) {
|
|
|
54
54
|
return Boolean(x && y) && (x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`));
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/** #5979: backticked error/outcome-code/test signatures of the issue body (identifier-shaped, not a path). */
|
|
58
|
+
function symptomTerms(body) {
|
|
59
|
+
return [...new Set([...String(body ?? "").matchAll(/`([A-Za-z][\w.:-]{3,79})`/g)].map((m) => m[1].toLowerCase()).filter((t) => !/\.(?:m?[jt]sx?|md|json|ya?ml|py|sh)$/.test(t)))];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** #5979: a subjectHistory row shares the issue's symptom: it matched on a code-shaped term (outcome code, error name, symbol), on two or more terms, or its title carries a backticked signature of the issue. */
|
|
63
|
+
function symptomMatch(row, terms) {
|
|
64
|
+
const m = (row?.matched ?? []).map(String);
|
|
65
|
+
return m.some((t) => /[._:-]|\d|[a-z][A-Z]|^[A-Z0-9_]{3,}$/.test(t)) || m.length >= 2 || terms.some((t) => String(row?.title ?? "").toLowerCase().includes(t));
|
|
66
|
+
}
|
|
67
|
+
|
|
57
68
|
/**
|
|
58
69
|
* Count earlier merged fixes on the same symptom and the same area. A subjectHistory row counts when it is a merged PR
|
|
59
|
-
* whose files (`mergedPrFiles[number]`) overlap a path the issue names. A `Recurs #n` link is an explicit symptom match:
|
|
70
|
+
* whose files (`mergedPrFiles[number]`) overlap a path the issue names AND that shares the symptom (#5979: path-only overlap never counts). A `Recurs #n` link is an explicit symptom match:
|
|
60
71
|
* it counts when its files overlap or are unknown (the author declared the same area). Rows without overlap never count.
|
|
61
72
|
* @returns {{recurs:boolean, count:number, threshold:number, evidence:{number:number, title:string, via:string, paths:string[]}[], reason:string}}
|
|
62
73
|
*/
|
|
@@ -64,9 +75,11 @@ export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", nam
|
|
|
64
75
|
const named = [...new Set((namedPaths ?? []).map(clean).filter(Boolean))];
|
|
65
76
|
const filesOf = (n) => (mergedPrFiles instanceof Map ? mergedPrFiles.get(n) : mergedPrFiles?.[n]);
|
|
66
77
|
const evidence = [], seen = new Set();
|
|
78
|
+
const sym = symptomTerms(body);
|
|
67
79
|
for (const r of rows ?? []) {
|
|
68
80
|
const n = Number(r?.number);
|
|
69
81
|
if (!Number.isSafeInteger(n) || seen.has(n) || r?.kind !== "PR" || r?.status !== "merged") continue;
|
|
82
|
+
if (!symptomMatch(r, sym)) continue; // #5979: path overlap alone is the same area, not the same symptom
|
|
70
83
|
const paths = (filesOf(n) ?? []).map(clean).filter((f) => named.some((p) => pathsOverlap(f, p)));
|
|
71
84
|
if (!paths.length) continue;
|
|
72
85
|
seen.add(n);
|
|
@@ -88,14 +101,28 @@ export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", nam
|
|
|
88
101
|
return { recurs, count, threshold: t, evidence, reason };
|
|
89
102
|
}
|
|
90
103
|
|
|
104
|
+
/** #6016: a staging->default release PR head (`release/...`). */
|
|
105
|
+
export const isReleaseHead = (ref) => /^release\//.test(String(ref ?? ""));
|
|
106
|
+
|
|
91
107
|
/**
|
|
92
108
|
* The engine-side gather: subjectHistory rows plus one file-list read per merged row (capped). `io`: {gh, git}. Never
|
|
93
109
|
* throws: a failed source contributes nothing and lands in `errors`.
|
|
94
110
|
*/
|
|
95
|
-
export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [] }) {
|
|
111
|
+
export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [], createdAt = null }) {
|
|
96
112
|
const errors = [];
|
|
97
113
|
let rows = [];
|
|
98
114
|
try { const h = await subjectHistory({ io, repo, issue, title, body, base, exclude }); rows = h.rows ?? []; errors.push(...(h.errors ?? [])); } catch (e) { errors.push(`recurrence: ${String(e?.message ?? e).slice(0, 80)}`); }
|
|
115
|
+
// #6016: a release PR (head release/*) touches every shipped file, and a PR merged after the issue was filed cannot be an
|
|
116
|
+
// earlier fix that did not hold: neither is evidence. A row whose metadata cannot be read stays (explicit Recurs links too).
|
|
117
|
+
const created = Date.parse(createdAt ?? "");
|
|
118
|
+
const notEvidence = new Set();
|
|
119
|
+
for (const r of rows.filter((x) => x?.kind === "PR" && x?.status === "merged").slice(0, MAX_RECURRENCE_ROWS)) {
|
|
120
|
+
try {
|
|
121
|
+
const m = JSON.parse(String(await io.gh(["api", `repos/${repo}/pulls/${Number(r.number)}`, "--jq", "{head: .head.ref, merged: .merged_at}"])));
|
|
122
|
+
if (isReleaseHead(m?.head) || (Number.isFinite(created) && Date.parse(m?.merged ?? "") > created)) notEvidence.add(Number(r.number));
|
|
123
|
+
} catch { /* unreadable: keep the row */ }
|
|
124
|
+
}
|
|
125
|
+
rows = rows.filter((r) => !notEvidence.has(Number(r?.number)));
|
|
99
126
|
const wanted = [...new Set([...rows.filter((r) => r?.kind === "PR" && r?.status === "merged").map((r) => Number(r.number)), ...recursLinks(body)])].slice(0, MAX_RECURRENCE_ROWS);
|
|
100
127
|
const mergedPrFiles = {};
|
|
101
128
|
if (namedPaths.length) {
|
|
@@ -121,6 +148,12 @@ Prefer "delete" or "replace" of the earlier fixes; "extend" needs its reason in
|
|
|
121
148
|
/** #5751: a design lane's contract must carry design {why_failed, disposition delete|replace|extend, outcome {metric, target}}. */
|
|
122
149
|
export function designContractFailures(contract, detection) {
|
|
123
150
|
if (!detection?.recurs) return [];
|
|
151
|
+
// #5918/#5979: a design block is demanded once. Asked for on an earlier run and still absent, it is not demanded again: the repeat parks (failure.repeated) for a decision.
|
|
152
|
+
if (detection.demanded) {
|
|
153
|
+
const d0 = contract?.design;
|
|
154
|
+
if (d0 && typeof d0 === "object" && !Array.isArray(d0)) return designContractFailures(contract, { ...detection, demanded: false });
|
|
155
|
+
return [{ code: C.FAILURE_REPEATED, kind: "design_missing_repeated", detail: `recurring issue (${detection.count} earlier fixes): the design block was already demanded on an earlier run and is still missing; parked for a decision instead of demanding it again` }];
|
|
156
|
+
}
|
|
124
157
|
const d = contract?.design, problems = [];
|
|
125
158
|
const s = (v) => typeof v === "string" && v.trim();
|
|
126
159
|
if (!d || typeof d !== "object" || Array.isArray(d)) problems.push("no design block");
|
|
@@ -131,3 +164,6 @@ export function designContractFailures(contract, detection) {
|
|
|
131
164
|
}
|
|
132
165
|
return problems.length ? [{ code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: `recurring issue (${detection.count} earlier fixes) routed to a design lane: ${problems.join("; ")}` }] : [];
|
|
133
166
|
}
|
|
167
|
+
|
|
168
|
+
/** #5979: true when an earlier NEEDS_HUMAN/PARKED comment of the issue already reported the missing design block. */
|
|
169
|
+
export const designDemanded = (comments) => (Array.isArray(comments) ? comments : []).some((c) => /<!--\s*FORGE:(?:NEEDS_HUMAN|PARKED)/.test(String(c?.body ?? "")) && /routed to a design lane:/.test(String(c?.body ?? "")));
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { parseRecurrenceConfig, detectRecurrence, recursLinks, pathsOverlap, recurrenceFacts, designLaneNote, designContractFailures } from "./recurrence.mjs";
|
|
5
|
+
import { parseRecurrenceConfig, detectRecurrence, recursLinks, pathsOverlap, recurrenceFacts, designLaneNote, designContractFailures, isReleaseHead } from "./recurrence.mjs";
|
|
6
6
|
|
|
7
7
|
const row = (number, o = {}) => ({ number, kind: "PR", status: "merged", title: `fix leak ${number}`, matched: ["reservation", "leak"], ...o });
|
|
8
8
|
const NAMED = ["src/billing/reserve.js"];
|
|
@@ -76,6 +76,27 @@ describe("recurrence detection (#5751)", () => {
|
|
|
76
76
|
});
|
|
77
77
|
});
|
|
78
78
|
|
|
79
|
+
describe("recurrence evidence excludes release PRs and later merges (#6016)", () => {
|
|
80
|
+
const gh = (meta) => async (a) => {
|
|
81
|
+
const j = a.join(" ");
|
|
82
|
+
if (j.includes("search/issues")) return [10, 11, 12].map((n) => JSON.stringify({ number: n, title: `pr ${n}`, pr: true, merged: true })).join("\n");
|
|
83
|
+
const f = /pulls\/(\d+)\/files/.exec(j); if (f) return "src/billing/reserve.js\n";
|
|
84
|
+
const m = /pulls\/(\d+)$/.exec(a[1] ?? ""); if (m) return JSON.stringify(meta[m[1]]);
|
|
85
|
+
throw new Error("unexpected " + j);
|
|
86
|
+
};
|
|
87
|
+
it("a release PR and a PR merged after the issue was filed are not earlier fixes", async () => {
|
|
88
|
+
const meta = { 10: { head: "release/20261123-1", merged: "2026-11-01T00:00:00Z" }, 11: { head: "feat/x", merged: "2026-11-20T00:00:00Z" }, 12: { head: "feat/y", merged: "2026-11-02T00:00:00Z" } };
|
|
89
|
+
const d = await recurrenceFacts({ io: { gh: gh(meta) }, repo: "o/r", issue: 7, title: "reservation leak", body: "See src/billing/reserve.js", namedPaths: NAMED, threshold: 2, createdAt: "2026-11-10T00:00:00Z" });
|
|
90
|
+
assert.deepEqual(d.evidence.map((e) => e.number), [12]);
|
|
91
|
+
assert.equal(d.recurs, false);
|
|
92
|
+
});
|
|
93
|
+
it("isReleaseHead matches only release/ heads", () => {
|
|
94
|
+
assert.equal(isReleaseHead("release/1"), true);
|
|
95
|
+
assert.equal(isReleaseHead("feat/release/1"), false);
|
|
96
|
+
assert.equal(isReleaseHead(null), false);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
79
100
|
describe("design lane (#5751)", () => {
|
|
80
101
|
const det = detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: NAMED, 11: NAMED }, namedPaths: NAMED });
|
|
81
102
|
it("the plan note names the earlier fixes and asks why they failed, delete or replace, a measurable outcome and allows a split", () => {
|
|
@@ -97,3 +118,37 @@ describe("design lane (#5751)", () => {
|
|
|
97
118
|
assert.deepEqual(designContractFailures({}, { recurs: false }), [], "an ordinary lane needs no design block");
|
|
98
119
|
});
|
|
99
120
|
});
|
|
121
|
+
|
|
122
|
+
import { designDemanded } from "./recurrence.mjs";
|
|
123
|
+
describe("symptom match and one-time design demand (#5979)", () => {
|
|
124
|
+
const files = { 10: NAMED, 11: NAMED };
|
|
125
|
+
it("path-only overlap without a symptom match does not recur", () => {
|
|
126
|
+
const rows = [row(10, { matched: ["billing"], title: "tidy billing" }), row(11, { matched: ["reserve"], title: "rename" })];
|
|
127
|
+
const d = detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED, body: "the page is slow" });
|
|
128
|
+
assert.equal(d.recurs, false);
|
|
129
|
+
assert.equal(d.count, 0);
|
|
130
|
+
});
|
|
131
|
+
it("a code-shaped symptom plus path still recurs", () => {
|
|
132
|
+
const rows = [row(10, { matched: ["reservation.leak"] }), row(11, { matched: ["reservation.leak"] })];
|
|
133
|
+
assert.equal(detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED }).recurs, true);
|
|
134
|
+
});
|
|
135
|
+
it("a backticked signature of the issue in the row title is a symptom match", () => {
|
|
136
|
+
const rows = [row(10, { matched: ["billing"], title: "fix `ERR_RESERVE` crash" }), row(11, { matched: ["billing"], title: "again ERR_RESERVE" })];
|
|
137
|
+
assert.equal(detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED, body: "throws `ERR_RESERVE`" }).recurs, true);
|
|
138
|
+
});
|
|
139
|
+
it("a Recurs link is unchanged", () => {
|
|
140
|
+
assert.equal(detectRecurrence({ rows: [], mergedPrFiles: { 5: NAMED, 6: NAMED }, body: "Recurs #5, #6", namedPaths: NAMED }).recurs, true);
|
|
141
|
+
});
|
|
142
|
+
it("a design block already demanded on an earlier run is not demanded again", () => {
|
|
143
|
+
const det = { recurs: true, count: 2, demanded: true };
|
|
144
|
+
const f = designContractFailures({}, det);
|
|
145
|
+
assert.equal(f.length, 1);
|
|
146
|
+
assert.equal(f[0].kind, "design_missing_repeated");
|
|
147
|
+
assert.equal(designContractFailures({}, { ...det, demanded: false })[0].kind, "design_missing");
|
|
148
|
+
assert.deepEqual(designContractFailures({ design: { why_failed: "w", disposition: "replace", outcome: { metric: "m", target: "t" } } }, det), []);
|
|
149
|
+
});
|
|
150
|
+
it("designDemanded reads an earlier NEEDS_HUMAN naming the design lane", () => {
|
|
151
|
+
assert.equal(designDemanded([{ body: "<!-- FORGE:NEEDS_HUMAN -->\nrecurring issue (2 earlier fixes) routed to a design lane: no design block" }]), true);
|
|
152
|
+
assert.equal(designDemanded([{ body: "<!-- FORGE:NEEDS_HUMAN -->\nother" }]), false);
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -78,6 +78,8 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
78
78
|
const e = new Error(`sandbox ${what}: HTTP ${r.status}${who ? ` (${who} auth${reason ? `: ${reason}` : ""})` : ""}`);
|
|
79
79
|
e.status = r.status;
|
|
80
80
|
if (hop) e.hop = hop;
|
|
81
|
+
if (typeof r.data?.code === "string" && r.data.code.startsWith("pool.")) e.poolCode = r.data.code; // #5985: the pool's refusal code reaches the deferral row
|
|
82
|
+
if (r.data?.live && typeof r.data.live === "object") e.live = { load_per_core: r.data.live.load_per_core, mem_available_gb: r.data.live.mem_available_gb };
|
|
81
83
|
if (reason) e.reason = reason;
|
|
82
84
|
if ([500, 502, 503, 504].includes(r.status)) e.transient = true; // #4672: a router restart or gateway blip, retried by the lane poll; #5095: 500 too
|
|
83
85
|
if (r.status === 429 || r.status === 503) e.retryable = true;
|
|
@@ -141,8 +143,24 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
141
143
|
const sb = r.data.sandboxes && typeof r.data.sandboxes === "object" ? Object.keys(r.data.sandboxes) : [];
|
|
142
144
|
return { agents, total: int(r.data.remote_lanes) ?? sb.filter((id) => id.startsWith("fdrsbx-")).length };
|
|
143
145
|
},
|
|
146
|
+
/** #5985: finished-lane usage rows (`{repo, cpu_avg, ...}`) of every pool agent (`GET /agents/:name/usage`), for the light/heavy lane class. A bad answer throws. */
|
|
147
|
+
async usageHistory() {
|
|
148
|
+
const r = await call("GET", "/agents");
|
|
149
|
+
if (!r.ok) throw fail("usage history", r);
|
|
150
|
+
const names = (Array.isArray(r.data?.agents) ? r.data.agents : []).map((a) => a?.name).filter((n) => typeof n === "string");
|
|
151
|
+
const rows = [];
|
|
152
|
+
for (const n of names) { try { const u = await call("GET", `/agents/${encodeURIComponent(n)}/usage`); if (u.ok && Array.isArray(u.data?.rows)) rows.push(...u.data.rows); } catch { /* one agent down: its rows are unknown */ } }
|
|
153
|
+
return rows;
|
|
154
|
+
},
|
|
144
155
|
async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
|
|
145
156
|
async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
|
|
157
|
+
/** #5991: the pool agent that runs `agent` (any agent when unnamed) answers `GET /agents` and is not paused; errors propagate. */
|
|
158
|
+
async agentOnline(agent = null) {
|
|
159
|
+
const r = await call("GET", "/agents");
|
|
160
|
+
const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
|
|
161
|
+
if (!list) throw fail("agents", r);
|
|
162
|
+
return list.some((a) => a?.ok === true && !a.paused && (!agent || a.name === agent));
|
|
163
|
+
},
|
|
146
164
|
async capacity() {
|
|
147
165
|
// `free` (#4540) and agent liveness `online`/`total` (#4547) are each optional; none valid is unknown.
|
|
148
166
|
const ok = (v) => Number.isInteger(v) && v >= 0;
|
|
@@ -152,13 +170,19 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
152
170
|
reached = true;
|
|
153
171
|
if (r.ok) { const { free, online, total } = r.data ?? {}; out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}) }; }
|
|
154
172
|
} catch (e) { out = {}; lastErr = e; }
|
|
155
|
-
if (out.online === undefined) {
|
|
173
|
+
if (out.online === undefined || out.load_per_core === undefined) {
|
|
156
174
|
// #4788: a router without /status liveness: online = agents answering and not paused, as bin/pool/router.mjs status() does.
|
|
157
175
|
try {
|
|
158
176
|
const r = await call("GET", "/agents");
|
|
159
177
|
reached = true;
|
|
160
178
|
const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
|
|
161
|
-
if (list) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
|
|
179
|
+
if (list && out.online === undefined) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
|
|
180
|
+
// #5985: live host figures (worst agent); a pool reporting none leaves them unknown
|
|
181
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
182
|
+
const loads = (list ?? []).map((a) => num(a?.load_per_core ?? a?.live?.load_per_core)).filter((v) => v !== null);
|
|
183
|
+
const mems = (list ?? []).map((a) => num(a?.mem_available_gb ?? a?.live?.mem_available_gb)).filter((v) => v !== null);
|
|
184
|
+
if (loads.length) out = { ...out, load_per_core: Math.max(...loads) };
|
|
185
|
+
if (mems.length) out = { ...out, mem_available_gb: Math.min(...mems) };
|
|
162
186
|
} catch (e) { lastErr = e; /* liveness stays unknown */ }
|
|
163
187
|
}
|
|
164
188
|
// #5048 (release review REG-2): a router that answered neither call is unreachable: throw, so the pool is marked down
|
|
@@ -302,11 +326,18 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
302
326
|
if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
|
|
303
327
|
return rest;
|
|
304
328
|
},
|
|
329
|
+
/** #5991: is the pool agent of this handle answering? Unknown (null) without transport support; transport errors propagate. */
|
|
330
|
+
async agentOnline(h) {
|
|
331
|
+
if (typeof transport.agentOnline !== "function") return null;
|
|
332
|
+
return transport.agentOnline(typeof h?.agent === "string" && h.agent ? h.agent : null);
|
|
333
|
+
},
|
|
305
334
|
async capacity() {
|
|
306
335
|
// #5048: no capacity() is unknown (null); a transport error propagates, so the caller can report the pool down
|
|
307
336
|
if (typeof transport.capacity !== "function") return null;
|
|
308
337
|
return (await transport.capacity()) ?? null;
|
|
309
338
|
},
|
|
339
|
+
/** #5985: the pool's usage-history rows; null when the transport has none. */
|
|
340
|
+
async usageHistory() { return typeof transport.usageHistory === "function" ? (await transport.usageHistory()) ?? null : null; },
|
|
310
341
|
/** #4612: a graceful stop at the lane's checkpoint; false when unsupported or failed. Never destroys the sandbox. */
|
|
311
342
|
async stop(h) {
|
|
312
343
|
if (typeof transport.stop !== "function") { stopWhy.set(h.id, "the transport has no stop"); return false; }
|
package/bin/lean/sched.mjs
CHANGED
|
@@ -25,6 +25,7 @@ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statS
|
|
|
25
25
|
import { homedir } from "node:os";
|
|
26
26
|
import { join } from "node:path";
|
|
27
27
|
import { writeAtomic } from "./batch.mjs";
|
|
28
|
+
import { formatConcurrency } from "./concurrency.mjs";
|
|
28
29
|
|
|
29
30
|
export const DEFAULT_PRIORITY = 2;
|
|
30
31
|
export const LOCK_WAIT_MS = 2000;
|
|
@@ -260,6 +261,24 @@ export function remoteLines(st, { agentOf = null } = {}) {
|
|
|
260
261
|
return out;
|
|
261
262
|
}
|
|
262
263
|
|
|
264
|
+
/**
|
|
265
|
+
* #5985: `sched show`/status lines `batch B concurrency: running/K/ceiling (limiting factor)`, from each running batch's last
|
|
266
|
+
* controller event in `log.jsonl` (`eventsOf(batch) -> rows`); `achieved` is running over the configured ceiling. Empty when none logged.
|
|
267
|
+
*/
|
|
268
|
+
export function concurrencyLines(st, { eventsOf = null } = {}) {
|
|
269
|
+
if (typeof eventsOf !== "function") return [];
|
|
270
|
+
const batches = [...new Set([...(st?.slots ?? []), ...(st?.remote ?? [])].map((e) => e.batch).filter(Boolean))];
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const b of batches) {
|
|
273
|
+
let last = null;
|
|
274
|
+
try { for (const r of eventsOf(b) ?? []) if (r?.event === "concurrency") last = r; } catch { last = null; }
|
|
275
|
+
if (!last || !Number.isInteger(last.ceiling)) continue;
|
|
276
|
+
const running = Number.isInteger(last.running) ? last.running : 0;
|
|
277
|
+
out.push(`batch ${b} ${formatConcurrency({ running, k: last.k, ceiling: last.ceiling, factor: last.factor })}; achieved ${running} of ${last.ceiling} configured`);
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
|
|
263
282
|
/** #5847: batch-start report of the effective concurrency K, the host cap and which source set it; pure and read-only. */
|
|
264
283
|
export function describeConcurrency({ parallel, parallelFrom = "default", registryCap = null, globalParallel = null, derivedCap = null, yamlFound = true, cwd = "." } = {}) {
|
|
265
284
|
const pos = (n) => (Number.isInteger(n) && n > 0 ? n : null);
|
package/bin/lean/sched.test.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
8
|
+
import { concurrencyLines, describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
9
9
|
import { orchestrate, estimateLaneMinutes, laneHistory, formatEstimateSummary, EST_DEFAULT_MIN, POST_DEPLOY_EST_MIN } from "./orchestrate.mjs";
|
|
10
10
|
import { schedFromCli } from "../engine-cli.mjs";
|
|
11
11
|
|
|
@@ -601,3 +601,13 @@ describe("describeConcurrency", () => {
|
|
|
601
601
|
assert.deepEqual(describeConcurrency({ parallel: 1 }).warnings, []);
|
|
602
602
|
});
|
|
603
603
|
});
|
|
604
|
+
|
|
605
|
+
describe("concurrencyLines (#5985)", () => {
|
|
606
|
+
it("prints running/K/ceiling (limiting factor) with achieved vs configured from the last controller event", () => {
|
|
607
|
+
const rows = [{ event: "concurrency", k: 8, ceiling: 8, running: 8, factor: "ceiling" }, { issue: 3, outcome: "merged" }, { event: "concurrency", k: 4, ceiling: 8, running: 3, factor: "host_load" }];
|
|
608
|
+
const st = { slots: [{ batch: "b1" }], remote: [{ batch: "b1" }, { batch: "b2" }] };
|
|
609
|
+
const lines = concurrencyLines(st, { eventsOf: (b) => (b === "b1" ? rows : []) });
|
|
610
|
+
assert.deepEqual(lines, ["batch b1 concurrency: 3/4/8 (host_load); achieved 3 of 8 configured"]);
|
|
611
|
+
assert.deepEqual(concurrencyLines(st), []);
|
|
612
|
+
});
|
|
613
|
+
});
|
|
@@ -55,9 +55,16 @@ export function tickText(c) {
|
|
|
55
55
|
* @returns the check, plus `killed` (and `started` when it started one)
|
|
56
56
|
*/
|
|
57
57
|
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
58
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null } = {}) {
|
|
58
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, restart = null, batchVerdicts = null, unit = null, emit = null } = {}) {
|
|
59
59
|
const c = stallCheck({ dir, stallMs, now, alive });
|
|
60
60
|
if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
|
|
61
|
+
// #5966: the unit says active but no daemon answers (no live pid/heartbeat): alert and restart it, whether or not batches are unfinished
|
|
62
|
+
if (c.status === "down" && restart && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
|
|
63
|
+
log(`schedd watchdog: ALERT unit is active but no daemon answers (schedd status: not running); restarting the unit`);
|
|
64
|
+
try { emit?.({ type: "schedd.unit-no-daemon", at: now() }); } catch { /* advisory */ }
|
|
65
|
+
try { await restart(); } catch (e) { log(`schedd watchdog: restart failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false, restarted: false }; }
|
|
66
|
+
return { ...c, killed: null, alerted: true, started: true, restarted: true }; // `systemctl start` is a no-op on an active unit, so this must be a restart
|
|
67
|
+
}
|
|
61
68
|
if (c.status === "down" && start) {
|
|
62
69
|
let ids = [];
|
|
63
70
|
try { ids = unfinished() ?? []; } catch { ids = []; }
|
|
@@ -68,4 +68,23 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
|
68
68
|
assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
|
|
69
69
|
assert.equal(bestEffortRenice(() => {}), true);
|
|
70
70
|
});
|
|
71
|
+
|
|
72
|
+
it("#5966: a down daemon while the unit is active alerts, emits an event and restarts the unit, even with no unfinished batches", async () => {
|
|
73
|
+
const dir = tmpDir("schedd-wd-unit-"), lines = [], events = [];
|
|
74
|
+
let starts = 0, restarts = 0;
|
|
75
|
+
const run = (unit, restart = async () => { restarts++; }) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, restart, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
|
|
76
|
+
const r = await run(() => "active");
|
|
77
|
+
assert.equal(r.started, true);
|
|
78
|
+
assert.equal(r.alerted, true);
|
|
79
|
+
assert.equal(r.restarted, true);
|
|
80
|
+
assert.deepEqual([restarts, starts], [1, 0], "an active unit is restarted, never started");
|
|
81
|
+
assert.equal(events[0].type, "schedd.unit-no-daemon");
|
|
82
|
+
assert.ok(lines.some((l) => l.includes("ALERT")));
|
|
83
|
+
await run(() => "inactive");
|
|
84
|
+
await run(() => null);
|
|
85
|
+
assert.equal(restarts, 1, "an inactive or absent unit with nothing unfinished is left down");
|
|
86
|
+
const f = await run(() => "active", async () => { throw new Error("denied"); });
|
|
87
|
+
assert.deepEqual([f.started, f.restarted, f.alerted], [false, false, true]);
|
|
88
|
+
assert.match(lines.at(-1), /restart failed: denied/);
|
|
89
|
+
});
|
|
71
90
|
});
|