opencode-model-router 2.8.0 → 2.9.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/CHANGELOG.md +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
|
@@ -0,0 +1,3083 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration queue (plan 3.2.3, design memo 3.2.1 in docs/qa/critical-path-execution/phase-3.2.md).
|
|
3
|
+
*
|
|
4
|
+
* The only module that journals integration entries. It owns every move of the integration branch
|
|
5
|
+
* (I1: `merge --ff-only` to a checked commit, then a CAS on the branch ref) and journals every step
|
|
6
|
+
* before and after its git writes (I4).
|
|
7
|
+
*/
|
|
8
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
+
import { link, mkdir, open, readdir, readFile, rename, unlink } from "node:fs/promises";
|
|
10
|
+
import * as nodePath from "node:path";
|
|
11
|
+
import { stripUrlUserinfo } from "../../router/git-tools";
|
|
12
|
+
import {
|
|
13
|
+
AX_MAX_CHARS,
|
|
14
|
+
CHECK_TRIES,
|
|
15
|
+
DETAIL_MAX_BYTES,
|
|
16
|
+
OUTPUT_TAIL_BYTES,
|
|
17
|
+
type CheckErrorReason,
|
|
18
|
+
type CheckResult,
|
|
19
|
+
type CreateRefOutcome,
|
|
20
|
+
type IntegrateGit,
|
|
21
|
+
type IntegrationChecks,
|
|
22
|
+
type Logger,
|
|
23
|
+
type ResolvedCommand,
|
|
24
|
+
type WriteGuard,
|
|
25
|
+
type WritePurpose,
|
|
26
|
+
} from "./checks";
|
|
27
|
+
import type { GitOps } from "../git";
|
|
28
|
+
import { executorServiceObservation, type ServiceObservation } from "../observations";
|
|
29
|
+
import type { ServiceIdentity } from "../../compat/v2-observations";
|
|
30
|
+
import {
|
|
31
|
+
ExecutorError,
|
|
32
|
+
TASK_TRANSITIONS,
|
|
33
|
+
formatInboxId,
|
|
34
|
+
nextInboxNumber,
|
|
35
|
+
type BatchBuilder,
|
|
36
|
+
type Clock,
|
|
37
|
+
type ExecutorEvent,
|
|
38
|
+
type ExecutorEventInput,
|
|
39
|
+
type GateState,
|
|
40
|
+
type GateTrigger,
|
|
41
|
+
type InboxItem,
|
|
42
|
+
type InboxKind,
|
|
43
|
+
type IntegrationEntry,
|
|
44
|
+
type IntegrationListener,
|
|
45
|
+
type IntegrationQueue,
|
|
46
|
+
type IntegrationStep,
|
|
47
|
+
type IntegrationStepResult,
|
|
48
|
+
type IsoTime,
|
|
49
|
+
type JsonValue,
|
|
50
|
+
type LeaseService,
|
|
51
|
+
type LedgerV1,
|
|
52
|
+
type LedgerWriter,
|
|
53
|
+
type OpenIntegrationEntry,
|
|
54
|
+
type PhaseId,
|
|
55
|
+
type PlanId,
|
|
56
|
+
type ResumeReport,
|
|
57
|
+
type RunCommandRef,
|
|
58
|
+
type SlotLease,
|
|
59
|
+
type SlotPool,
|
|
60
|
+
type TaskId,
|
|
61
|
+
type TaskState,
|
|
62
|
+
type TransitionTrigger,
|
|
63
|
+
} from "../types";
|
|
64
|
+
|
|
65
|
+
export const PREEMPT_LIMIT = 3, LOCK_HEARTBEAT_MS = 30_000, LOCK_STALE_MS = 600_000, STALLED_POLL_MS = 5_000;
|
|
66
|
+
/** QA-3.2-33: a repo-lock wait is reported once after this long. */
|
|
67
|
+
export const LOCK_WAIT_REPORT_MS = 300_000;
|
|
68
|
+
/** QA-62C-7: a failed repo-lock heartbeat is retried after at most this long; this many failures in a row are warned once. */
|
|
69
|
+
export const LOCK_HEARTBEAT_RETRY_MS = 1_000, LOCK_HEARTBEAT_WARN_FAILURES = 3;
|
|
70
|
+
/** QA-3.2-30: retries of a tag entry of a completed plan (after its 3 tries), with doubling delays from TAG_RETRY_BASE_MS. */
|
|
71
|
+
export const TAG_RETRY_LIMIT = 3, TAG_RETRY_BASE_MS = 60_000;
|
|
72
|
+
|
|
73
|
+
export interface TaskRange { taskId: TaskId; from: string; to: string }
|
|
74
|
+
|
|
75
|
+
export type SuiteResolution = { kind: "off" } | { kind: "none" } | { kind: "runs"; commands: ResolvedCommand[] }
|
|
76
|
+
| { kind: "refused"; reason: string; ref: RunCommandRef | null };
|
|
77
|
+
export interface SuiteRunRequest {
|
|
78
|
+
planId: PlanId; phaseId: PhaseId; commit: string; base: string | null;
|
|
79
|
+
ranges: readonly TaskRange[]; commands: readonly ResolvedCommand[]; slot: SlotLease;
|
|
80
|
+
}
|
|
81
|
+
export type SuiteVerdict = { kind: "passed" } | { kind: "flaky"; ids: string[] } | { kind: "pre-existing"; ids: string[] }
|
|
82
|
+
| { kind: "culprit"; range: TaskRange; ids: string[]; files: string[] }
|
|
83
|
+
| { kind: "unattributed"; ids: string[]; reason: "outside" | "no-base" | "base-unparsed" | "base-overlap" }
|
|
84
|
+
| { kind: "error"; reason: CheckErrorReason; message: string } | { kind: "interrupted"; by: "abort" | "dispose" };
|
|
85
|
+
export interface RevertRequest {
|
|
86
|
+
planId: PlanId; phaseId: PhaseId; culprit: TaskRange; suiteCommit: string; head: string;
|
|
87
|
+
regression: { ids: string[]; files: string[]; commands: ResolvedCommand[] }; slot: SlotLease;
|
|
88
|
+
}
|
|
89
|
+
export type RevertVerdict = { kind: "ok"; revertHead: string; reverted: string[] } | { kind: "conflict"; at: string; paths: string[] }
|
|
90
|
+
| { kind: "failed"; ids: string[]; files: string[]; output: string } | { kind: "error"; reason: CheckErrorReason; message: string }
|
|
91
|
+
| { kind: "interrupted"; by: "abort" | "dispose" };
|
|
92
|
+
export interface LandRequest { toplevel: string; baseBranch: string; candidate: string; integrationBranch: string }
|
|
93
|
+
export type LandRefusal = { reason: "toplevel-mismatch"; actual: string } | { reason: "not-checked-out"; head: string | null }
|
|
94
|
+
| { reason: "dirty"; paths: string[] } | { reason: "diverged"; baseTip: string } | { reason: "ignored-overwrite"; paths: string[] }
|
|
95
|
+
| { reason: "base-missing" };
|
|
96
|
+
export type LandInspection = { ok: true; baseTip: string; noop: boolean } | { ok: false; refusal: LandRefusal; baseTip: string | null };
|
|
97
|
+
export type LandOutcome = { kind: "landed"; from: string; to: string } | { kind: "refused"; refusal: LandRefusal } | { kind: "error"; message: string };
|
|
98
|
+
export type TagOutcome = CreateRefOutcome | { kind: "error"; message: string };
|
|
99
|
+
|
|
100
|
+
export type IntegrationStepEvent = Extract<ExecutorEvent, { type: "integration-step" }>;
|
|
101
|
+
|
|
102
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
103
|
+
// 5.2 detail schemas (M34) and 5.3 counters (M33)
|
|
104
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
export interface RangeDetail { taskId: TaskId; from: string; to: string }
|
|
107
|
+
export interface CheckDetail {
|
|
108
|
+
v: 1; verdict: "pass" | "fail" | "error";
|
|
109
|
+
components: Array<{ name: string; label: string; exitCode: number | null; timedOut: boolean; durationMs: number;
|
|
110
|
+
scope: "spec" | "no-affected" | "full" | "rerun"; flakyIds: string[] }>;
|
|
111
|
+
failingFiles: string[]; flakyIds: string[]; note: "no-checks" | null;
|
|
112
|
+
error: { reason: string; message: string } | null; output: string;
|
|
113
|
+
}
|
|
114
|
+
export interface RefusedDetail {
|
|
115
|
+
v: 1; reason: string; n?: number; message?: string;
|
|
116
|
+
error?: { code: string; detail: JsonValue };
|
|
117
|
+
}
|
|
118
|
+
export interface StepDetailMap {
|
|
119
|
+
rebase: { v: 1; onto: string; tasks: Array<{ taskId: TaskId; tip: string; upstream: string }> }
|
|
120
|
+
| { v: 1; stacked: RangeDetail[]; deferred: TaskId[] }
|
|
121
|
+
| { v: 1; taskId: TaskId; paths: string[]; truncated: boolean;
|
|
122
|
+
ours: Record<string, Array<{ sha: string; subject: string }>>; theirs: Record<string, Array<{ sha: string; subject: string }>> }
|
|
123
|
+
| RefusedDetail;
|
|
124
|
+
checks: { v: 1; base: string; candidate: string; tasks: TaskId[]; probe?: "memo" } | CheckDetail | RefusedDetail;
|
|
125
|
+
"batch-checks": { v: 1; base: string; candidate: string; tasks: TaskId[]; probe?: "memo" } | CheckDetail | RefusedDetail;
|
|
126
|
+
bisect: { v: 1; base: string; candidate: string; tasks: TaskId[]; probe?: "memo" } | CheckDetail
|
|
127
|
+
| { v: 1; candidate: string; taskId: TaskId; probe: "to" | "from" }
|
|
128
|
+
| { v: 1; verdict: "pass" | "fail"; probes: number; culprit?: RangeDetail; outside?: "from-fails" | "last-passes"; files?: string[] }
|
|
129
|
+
| RefusedDetail;
|
|
130
|
+
"fast-forward": { v: 1; from: string; to: string; ranges: RangeDetail[] } | { v: 1; from: string; to: string } | RefusedDetail;
|
|
131
|
+
"phase-suite": { v: 1; commit: string; base: string | null; commands: Array<{ label: string; ref: RunCommandRef | null }> }
|
|
132
|
+
| { v: 1; files: string[]; idsUnparsed: boolean; durationMs: number; output: string } | RefusedDetail;
|
|
133
|
+
"suite-rerun": { v: 1; n: 1 | 2; files: string[] } | { v: 1; at: "base"; commit: string; files: string[] }
|
|
134
|
+
| { v: 1; reproduced?: string[]; flaky?: string[]; durationMs: number; output: string } | RefusedDetail;
|
|
135
|
+
"revert-build": { v: 1; culprit: RangeDetail; suiteCommit: string; head: string; files: string[] }
|
|
136
|
+
| { v: 1; revertHead: string; reverted: string[] } | { v: 1; at: string; paths: string[]; commands: string[] } | RefusedDetail;
|
|
137
|
+
"revert-checks": { v: 1; base: string; candidate: string; extraFiles: string[] } | CheckDetail | RefusedDetail;
|
|
138
|
+
"revert-fast-forward": { v: 1; from: string; to: string; culprit: RangeDetail; suiteCommit: string }
|
|
139
|
+
| { v: 1; from: string; to: string } | RefusedDetail;
|
|
140
|
+
rollback: { v: 1; of: IntegrationStep | null; reason: "resume" | "abort" | "stalled" } | { v: 1; reset: string | null };
|
|
141
|
+
tag: { v: 1; name: string; commit: string } | { v: 1; outcome: "created" | "exists-same" | "exists-other"; at?: string } | RefusedDetail;
|
|
142
|
+
land: { v: 1; mode: string; toplevel: string; baseBranch: string }
|
|
143
|
+
| { v: 1; from?: string; to?: string; refusal?: LandRefusal } | RefusedDetail;
|
|
144
|
+
}
|
|
145
|
+
export type StepDetail = StepDetailMap[IntegrationStep];
|
|
146
|
+
|
|
147
|
+
export type IntegrationMetricKey =
|
|
148
|
+
| "integration.entry" | "integration.step" | "integration.checks" | "integration.checks.none" | "integration.flaky"
|
|
149
|
+
| "integration.batch" | "integration.bisect.probes" | "integration.suite" | "integration.revert" | "integration.preempt"
|
|
150
|
+
| "integration.slot.wait" | "integration.tag" | "integration.land" | "integration.resume" | "integration.lock.takeover"
|
|
151
|
+
/** A dequeued task that was no longer `verified` when its entry's first batch was built (dropped, no transition). */
|
|
152
|
+
| "integration.dequeue.skipped"
|
|
153
|
+
/** A repo-lock wait that outlasted LOCK_WAIT_REPORT_MS (one inbox item per wait). */
|
|
154
|
+
| "integration.lock.wait";
|
|
155
|
+
|
|
156
|
+
/** M34: JSON detail capped at 16 KiB; an `output` field keeps its last 4 KiB. */
|
|
157
|
+
export function encodeDetail(detail: StepDetail | Record<string, unknown>): string {
|
|
158
|
+
const obj: Record<string, unknown> = { ...(detail as Record<string, unknown>) };
|
|
159
|
+
if (typeof obj.output === "string") obj.output = tailBytes(obj.output, OUTPUT_TAIL_BYTES);
|
|
160
|
+
let text = JSON.stringify(obj);
|
|
161
|
+
if (Buffer.byteLength(text, "utf8") <= DETAIL_MAX_BYTES) return text;
|
|
162
|
+
if (typeof obj.output === "string") obj.output = tailBytes(obj.output, 1024);
|
|
163
|
+
for (const key of ["ours", "theirs", "components", "paths", "ranges", "stacked", "tasks", "files", "extraFiles"]) {
|
|
164
|
+
text = JSON.stringify(obj);
|
|
165
|
+
if (Buffer.byteLength(text, "utf8") <= DETAIL_MAX_BYTES) return text;
|
|
166
|
+
const value = obj[key];
|
|
167
|
+
if (Array.isArray(value)) obj[key] = value.slice(0, 20);
|
|
168
|
+
else if (value !== undefined && typeof value === "object") obj[key] = {};
|
|
169
|
+
obj.truncated = true;
|
|
170
|
+
}
|
|
171
|
+
text = JSON.stringify(obj);
|
|
172
|
+
if (Buffer.byteLength(text, "utf8") <= DETAIL_MAX_BYTES) return text;
|
|
173
|
+
return JSON.stringify({ v: 1, truncated: true, reason: typeof obj.reason === "string" ? obj.reason : undefined });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function tailBytes(s: string, max: number): string {
|
|
177
|
+
const buf = Buffer.from(s, "utf8");
|
|
178
|
+
if (buf.length <= max) return s;
|
|
179
|
+
return buf.subarray(buf.length - max).toString("utf8").replace(/^\uFFFD+/, "");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function clipText(s: string, max: number = AX_MAX_CHARS): string {
|
|
183
|
+
return s.length <= max ? s : s.slice(0, max - 1) + "\u2026";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Keep both Git failure contexts, without letting diagnostics overflow the journal or prevent the infrastructure pause. */
|
|
187
|
+
function refusedError(e: unknown): RefusedDetail {
|
|
188
|
+
const out: RefusedDetail = { v: 1, reason: "error", message: clipText(stripUrlUserinfo(message(e)), 1000) };
|
|
189
|
+
if (e instanceof ExecutorError) {
|
|
190
|
+
let detail: JsonValue;
|
|
191
|
+
try {
|
|
192
|
+
// Redact before clipping each string: a byte boundary must not expose a credential suffix.
|
|
193
|
+
const sanitizeString = (value: string): string => {
|
|
194
|
+
const clean = stripUrlUserinfo(value);
|
|
195
|
+
let limit = 2048;
|
|
196
|
+
let bounded = tailBytes(clean, limit);
|
|
197
|
+
// Bound encoded bytes too, so escaping stderr cannot crowd out either failure context.
|
|
198
|
+
while (Buffer.byteLength(JSON.stringify(bounded), "utf8") > 2048) {
|
|
199
|
+
limit = Math.floor(limit / 2);
|
|
200
|
+
bounded = tailBytes(clean, limit);
|
|
201
|
+
}
|
|
202
|
+
return bounded;
|
|
203
|
+
};
|
|
204
|
+
const copies = new WeakMap<object, Record<string, unknown>>();
|
|
205
|
+
let remaining = 256; // Bound traversal too, including arrays and objects returned by toJSON.
|
|
206
|
+
const text = JSON.stringify(e.detail, (_key, value: unknown) => {
|
|
207
|
+
if (--remaining < 0) throw new Error("Diagnostic traversal limit");
|
|
208
|
+
if (typeof value === "string") return sanitizeString(value);
|
|
209
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
|
|
210
|
+
// Reuse copies so JSON.stringify still detects cycles, but permits shared diagnostic objects.
|
|
211
|
+
const previous = copies.get(value);
|
|
212
|
+
if (previous) return previous;
|
|
213
|
+
const copy: Record<string, unknown> = Object.create(null);
|
|
214
|
+
copies.set(value, copy);
|
|
215
|
+
for (const key in value) {
|
|
216
|
+
if (--remaining < 0) throw new Error("Diagnostic traversal limit");
|
|
217
|
+
if (!Object.hasOwn(value, key)) continue;
|
|
218
|
+
const base = sanitizeString(key);
|
|
219
|
+
let cleanKey = base;
|
|
220
|
+
// Renaming must not overwrite another diagnostic; a null prototype keeps __proto__ inert.
|
|
221
|
+
for (let n = 2; Object.hasOwn(copy, cleanKey); n++) cleanKey = `${base}#${n}`;
|
|
222
|
+
copy[cleanKey] = (value as Record<string, unknown>)[key];
|
|
223
|
+
}
|
|
224
|
+
return copy;
|
|
225
|
+
});
|
|
226
|
+
detail = Buffer.byteLength(text, "utf8") <= 8192 ? JSON.parse(text) as JsonValue
|
|
227
|
+
: { truncated: true, tail: tailBytes(text, 4096) };
|
|
228
|
+
} catch {
|
|
229
|
+
detail = { unavailable: true };
|
|
230
|
+
}
|
|
231
|
+
out.error = { code: e.code, detail };
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function parseDetail(text: string | null | undefined): Record<string, unknown> | null {
|
|
237
|
+
if (typeof text !== "string" || text === "") return null;
|
|
238
|
+
try {
|
|
239
|
+
const parsed: unknown = JSON.parse(text);
|
|
240
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
|
|
241
|
+
} catch {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
247
|
+
// 5.1 seams
|
|
248
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
export interface StepJournal {
|
|
251
|
+
readonly entry: Readonly<IntegrationEntry>;
|
|
252
|
+
readonly signal: AbortSignal;
|
|
253
|
+
/** ISS for the open entry; rejects if a step is open. Resolves after the fsync. */
|
|
254
|
+
start(step: IntegrationStep, detail: StepDetail,
|
|
255
|
+
patch?: Partial<Pick<IntegrationEntry, "candidate" | "slot" | "taskIds">>): Promise<void>;
|
|
256
|
+
/** Never closes; closing ends belong to the queue (M1, A2-1). Runners leave their final step open. */
|
|
257
|
+
end(result: Exclude<IntegrationStepResult, "rolled-back">, detail: StepDetail, failingIds?: readonly string[]): Promise<void>;
|
|
258
|
+
assertWriteCwd(cwd: string, purpose: WritePurpose): Promise<void>;
|
|
259
|
+
/** Buffered; appended inside the next batch. */
|
|
260
|
+
counter(key: IntegrationMetricKey, value: number, labels: Record<string, string>): void;
|
|
261
|
+
}
|
|
262
|
+
export interface PhaseSuiteRunner {
|
|
263
|
+
resolve(ledger: Readonly<LedgerV1>, phaseId: PhaseId, commit: string): Promise<SuiteResolution>;
|
|
264
|
+
run(req: SuiteRunRequest, j: StepJournal): Promise<SuiteVerdict>;
|
|
265
|
+
revert(req: RevertRequest, j: StepJournal): Promise<RevertVerdict>;
|
|
266
|
+
/** Aborts the in-flight background run if it still has preemption budget; true if aborted. */
|
|
267
|
+
preemptBackground(): boolean;
|
|
268
|
+
}
|
|
269
|
+
export interface Lander {
|
|
270
|
+
tagName(planId: PlanId, phaseId: PhaseId): string;
|
|
271
|
+
tag(req: { cwd: string; name: string; commit: string }): Promise<TagOutcome>;
|
|
272
|
+
inspect(req: LandRequest): Promise<LandInspection>;
|
|
273
|
+
fastForward(req: LandRequest): Promise<LandOutcome>;
|
|
274
|
+
commands(req: LandRequest, refusal: LandRefusal): string[];
|
|
275
|
+
}
|
|
276
|
+
/** V2: wired by 5.1 from the 2.2 store's history read; the queue caches it and appends its own writes. */
|
|
277
|
+
export interface IntegrationHistory {
|
|
278
|
+
steps(): Promise<readonly IntegrationStepEvent[]>;
|
|
279
|
+
}
|
|
280
|
+
export interface RepoLock {
|
|
281
|
+
readonly lost: AbortSignal;
|
|
282
|
+
release(): Promise<void>;
|
|
283
|
+
/** Re-reads the lock file: true while it is still ours (QA-3.2-28, checked right before the CAS). Optional for doubles. */
|
|
284
|
+
verify?(): Promise<boolean>;
|
|
285
|
+
}
|
|
286
|
+
/** What a long repo-lock wait is waiting for (QA-3.2-33). */
|
|
287
|
+
export interface LockWaitInfo {
|
|
288
|
+
file: string; pid: number | null; hostname: string | null; planId: string | null; heartbeatAgeMs: number | null; waitedMs: number;
|
|
289
|
+
}
|
|
290
|
+
export interface RepoLockFactory {
|
|
291
|
+
/** `onWait` is called at most once per wait, after it outlasted the factory's report delay. */
|
|
292
|
+
acquire(repoKey: string, holder: { planId: PlanId; entryId: string | null }, signal: AbortSignal,
|
|
293
|
+
onWait?: (info: LockWaitInfo) => void): Promise<RepoLock>;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
297
|
+
// Event constructors (A1-2.4 Q rows)
|
|
298
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
299
|
+
|
|
300
|
+
type StepInput = Extract<ExecutorEventInput, { type: "integration-step" }>;
|
|
301
|
+
|
|
302
|
+
function iss(entry: IntegrationEntry, step: IntegrationStep, detail: StepDetail | Record<string, unknown>,
|
|
303
|
+
failingIds: readonly string[] = []): StepInput {
|
|
304
|
+
return { type: "integration-step", edge: "start", entry: { ...entry, taskIds: [...entry.taskIds] }, step, result: null,
|
|
305
|
+
detail: encodeDetail(detail), failingIds: [...failingIds], closes: false };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function ise(entry: IntegrationEntry, step: IntegrationStep, result: IntegrationStepResult,
|
|
309
|
+
detail: StepDetail | Record<string, unknown>, closes: boolean, failingIds: readonly string[] = []): StepInput {
|
|
310
|
+
return { type: "integration-step", edge: "end", entry: { ...entry, taskIds: [...entry.taskIds] }, step, result,
|
|
311
|
+
detail: encodeDetail(detail), failingIds: [...failingIds], closes };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function counterEvent(key: IntegrationMetricKey, value: number, labels: Record<string, string>): ExecutorEventInput {
|
|
315
|
+
return { type: "metric", metric: { name: "counter", key, value, labels: { ...labels } } };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
319
|
+
// Queue dependencies (memo §6)
|
|
320
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
export interface IntegrationQueueDeps {
|
|
323
|
+
planId: PlanId; writer: LedgerWriter; history: IntegrationHistory; git: GitOps; igit: IntegrateGit;
|
|
324
|
+
pool: SlotPool; leases: LeaseService; checks: IntegrationChecks; suite: PhaseSuiteRunner; lander: Lander; listener: IntegrationListener;
|
|
325
|
+
settle: (taskId: TaskId, release: () => Promise<void>) => void; locks: RepoLockFactory; guard: WriteGuard; clock: Clock; logger: Logger;
|
|
326
|
+
/**
|
|
327
|
+
* M1: gives back the slot of a task row 34 blocked. The runtime saves the slot's unsaved work first
|
|
328
|
+
* (`releaseSlotSaved`), and a failed save keeps the slot leased. It never releases a slot whose cancelled child
|
|
329
|
+
* `sweepBlocked` is still releasing. N-1: it takes the task's mutex, so the serial lane never awaits it.
|
|
330
|
+
*/
|
|
331
|
+
releaseSlot: (taskId: TaskId, slot: string) => Promise<void>;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The serial-lane entry in flight (at most one, M4) or the background suite entry. */
|
|
335
|
+
interface LiveEntry {
|
|
336
|
+
entry: IntegrationEntry;
|
|
337
|
+
startSeq: number;
|
|
338
|
+
/** The step whose start is journaled and whose end is not, or null. */
|
|
339
|
+
open: IntegrationStep | null;
|
|
340
|
+
openedAt: number;
|
|
341
|
+
lane: "serial" | "background";
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Thrown inside a flow to stop the lane after the queue already journaled the halt (M13b) or lost the lock (M7). */
|
|
345
|
+
class LaneStop extends Error {
|
|
346
|
+
override readonly name = "LaneStop" as const;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** A git read that could not run (infrastructure), as opposed to a ref that does not exist (QA-3.2-9). */
|
|
350
|
+
class GitReadError extends Error {
|
|
351
|
+
override readonly name = "GitReadError" as const;
|
|
352
|
+
constructor(readonly ref: string, cause: unknown) {
|
|
353
|
+
super(`git could not read ${ref}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function errCode(e: unknown): string | null {
|
|
358
|
+
return e instanceof ExecutorError ? e.code : null;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function message(e: unknown): string {
|
|
362
|
+
return e instanceof Error ? e.message : String(e);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function rangesOf(stacked: readonly RangeDetail[]): RangeDetail[] {
|
|
366
|
+
return stacked.map(r => ({ taskId: r.taskId, from: r.from, to: r.to }));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function checkDetail(r: CheckResult): CheckDetail {
|
|
370
|
+
return {
|
|
371
|
+
v: 1, verdict: r.verdict,
|
|
372
|
+
components: r.components.map(c => ({ name: c.name, label: c.label, exitCode: c.exitCode, timedOut: c.timedOut,
|
|
373
|
+
durationMs: c.durationMs, scope: c.scope, flakyIds: [...c.flakyIds] })),
|
|
374
|
+
failingFiles: r.verdict === "fail" ? [...r.failingFiles] : [],
|
|
375
|
+
flakyIds: r.verdict === "error" ? [] : [...r.flakyIds],
|
|
376
|
+
note: r.verdict === "pass" ? r.note : null,
|
|
377
|
+
error: r.verdict === "error" ? { reason: r.reason, message: r.message } : null,
|
|
378
|
+
output: r.verdict === "fail" ? r.output : "",
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
383
|
+
// M5: repo lock (I3) = in-process mutex per repo.key + cross-process lock file
|
|
384
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
385
|
+
|
|
386
|
+
/** In-process tails per repo key, shared by every queue (and every factory) in the process. */
|
|
387
|
+
const REPO_MUTEX = new Map<string, Promise<void>>();
|
|
388
|
+
|
|
389
|
+
interface LockFileContent { pid: number; hostname: string; planId: string; entryId: string | null; heartbeatAt: number; token: string | null }
|
|
390
|
+
|
|
391
|
+
function parseLockFile(text: string): LockFileContent | null {
|
|
392
|
+
try {
|
|
393
|
+
const v: unknown = JSON.parse(text);
|
|
394
|
+
if (v === null || typeof v !== "object") return null;
|
|
395
|
+
const o = v as Record<string, unknown>;
|
|
396
|
+
if (typeof o.pid !== "number" || typeof o.hostname !== "string" || typeof o.heartbeatAt !== "number") return null;
|
|
397
|
+
return { pid: o.pid, hostname: o.hostname, planId: typeof o.planId === "string" ? o.planId : "",
|
|
398
|
+
entryId: typeof o.entryId === "string" ? o.entryId : null, heartbeatAt: o.heartbeatAt,
|
|
399
|
+
token: typeof o.token === "string" ? o.token : null };
|
|
400
|
+
} catch {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function fsCode(e: unknown): unknown {
|
|
406
|
+
return e !== null && typeof e === "object" ? (e as { code?: unknown }).code : undefined;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** A repo lock; `takeover` says whether acquiring it took over a dead or stale holder (counter `integration.lock.takeover`). */
|
|
410
|
+
export interface RepoLockWithTakeover extends RepoLock { readonly takeover: "dead-pid" | "stale" | null }
|
|
411
|
+
|
|
412
|
+
export function createRepoLockFactory(o: {
|
|
413
|
+
stateRoot: string; clock: Clock; pid: number; hostname: string;
|
|
414
|
+
isPidAlive: (pid: number) => boolean; heartbeatMs?: number; staleMs?: number; waitReportMs?: number;
|
|
415
|
+
/** QA-62C-7: told once when the heartbeat failed LOCK_HEARTBEAT_WARN_FAILURES times in a row. */
|
|
416
|
+
logger?: Pick<Logger, "warn">;
|
|
417
|
+
}): RepoLockFactory {
|
|
418
|
+
const heartbeatMs = o.heartbeatMs ?? LOCK_HEARTBEAT_MS;
|
|
419
|
+
const heartbeatRetryMs = Math.min(heartbeatMs, LOCK_HEARTBEAT_RETRY_MS);
|
|
420
|
+
const staleMs = o.staleMs ?? LOCK_STALE_MS;
|
|
421
|
+
const waitReportMs = o.waitReportMs ?? LOCK_WAIT_REPORT_MS;
|
|
422
|
+
|
|
423
|
+
function lockPath(repoKey: string): string {
|
|
424
|
+
const digest = createHash("sha256").update(repoKey, "utf8").digest("hex");
|
|
425
|
+
return nodePath.join(o.stateRoot, "repos", digest, "integration.lock");
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function takeMutex(repoKey: string, signal: AbortSignal): Promise<() => void> {
|
|
429
|
+
for (;;) {
|
|
430
|
+
if (signal.aborted) throw new ExecutorError("E_DISPOSED", "repo lock wait aborted", { repoKey: repoKey.slice(0, 200) });
|
|
431
|
+
const tail = REPO_MUTEX.get(repoKey);
|
|
432
|
+
if (tail === undefined) {
|
|
433
|
+
let free!: () => void;
|
|
434
|
+
const mine = new Promise<void>(resolve => { free = resolve; });
|
|
435
|
+
REPO_MUTEX.set(repoKey, mine);
|
|
436
|
+
return () => {
|
|
437
|
+
if (REPO_MUTEX.get(repoKey) === mine) REPO_MUTEX.delete(repoKey);
|
|
438
|
+
free();
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
await Promise.race([tail, new Promise<void>(resolve => signal.addEventListener("abort", () => resolve(), { once: true }))]);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
446
|
+
await new Promise<void>(resolve => {
|
|
447
|
+
// An abort that fired during the caller's file-system awaits must not leave this wait to the clock alone.
|
|
448
|
+
if (signal.aborted) {
|
|
449
|
+
resolve();
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const onAbort = (): void => { o.clock.clearTimer(h); resolve(); };
|
|
453
|
+
const h = o.clock.setTimer(ms, () => { signal.removeEventListener("abort", onAbort); resolve(); });
|
|
454
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
let tmpSeq = 0;
|
|
459
|
+
function sideName(file: string, tag: string): string {
|
|
460
|
+
tmpSeq++;
|
|
461
|
+
return `${file}.${o.pid}.${tmpSeq}.${randomBytes(4).toString("hex")}.${tag}`;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Writes `content` to a fresh side file in full (fsync'd), so no reader ever sees a partial lock file (QA-3.2-4). */
|
|
465
|
+
async function writeSide(file: string, content: LockFileContent): Promise<string> {
|
|
466
|
+
const tmp = sideName(file, "tmp");
|
|
467
|
+
const fh = await open(tmp, "wx");
|
|
468
|
+
try {
|
|
469
|
+
await fh.writeFile(JSON.stringify(content), "utf8");
|
|
470
|
+
await fh.sync();
|
|
471
|
+
} finally {
|
|
472
|
+
await fh.close();
|
|
473
|
+
}
|
|
474
|
+
return tmp;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Creates the lock atomically and complete: a hard link of a fully written side file, which never overwrites (EEXIST). */
|
|
478
|
+
async function create(file: string, content: LockFileContent): Promise<boolean> {
|
|
479
|
+
const tmp = await writeSide(file, content);
|
|
480
|
+
try {
|
|
481
|
+
await link(tmp, file);
|
|
482
|
+
return true;
|
|
483
|
+
} catch (e) {
|
|
484
|
+
if (fsCode(e) === "EEXIST") return false;
|
|
485
|
+
throw e;
|
|
486
|
+
} finally {
|
|
487
|
+
await unlink(tmp).catch(() => undefined);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async function readRaw(file: string): Promise<string | null> {
|
|
492
|
+
try {
|
|
493
|
+
return await readFile(file, "utf8");
|
|
494
|
+
} catch (e) {
|
|
495
|
+
if (fsCode(e) === "ENOENT") return null;
|
|
496
|
+
throw e;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Compare-and-delete: removes the lock file only if it still holds `raw`. The file is renamed aside first (atomic, one
|
|
502
|
+
* taker wins); a file that is not the one judged (another taker already replaced it) is linked back. True if removed.
|
|
503
|
+
*/
|
|
504
|
+
async function removeIfSame(file: string, raw: string): Promise<boolean> {
|
|
505
|
+
const tomb = sideName(file, "stale");
|
|
506
|
+
try {
|
|
507
|
+
await rename(file, tomb);
|
|
508
|
+
} catch (e) {
|
|
509
|
+
if (fsCode(e) === "ENOENT") return false;
|
|
510
|
+
throw e;
|
|
511
|
+
}
|
|
512
|
+
let moved: string;
|
|
513
|
+
try {
|
|
514
|
+
moved = await readFile(tomb, "utf8");
|
|
515
|
+
} catch (e) {
|
|
516
|
+
// Not judgeable (not a file): put it back where it was and fail.
|
|
517
|
+
await rename(tomb, file).catch(() => undefined);
|
|
518
|
+
throw e;
|
|
519
|
+
}
|
|
520
|
+
if (moved !== raw) await link(tomb, file).catch(() => undefined);
|
|
521
|
+
await unlink(tomb).catch(() => undefined);
|
|
522
|
+
return moved === raw;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Why the holder recorded in `raw` may be taken over, or null for a live holder. Same host: pid liveness only (R4);
|
|
527
|
+
* our own pid while this process holds the repo mutex is a leftover. Other hosts: the heartbeat age. Unparsable counts
|
|
528
|
+
* as stale; the caller takes over only when the same verdict holds for the same bytes at two polls.
|
|
529
|
+
*/
|
|
530
|
+
function judge(raw: string): "dead-pid" | "stale" | null {
|
|
531
|
+
const current = parseLockFile(raw);
|
|
532
|
+
if (current === null) return "stale";
|
|
533
|
+
if (current.hostname === o.hostname) return current.pid === o.pid || !o.isPidAlive(current.pid) ? "dead-pid" : null;
|
|
534
|
+
return o.clock.now() - current.heartbeatAt > staleMs ? "stale" : null;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Nit (QA-3.2 round 2): removes side files a crashed writer left next to the lock (`<lock>.<pid>.<n>.<hex>.tmp|stale`).
|
|
539
|
+
* Only ours (this process holds the repo mutex, so none of ours is in flight) or a dead same-host pid's are removed.
|
|
540
|
+
*/
|
|
541
|
+
async function cleanSides(file: string): Promise<void> {
|
|
542
|
+
const dir = nodePath.dirname(file);
|
|
543
|
+
const base = nodePath.basename(file) + ".";
|
|
544
|
+
let names: string[];
|
|
545
|
+
try {
|
|
546
|
+
names = await readdir(dir);
|
|
547
|
+
} catch {
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
for (const name of names) {
|
|
551
|
+
if (!name.startsWith(base) || !(name.endsWith(".tmp") || name.endsWith(".stale"))) continue;
|
|
552
|
+
const pid = Number(name.slice(base.length).split(".")[0]);
|
|
553
|
+
if (!Number.isInteger(pid)) continue;
|
|
554
|
+
if (pid !== o.pid && o.isPidAlive(pid)) continue;
|
|
555
|
+
await unlink(nodePath.join(dir, name)).catch(() => undefined);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
return {
|
|
560
|
+
async acquire(repoKey, holder, signal, onWait) {
|
|
561
|
+
const freeMutex = await takeMutex(repoKey, signal);
|
|
562
|
+
const file = lockPath(repoKey);
|
|
563
|
+
const token = randomBytes(8).toString("hex");
|
|
564
|
+
let takeover: "dead-pid" | "stale" | null = null;
|
|
565
|
+
const startedAt = o.clock.now();
|
|
566
|
+
let reported = false;
|
|
567
|
+
try {
|
|
568
|
+
await mkdir(nodePath.dirname(file), { recursive: true });
|
|
569
|
+
await cleanSides(file);
|
|
570
|
+
let suspect: { raw: string; reason: "dead-pid" | "stale" } | null = null;
|
|
571
|
+
/** Set by a successful compare-and-delete; counted only if our very next create wins (nit: takeover counter). */
|
|
572
|
+
let removed: "dead-pid" | "stale" | null = null;
|
|
573
|
+
for (;;) {
|
|
574
|
+
if (signal.aborted) throw new ExecutorError("E_DISPOSED", "repo lock wait aborted", { repoKey: repoKey.slice(0, 200) });
|
|
575
|
+
const content: LockFileContent = { pid: o.pid, hostname: o.hostname, planId: holder.planId, entryId: holder.entryId,
|
|
576
|
+
heartbeatAt: o.clock.now(), token };
|
|
577
|
+
if (await create(file, content)) {
|
|
578
|
+
takeover = removed;
|
|
579
|
+
break;
|
|
580
|
+
}
|
|
581
|
+
removed = null;
|
|
582
|
+
const raw = await readRaw(file);
|
|
583
|
+
if (raw === null) {
|
|
584
|
+
suspect = null;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
const reason = judge(raw);
|
|
588
|
+
if (reason !== null && suspect !== null && suspect.raw === raw && suspect.reason === reason) {
|
|
589
|
+
suspect = null;
|
|
590
|
+
if (await removeIfSame(file, raw)) removed = reason;
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
suspect = reason === null ? null : { raw, reason };
|
|
594
|
+
// QA-3.2-33: one report per wait once it outlasted waitReportMs (the holder, its heartbeat age, the file).
|
|
595
|
+
if (!reported && onWait !== undefined && o.clock.now() - startedAt >= waitReportMs) {
|
|
596
|
+
reported = true;
|
|
597
|
+
const cur = parseLockFile(raw);
|
|
598
|
+
try {
|
|
599
|
+
onWait({ file, pid: cur?.pid ?? null, hostname: cur?.hostname ?? null, planId: cur?.planId ?? null,
|
|
600
|
+
heartbeatAgeMs: cur === null ? null : o.clock.now() - cur.heartbeatAt, waitedMs: o.clock.now() - startedAt });
|
|
601
|
+
} catch {
|
|
602
|
+
// A reporting failure never breaks the wait.
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
await sleep(Math.min(heartbeatMs, 1000), signal);
|
|
606
|
+
}
|
|
607
|
+
} catch (e) {
|
|
608
|
+
freeMutex();
|
|
609
|
+
throw e;
|
|
610
|
+
}
|
|
611
|
+
const lost = new AbortController();
|
|
612
|
+
let released = false;
|
|
613
|
+
/** QA-3.2-27: the beat in flight; release() waits for it before its compare-and-delete. */
|
|
614
|
+
let beating: Promise<void> | null = null;
|
|
615
|
+
const ours = (raw: string | null): boolean => {
|
|
616
|
+
const current = raw === null ? null : parseLockFile(raw);
|
|
617
|
+
return current !== null && current.pid === o.pid && current.hostname === o.hostname && current.token === token;
|
|
618
|
+
};
|
|
619
|
+
/** QA-62C-7: transient beat failures in a row; a success resets it. */
|
|
620
|
+
let failures = 0;
|
|
621
|
+
const beatOnce = async (): Promise<void> => {
|
|
622
|
+
if (released || lost.signal.aborted) return;
|
|
623
|
+
let failed: unknown = null;
|
|
624
|
+
let ok = false;
|
|
625
|
+
try {
|
|
626
|
+
const raw = await readRaw(file);
|
|
627
|
+
if (released) return;
|
|
628
|
+
const current = raw === null ? null : parseLockFile(raw);
|
|
629
|
+
if (current === null || !ours(raw)) {
|
|
630
|
+
lost.abort();
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
// A full side file renamed over the lock: the lock file is never empty or partial (QA-3.2-4).
|
|
634
|
+
const tmp = await writeSide(file, { ...current, heartbeatAt: o.clock.now() });
|
|
635
|
+
if (released) {
|
|
636
|
+
await unlink(tmp).catch(() => undefined);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
await rename(tmp, file);
|
|
641
|
+
} catch (e) {
|
|
642
|
+
await unlink(tmp).catch(() => undefined);
|
|
643
|
+
throw e;
|
|
644
|
+
}
|
|
645
|
+
ok = true;
|
|
646
|
+
} catch (e) {
|
|
647
|
+
// A transient read or rename failure is retried soon (QA-62C-7); only a missing or foreign lock file is a loss.
|
|
648
|
+
failed = e;
|
|
649
|
+
}
|
|
650
|
+
if (released || lost.signal.aborted) return;
|
|
651
|
+
if (ok) {
|
|
652
|
+
failures = 0;
|
|
653
|
+
} else {
|
|
654
|
+
failures++;
|
|
655
|
+
if (failures === LOCK_HEARTBEAT_WARN_FAILURES) {
|
|
656
|
+
try {
|
|
657
|
+
o.logger?.warn(`integration queue: repo lock heartbeat failed ${failures} times in a row (${file}); retrying every ${heartbeatRetryMs} ms: ${message(failed)}`);
|
|
658
|
+
} catch {
|
|
659
|
+
// A reporting failure never stops the heartbeat.
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
// A failed beat re-arms at the short retry delay; a successful one at the normal period.
|
|
664
|
+
timer = o.clock.setTimer(ok ? heartbeatMs : heartbeatRetryMs, beat);
|
|
665
|
+
};
|
|
666
|
+
const beat = (): void => {
|
|
667
|
+
const p = beatOnce();
|
|
668
|
+
beating = p;
|
|
669
|
+
void p.finally(() => { if (beating === p) beating = null; });
|
|
670
|
+
};
|
|
671
|
+
let timer = o.clock.setTimer(heartbeatMs, beat);
|
|
672
|
+
const lock: RepoLockWithTakeover = {
|
|
673
|
+
lost: lost.signal,
|
|
674
|
+
takeover,
|
|
675
|
+
async verify() {
|
|
676
|
+
if (released || lost.signal.aborted) return false;
|
|
677
|
+
try {
|
|
678
|
+
if (ours(await readRaw(file))) return true;
|
|
679
|
+
} catch {
|
|
680
|
+
return true; // unreadable now: not proof of a loss; the heartbeat decides
|
|
681
|
+
}
|
|
682
|
+
lost.abort();
|
|
683
|
+
return false;
|
|
684
|
+
},
|
|
685
|
+
async release() {
|
|
686
|
+
if (released) return;
|
|
687
|
+
released = true;
|
|
688
|
+
o.clock.clearTimer(timer);
|
|
689
|
+
try {
|
|
690
|
+
if (beating !== null) await beating;
|
|
691
|
+
const raw = await readRaw(file);
|
|
692
|
+
if (raw !== null && ours(raw)) await removeIfSame(file, raw);
|
|
693
|
+
} catch {
|
|
694
|
+
// Already gone or replaced by a takeover: nothing of ours to remove.
|
|
695
|
+
} finally {
|
|
696
|
+
freeMutex();
|
|
697
|
+
}
|
|
698
|
+
},
|
|
699
|
+
};
|
|
700
|
+
return lock;
|
|
701
|
+
},
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
706
|
+
// The queue
|
|
707
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
708
|
+
|
|
709
|
+
type CheckStep = "checks" | "batch-checks" | "bisect" | "revert-checks";
|
|
710
|
+
type Pre = (l: Readonly<LedgerV1>) => ExecutorEventInput[];
|
|
711
|
+
const NONE: Pre = () => [];
|
|
712
|
+
|
|
713
|
+
interface PendingRevert { phaseId: PhaseId; culprit: TaskRange; suiteCommit: string; ids: string[]; files: string[]; commands: ResolvedCommand[]; rerun: LiveEntry | null }
|
|
714
|
+
interface StackResult { stacked: RangeDetail[]; deferred: TaskId[] }
|
|
715
|
+
|
|
716
|
+
export function createIntegrationQueue(d: IntegrationQueueDeps): IntegrationQueue {
|
|
717
|
+
return new Queue(d);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
class Queue implements IntegrationQueue {
|
|
721
|
+
private readonly d: IntegrationQueueDeps;
|
|
722
|
+
private readonly fifo: TaskId[] = [];
|
|
723
|
+
/** Resume reruns (M4 pick #1): requeued task entries' task ids, oldest `startSeq` first. */
|
|
724
|
+
private readonly requeued: Array<{ taskIds: TaskId[]; phaseId: PhaseId | null; startSeq: number }> = [];
|
|
725
|
+
private readonly reverts: PendingRevert[] = [];
|
|
726
|
+
private readonly tags: PhaseId[] = [];
|
|
727
|
+
/** Background lane FIFO by phase (M4): `start` from pending, `rerun` from suite-failed, `none` = ISS only (A2-1). */
|
|
728
|
+
private readonly suites: Array<{ phaseId: PhaseId; gate: "start" | "rerun" | "none" }> = [];
|
|
729
|
+
private steps: IntegrationStepEvent[] | null = null;
|
|
730
|
+
private counters: ExecutorEventInput[] = [];
|
|
731
|
+
private serial: LiveEntry | null = null;
|
|
732
|
+
private background: LiveEntry | null = null;
|
|
733
|
+
/** M36 stalled entries, at most one per lane (QA-3.2-5). */
|
|
734
|
+
private readonly stalled = new Map<LiveEntry["lane"], LiveEntry>();
|
|
735
|
+
/** Queued work that waits behind an infrastructure pause with no entry open (QA-3.2-9): the poll kicks it. */
|
|
736
|
+
private pausedWork = false;
|
|
737
|
+
/** QA-3.2-28: latched at the first lost-lock halt; every later git write stops until a lock is taken again. */
|
|
738
|
+
private lockLost = false;
|
|
739
|
+
/** QA-3.2-30: retries so far of a completed plan's tag entry, per phase. */
|
|
740
|
+
private readonly tagRetries = new Map<PhaseId, number>();
|
|
741
|
+
private stalledTimer: { readonly id: number } | null = null;
|
|
742
|
+
private lock: RepoLock | null = null;
|
|
743
|
+
private integrationLease: SlotLease | null = null;
|
|
744
|
+
/** I1: commits whose checks passed in a slot during the current serial entry. */
|
|
745
|
+
private passed = new Set<string>();
|
|
746
|
+
/** M18: verdicts by candidate sha within the current serial entry. */
|
|
747
|
+
private verdicts = new Map<string, "pass" | "fail">();
|
|
748
|
+
/** One-use proof of the checkout produced by the latest successful stack rebase. */
|
|
749
|
+
private stackedCheckout: { slot: string; head: string } | null = null;
|
|
750
|
+
private resumed = false;
|
|
751
|
+
private resuming: Promise<ResumeReport> | null = null;
|
|
752
|
+
private serialRunning = false;
|
|
753
|
+
private backgroundRunning = false;
|
|
754
|
+
private stopped = false;
|
|
755
|
+
private disposed = false;
|
|
756
|
+
private aborting = false;
|
|
757
|
+
private readonly ctl = new AbortController();
|
|
758
|
+
private readonly bgCtl = new AbortController();
|
|
759
|
+
/** Aborted only by dispose(): ends a wait for the repo lock. */
|
|
760
|
+
private readonly lockCtl = new AbortController();
|
|
761
|
+
|
|
762
|
+
constructor(d: IntegrationQueueDeps) {
|
|
763
|
+
this.d = d;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
private get ledger(): Readonly<LedgerV1> {
|
|
767
|
+
return this.d.writer.ledger;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
771
|
+
// Journal core (M1, M7, I4)
|
|
772
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
773
|
+
|
|
774
|
+
/** The first history load is cached as a promise, so concurrent first callers share one read (and one array). */
|
|
775
|
+
private async loadSteps(): Promise<IntegrationStepEvent[]> {
|
|
776
|
+
if (this.stepsP === null) {
|
|
777
|
+
this.stepsP = this.d.history.steps().then(s => {
|
|
778
|
+
this.steps = [...s];
|
|
779
|
+
return this.steps;
|
|
780
|
+
});
|
|
781
|
+
this.stepsP.catch(() => { this.stepsP = null; });
|
|
782
|
+
}
|
|
783
|
+
return this.stepsP;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
private stepsP: Promise<IntegrationStepEvent[]> | null = null;
|
|
787
|
+
|
|
788
|
+
private assertLive(): void {
|
|
789
|
+
if (this.disposed) throw new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId });
|
|
790
|
+
if (this.stopped) throw new LaneStop("integration lanes stopped after a rejected append");
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** Appends one batch; the buffered counters ride along. A rejected append stops both lanes (M7). */
|
|
794
|
+
private async append(build: Pre): Promise<Readonly<LedgerV1>> {
|
|
795
|
+
this.assertLive();
|
|
796
|
+
await this.loadSteps();
|
|
797
|
+
const counters = this.counters.splice(0);
|
|
798
|
+
let built: ExecutorEventInput[] = [];
|
|
799
|
+
let base = 0;
|
|
800
|
+
try {
|
|
801
|
+
const next = await this.d.writer.append(l => {
|
|
802
|
+
base = l.seq;
|
|
803
|
+
built = [...build(l), ...counters];
|
|
804
|
+
return built;
|
|
805
|
+
});
|
|
806
|
+
this.record(built, base);
|
|
807
|
+
return next;
|
|
808
|
+
} catch (e) {
|
|
809
|
+
await this.onAppendError(e);
|
|
810
|
+
throw e;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
private record(built: readonly ExecutorEventInput[], base: number): void {
|
|
815
|
+
const steps = this.steps;
|
|
816
|
+
if (steps === null || built.length === 0) return;
|
|
817
|
+
const at = this.d.clock.iso();
|
|
818
|
+
built.forEach((ev, i) => {
|
|
819
|
+
if (ev.type !== "integration-step") return;
|
|
820
|
+
steps.push({ ...ev, seq: base + 1 + i, at, batch: base + 1, last: i === built.length - 1 });
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
private async onAppendError(e: unknown): Promise<void> {
|
|
825
|
+
this.stopped = true;
|
|
826
|
+
const code = errCode(e);
|
|
827
|
+
// A lost ledger lock disposes the queue (the runners report `dispose`); any other rejection only stops the lanes.
|
|
828
|
+
this.bgCtl.abort(code === "E_LOCK_LOST" ? "dispose" : "stopped");
|
|
829
|
+
if (code === "E_LOCK_LOST") {
|
|
830
|
+
// Outcome unknown (2.2 handoff): no further git or listener call; the next writer's resume() reconciles.
|
|
831
|
+
this.disposed = true;
|
|
832
|
+
this.ctl.abort("dispose");
|
|
833
|
+
// dispose() returns early once `disposed` is set, so the repo lock (and its heartbeat) would otherwise never be released.
|
|
834
|
+
await this.releaseLock();
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
if (code === "E_ILLEGAL_TRANSITION") {
|
|
838
|
+
this.d.logger.warn(`integration queue: illegal transition rejected by the ledger writer: ${message(e)}`);
|
|
839
|
+
try {
|
|
840
|
+
const now = this.d.clock.iso();
|
|
841
|
+
await this.d.writer.append(l => [
|
|
842
|
+
...this.pauseEvents(l, "integration-bug"),
|
|
843
|
+
this.inboxEvent(l, "failure", "critical", null,
|
|
844
|
+
`Integration queue bug: a journal batch was rejected (${clipText(message(e), 500)}). The plan is paused and this queue has stopped: restart the executor (the new queue's resume() reconciles), then unpause.`, now),
|
|
845
|
+
]);
|
|
846
|
+
} catch (inner) {
|
|
847
|
+
this.d.logger.warn(`integration queue: could not pause after an illegal transition: ${message(inner)}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
// QA-3.2-34: a stopped queue makes no further git write: it must not keep the repo lock (nor the process's repo mutex)
|
|
851
|
+
// or its 5 s poll until dispose(). resume() and abort() release the lock in their own `finally`.
|
|
852
|
+
this.pausedWork = false;
|
|
853
|
+
this.clearStalled();
|
|
854
|
+
if (!this.holdLock) await this.releaseLock();
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
private pauseEvents(l: Readonly<LedgerV1>, reason: string): ExecutorEventInput[] {
|
|
858
|
+
return l.status === "running" ? [{ type: "status-changed", from: "running", to: "paused", reason }] : [];
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
private inboxEvent(l: Readonly<LedgerV1>, kind: InboxKind, severity: InboxItem["severity"], taskId: TaskId | null,
|
|
862
|
+
text: string, createdAt: IsoTime): ExecutorEventInput {
|
|
863
|
+
const item: InboxItem = { id: formatInboxId(kind, nextInboxNumber(l)), kind, severity, taskId, text: clipText(text),
|
|
864
|
+
options: [], answer: null, createdAt };
|
|
865
|
+
return { type: "inbox-added", item };
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
private newInbox(next: Readonly<LedgerV1>, before: number): InboxItem[] {
|
|
869
|
+
return next.inbox.slice(before);
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
private notifyInbox(items: readonly InboxItem[]): void {
|
|
873
|
+
if (this.disposed) return;
|
|
874
|
+
for (const item of items) this.safe(() => this.d.listener.onInbox(item));
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
private safe(fn: () => void): void {
|
|
878
|
+
try {
|
|
879
|
+
fn();
|
|
880
|
+
} catch (e) {
|
|
881
|
+
this.d.logger.warn(`integration queue: listener threw: ${message(e)}`);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** Opens an entry: `pre` events, then its first ISS, in one batch (M1 id rule). */
|
|
886
|
+
private async openEntry(lane: LiveEntry["lane"], init: Omit<IntegrationEntry, "id">, step: IntegrationStep,
|
|
887
|
+
detail: StepDetail, pre: Pre = NONE, failingIds: readonly string[] = []): Promise<LiveEntry> {
|
|
888
|
+
let entry: IntegrationEntry | null = null;
|
|
889
|
+
let startSeq = 0;
|
|
890
|
+
await this.append(l => {
|
|
891
|
+
const events = pre(l);
|
|
892
|
+
startSeq = l.seq + 1 + events.length;
|
|
893
|
+
entry = { ...init, id: entryIdAt(l, events.length), taskIds: [...init.taskIds] };
|
|
894
|
+
return [...events, iss(entry, step, detail, failingIds)];
|
|
895
|
+
});
|
|
896
|
+
if (entry === null) throw new ExecutorError("E_INVALID_INPUT", "entry builder did not run", null);
|
|
897
|
+
const live: LiveEntry = { entry, startSeq, open: step, openedAt: this.d.clock.now(), lane };
|
|
898
|
+
if (lane === "serial") this.serial = live;
|
|
899
|
+
else this.background = live;
|
|
900
|
+
return live;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** ISS for an open entry; a step must not be open (entry rules, phase-1.4.md:960). */
|
|
904
|
+
private async start(live: LiveEntry, step: IntegrationStep, detail: StepDetail,
|
|
905
|
+
patch?: Partial<Pick<IntegrationEntry, "candidate" | "slot" | "taskIds">>, failingIds: readonly string[] = [], pre: Pre = NONE): Promise<void> {
|
|
906
|
+
if (live.open !== null) throw new ExecutorError("E_INVALID_INPUT", "a step is already open", { entry: live.entry.id, step: live.open });
|
|
907
|
+
const entry: IntegrationEntry = { ...live.entry, ...(patch ?? {}) };
|
|
908
|
+
await this.append(l => [...pre(l), iss(entry, step, detail, failingIds)]);
|
|
909
|
+
live.entry = entry;
|
|
910
|
+
live.open = step;
|
|
911
|
+
live.openedAt = this.d.clock.now();
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/** ISE of the open step plus the row's other events; `closes` finishes the entry. Returns the new ledger. */
|
|
915
|
+
private async end(live: LiveEntry, result: IntegrationStepResult, detail: StepDetail, closes: boolean,
|
|
916
|
+
failingIds: readonly string[] = [], post: Pre = NONE): Promise<Readonly<LedgerV1>> {
|
|
917
|
+
const step = live.open;
|
|
918
|
+
if (step === null) throw new ExecutorError("E_INVALID_INPUT", "no step is open", { entry: live.entry.id });
|
|
919
|
+
const ms = this.d.clock.now() - live.openedAt;
|
|
920
|
+
const entry = live.entry;
|
|
921
|
+
const extra: ExecutorEventInput[] = [counterEvent("integration.step", ms, { step, result })];
|
|
922
|
+
if (closes) extra.push(counterEvent("integration.entry", 1, { kind: entry.kind, outcome: result }));
|
|
923
|
+
const next = await this.append(l => [ise(entry, step, result, detail, closes, failingIds), ...post(l), ...extra]);
|
|
924
|
+
live.open = null;
|
|
925
|
+
if (closes) await this.closed(live);
|
|
926
|
+
return next;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
private async closed(live: LiveEntry): Promise<void> {
|
|
930
|
+
if (this.serial === live) {
|
|
931
|
+
this.serial = null;
|
|
932
|
+
this.passed = new Set();
|
|
933
|
+
this.verdicts = new Map();
|
|
934
|
+
this.lastFail = new Map();
|
|
935
|
+
this.stackedCheckout = null;
|
|
936
|
+
if (!this.holdLock) await this.releaseLock();
|
|
937
|
+
}
|
|
938
|
+
if (this.background === live) this.background = null;
|
|
939
|
+
this.clearStalled(live);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
private async releaseLock(): Promise<void> {
|
|
943
|
+
const lock = this.lock;
|
|
944
|
+
this.lock = null;
|
|
945
|
+
if (lock !== null) {
|
|
946
|
+
try {
|
|
947
|
+
await lock.release();
|
|
948
|
+
} catch (e) {
|
|
949
|
+
this.d.logger.warn(`integration queue: repo lock release failed: ${message(e)}`);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/**
|
|
955
|
+
* Takes the repo lock (M5). abort() aborts `ctl` first and must still take the lock for its rollback batches, so only a
|
|
956
|
+
* lane's wait for a new entry (`cancellable`) also ends on `ctl` (QA-3.2-3); dispose() (`lockCtl`) ends every wait.
|
|
957
|
+
*/
|
|
958
|
+
private async takeLock(entryId: string | null, cancellable = false): Promise<void> {
|
|
959
|
+
if (this.lock !== null) return;
|
|
960
|
+
let signal = this.lockCtl.signal;
|
|
961
|
+
const cleanup: Array<() => void> = [];
|
|
962
|
+
if (cancellable) {
|
|
963
|
+
const both = new AbortController();
|
|
964
|
+
const stop = (): void => both.abort();
|
|
965
|
+
for (const s of [this.ctl.signal, this.lockCtl.signal]) {
|
|
966
|
+
if (s.aborted) both.abort();
|
|
967
|
+
s.addEventListener("abort", stop, { once: true });
|
|
968
|
+
cleanup.push(() => s.removeEventListener("abort", stop));
|
|
969
|
+
}
|
|
970
|
+
signal = both.signal;
|
|
971
|
+
}
|
|
972
|
+
let lock: RepoLock;
|
|
973
|
+
try {
|
|
974
|
+
lock = await this.d.locks.acquire(this.ledger.repo.key, { planId: this.d.planId, entryId }, signal,
|
|
975
|
+
info => { void this.lockWaitItem(info); });
|
|
976
|
+
} catch (e) {
|
|
977
|
+
if (errCode(e) === "E_DISPOSED" || signal.aborted) throw e;
|
|
978
|
+
// A plan that is not running (land() of a completed plan, resume() of a paused one) has no pause to take and no
|
|
979
|
+
// poll to retry: the error goes to the caller (land() rejects; the runtime logs it), as before.
|
|
980
|
+
if (this.ledger.status !== "running") throw e;
|
|
981
|
+
// QA-3.2-33: a running lane's lock that cannot be taken (filesystem error) is an infrastructure pause with an item,
|
|
982
|
+
// never a silent lane stop. Work stays queued; the poll retries once the plan runs again.
|
|
983
|
+
await this.infraPauseQueued(`The repository lock for ${this.ledger.repo.key} could not be taken (${clipText(message(e), 500)}).`);
|
|
984
|
+
throw new LaneStop(`repo lock unavailable: ${clipText(message(e), 300)}`);
|
|
985
|
+
} finally {
|
|
986
|
+
for (const c of cleanup) c();
|
|
987
|
+
}
|
|
988
|
+
this.lock = lock;
|
|
989
|
+
this.lockLost = false;
|
|
990
|
+
const takeover = (lock as Partial<RepoLockWithTakeover>).takeover;
|
|
991
|
+
if (takeover === "dead-pid" || takeover === "stale") {
|
|
992
|
+
this.counters.push(counterEvent("integration.lock.takeover", 1, { reason: takeover }));
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** QA-3.2-33: one inbox item for a repo-lock wait that outlasted the factory's report delay. */
|
|
997
|
+
private async lockWaitItem(info: LockWaitInfo): Promise<void> {
|
|
998
|
+
if (this.disposed || this.stopped) return;
|
|
999
|
+
const holder = info.pid === null ? "an unreadable lock file" : `pid ${info.pid} on ${info.hostname ?? "?"} (plan ${info.planId ?? "?"})`;
|
|
1000
|
+
const age = info.heartbeatAgeMs === null ? "unknown" : `${Math.round(info.heartbeatAgeMs / 1000)} s`;
|
|
1001
|
+
const now = this.d.clock.iso();
|
|
1002
|
+
try {
|
|
1003
|
+
const before = this.ledger.inbox.length;
|
|
1004
|
+
const next = await this.append(l => [this.inboxEvent(l, "failure", "blocking", null,
|
|
1005
|
+
`Integration has waited ${Math.round(info.waitedMs / 60_000)} min for the repository lock ${info.file}, held by ${holder}; last heartbeat ${age} ago. If that process is gone or stuck, stop it or remove the lock file.`, now),
|
|
1006
|
+
counterEvent("integration.lock.wait", info.waitedMs, {})]);
|
|
1007
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
this.laneError(e);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/** A StepJournal over a live entry, for the suite and revert runners (they never close). */
|
|
1014
|
+
private journal(live: LiveEntry, signal: AbortSignal): StepJournal {
|
|
1015
|
+
return {
|
|
1016
|
+
get entry() { return live.entry; },
|
|
1017
|
+
signal,
|
|
1018
|
+
start: async (step, detail, patch) => {
|
|
1019
|
+
if (live.open !== null) throw new ExecutorError("E_INVALID_INPUT", "a step is already open", { entry: live.entry.id, step: live.open });
|
|
1020
|
+
await this.start(live, step, detail, patch);
|
|
1021
|
+
},
|
|
1022
|
+
// Never closes: closing ends belong to the queue (M1, A2-1).
|
|
1023
|
+
end: async (result, detail, failingIds) => {
|
|
1024
|
+
await this.end(live, result, detail, false, failingIds ?? []);
|
|
1025
|
+
},
|
|
1026
|
+
assertWriteCwd: async (cwd, purpose) => {
|
|
1027
|
+
this.assertLive();
|
|
1028
|
+
await this.guardWrite(live, cwd, purpose);
|
|
1029
|
+
},
|
|
1030
|
+
counter: (key, value, labels) => {
|
|
1031
|
+
this.counters.push(counterEvent(key, value, labels));
|
|
1032
|
+
},
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** M13 halt: [ISE(open step, refused) if a step is open, status-changed (only if running), IA critical]. The lane stops. */
|
|
1037
|
+
private async halt(live: LiveEntry | null, reason: string, text: string): Promise<never> {
|
|
1038
|
+
const now = this.d.clock.iso();
|
|
1039
|
+
const before = this.ledger.inbox.length;
|
|
1040
|
+
const post: Pre = l => [...this.pauseEvents(l, reason), this.inboxEvent(l, "failure", "critical", null, text, now)];
|
|
1041
|
+
let next: Readonly<LedgerV1>;
|
|
1042
|
+
if (live !== null && live.open !== null) next = await this.end(live, "refused", { v: 1, reason }, false, [], post);
|
|
1043
|
+
else next = await this.append(post);
|
|
1044
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
1045
|
+
if (live !== null) this.markStalled(live);
|
|
1046
|
+
await this.releaseForPause(live);
|
|
1047
|
+
throw new LaneStop(reason);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* QA-3.2-3: a paused serial entry does not keep the repo lock (other plans on the same repository would deadlock);
|
|
1052
|
+
* the stalled poll or resume() takes it again before the rollback. resume() and abort() release it themselves.
|
|
1053
|
+
*/
|
|
1054
|
+
private async releaseForPause(live: LiveEntry | null): Promise<void> {
|
|
1055
|
+
if (this.holdLock || (live !== null && live.lane !== "serial")) return;
|
|
1056
|
+
await this.releaseLock();
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/** QA-3.2-4: a lost repo lock means another holder may write; no git write starts after it fired (halt instead). */
|
|
1060
|
+
private async assertLock(live: LiveEntry | null, verify = false): Promise<void> {
|
|
1061
|
+
// QA-3.2-28: once lost, every later write stops too (resume and abort loops included) until a lock is taken again.
|
|
1062
|
+
if (this.lockLost) throw new LaneStop("integration-lock-lost");
|
|
1063
|
+
const lock = this.lock;
|
|
1064
|
+
if (lock === null) return;
|
|
1065
|
+
// Right before the CAS the file itself is re-read (token compare): `lost` is only as fresh as the last heartbeat.
|
|
1066
|
+
const gone = lock.lost.aborted || (verify && lock.verify !== undefined && !(await lock.verify()));
|
|
1067
|
+
if (!gone) return;
|
|
1068
|
+
this.lockLost = true;
|
|
1069
|
+
this.lock = null;
|
|
1070
|
+
await lock.release().catch(() => undefined);
|
|
1071
|
+
await this.halt(live, "integration-lock-lost",
|
|
1072
|
+
`The repository lock for ${this.ledger.repo.key} was lost (taken over or removed) while integration entry ${live?.entry.id ?? "(none)"} was running; no further git write was made. The plan is paused; unpause to roll the entry back and retry.`);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** Every queue-side git write: the lock check (QA-3.2-4), then the write-cwd guard (M30, I5). */
|
|
1076
|
+
private async guardWrite(live: LiveEntry | null, cwd: string, purpose: WritePurpose): Promise<void> {
|
|
1077
|
+
if (live === null || live.lane === "serial") await this.assertLock(live);
|
|
1078
|
+
await this.d.guard.assertWriteCwd(cwd, purpose);
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1082
|
+
// M36 stalled entries (one per lane, QA-3.2-5)
|
|
1083
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1084
|
+
|
|
1085
|
+
private markStalled(live: LiveEntry): void {
|
|
1086
|
+
this.stalled.set(live.lane, live);
|
|
1087
|
+
this.ensurePoll();
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** The 5 s status poll runs while a stalled entry exists or queued work waits behind an infrastructure pause. */
|
|
1091
|
+
private ensurePoll(): void {
|
|
1092
|
+
if (this.stalledTimer !== null || this.disposed) return;
|
|
1093
|
+
const tick = (): void => {
|
|
1094
|
+
this.stalledTimer = null;
|
|
1095
|
+
if ((this.stalled.size === 0 && !this.pausedWork) || this.disposed) return;
|
|
1096
|
+
void this.pokeStalled();
|
|
1097
|
+
if ((this.stalled.size > 0 || this.pausedWork) && !this.disposed) this.stalledTimer = this.d.clock.setTimer(STALLED_POLL_MS, tick);
|
|
1098
|
+
};
|
|
1099
|
+
this.stalledTimer = this.d.clock.setTimer(STALLED_POLL_MS, tick);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
private clearStalled(live?: LiveEntry): void {
|
|
1103
|
+
if (live === undefined) this.stalled.clear();
|
|
1104
|
+
else if (this.stalled.get(live.lane) === live) this.stalled.delete(live.lane);
|
|
1105
|
+
if (this.stalled.size > 0 || (this.pausedWork && !this.disposed)) return;
|
|
1106
|
+
if (this.stalledTimer !== null) this.d.clock.clearTimer(this.stalledTimer);
|
|
1107
|
+
this.stalledTimer = null;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/**
|
|
1111
|
+
* M36: once status is running again, the in-process rollback (`reason:"stalled"`) of every stalled entry (each lane's,
|
|
1112
|
+
* oldest first), then requeue or rerun as resume() would.
|
|
1113
|
+
*/
|
|
1114
|
+
private async pokeStalled(): Promise<void> {
|
|
1115
|
+
if (this.disposed || this.stopped || this.aborting) {
|
|
1116
|
+
// QA-3.2-34: a stopped or aborting queue never rolls back in process; its 5 s poll must not re-arm forever.
|
|
1117
|
+
this.pausedWork = false;
|
|
1118
|
+
if (this.stalledTimer !== null) this.d.clock.clearTimer(this.stalledTimer);
|
|
1119
|
+
this.stalledTimer = null;
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
if (this.ledger.status !== "running") return;
|
|
1123
|
+
const wake = this.pausedWork;
|
|
1124
|
+
this.pausedWork = false;
|
|
1125
|
+
if (this.stalled.size === 0) {
|
|
1126
|
+
// Nothing stalled: kick only for work an infrastructure pause left queued (the poll's own wake-up). enqueue() and
|
|
1127
|
+
// checkPhase() kick by themselves; a second kick from here would set both lanes' `wanted` flags at once.
|
|
1128
|
+
if (wake) {
|
|
1129
|
+
this.clearStalled();
|
|
1130
|
+
this.kick();
|
|
1131
|
+
}
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
const lives = [...this.stalled.values()].sort((a, b) => a.startSeq - b.startSeq);
|
|
1135
|
+
this.clearStalled();
|
|
1136
|
+
const phases = new Set<PhaseId>();
|
|
1137
|
+
try {
|
|
1138
|
+
await this.withSerial(async () => {
|
|
1139
|
+
for (const live of lives) {
|
|
1140
|
+
if (live.lane === "serial") await this.takeLock(live.entry.id);
|
|
1141
|
+
const rolled = await this.rollbackEntry(this.toOpen(live), "stalled");
|
|
1142
|
+
await this.followUp(rolled, null, phases);
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
for (const p of phases) await this.checkPhaseSafe(p);
|
|
1146
|
+
} catch (e) {
|
|
1147
|
+
this.laneError(e);
|
|
1148
|
+
// QA-3.2-29: an entry whose rollback failed is still open in the ledger: keep it stalled for the next poll.
|
|
1149
|
+
if (!this.disposed && !this.stopped) {
|
|
1150
|
+
const open = new Set(this.d.writer.openIntegration().map(o => o.entry.id));
|
|
1151
|
+
for (const live of lives) if (open.has(live.entry.id) && !this.stalled.has(live.lane)) this.markStalled(live);
|
|
1152
|
+
}
|
|
1153
|
+
if (this.serial !== null && this.stalled.get("serial") === this.serial && !this.holdLock) await this.releaseLock();
|
|
1154
|
+
}
|
|
1155
|
+
this.kick();
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
private toOpen(live: LiveEntry): OpenIntegrationEntry {
|
|
1159
|
+
return { entry: live.entry, startSeq: live.startSeq, step: live.open ?? "rollback", edge: live.open === null ? "end" : "start",
|
|
1160
|
+
result: null };
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
private laneError(e: unknown): void {
|
|
1164
|
+
if (e instanceof LaneStop) return;
|
|
1165
|
+
if (errCode(e) === "E_DISPOSED" || errCode(e) === "E_LOCK_LOST") return;
|
|
1166
|
+
this.d.logger.warn(`integration queue: lane error: ${message(e)}`);
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1170
|
+
// Small reads and event helpers
|
|
1171
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1172
|
+
|
|
1173
|
+
private async slotLease(slot: string, owner: string): Promise<SlotLease> {
|
|
1174
|
+
const rec = await this.d.pool.get(slot);
|
|
1175
|
+
if (rec === null) throw new ExecutorError("E_SLOT_BROKEN", "slot not found", { slot });
|
|
1176
|
+
return { slot, path: rec.path, planId: this.d.planId, owner: rec.owner ?? owner, commit: rec.commit ?? "" };
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
private async integrationSlot(): Promise<SlotLease> {
|
|
1180
|
+
if (this.integrationLease === null) this.integrationLease = await this.d.pool.acquireSpecial(this.d.planId, "integration");
|
|
1181
|
+
return this.integrationLease;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/**
|
|
1185
|
+
* `refs/heads/<integration.branch>` read in `repo.toplevel` (the common repository, not the integration worktree,
|
|
1186
|
+
* which may be missing or broken; QA-3.2-9). Null if the ref does not exist; a git failure throws `GitReadError`.
|
|
1187
|
+
*/
|
|
1188
|
+
private async branchTip(): Promise<string | null> {
|
|
1189
|
+
const l = this.ledger;
|
|
1190
|
+
return this.readRefOrThrow(`refs/heads/${l.integration.branch}`);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
private async readRefOrThrow(ref: string): Promise<string | null> {
|
|
1194
|
+
try {
|
|
1195
|
+
return await this.d.igit.readRef(this.ledger.repo.toplevel, ref);
|
|
1196
|
+
} catch (e) {
|
|
1197
|
+
throw new GitReadError(ref, e);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
/** Reads a ref with up to CHECK_TRIES attempts; "infra" when git never ran (M13a), else the ref (null = missing). */
|
|
1202
|
+
private async readRefRetry(ref: string): Promise<{ kind: "ok"; at: string | null } | { kind: "infra"; message: string }> {
|
|
1203
|
+
let last = "";
|
|
1204
|
+
for (let n = 0; n < CHECK_TRIES; n++) {
|
|
1205
|
+
try {
|
|
1206
|
+
return { kind: "ok", at: await this.readRefOrThrow(ref) };
|
|
1207
|
+
} catch (e) {
|
|
1208
|
+
last = message(e);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
return { kind: "infra", message: last };
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
private async taskTip(id: TaskId): Promise<string> {
|
|
1215
|
+
const l = this.ledger;
|
|
1216
|
+
const branch = l.tasks[id]?.branch ?? null;
|
|
1217
|
+
if (branch === null) throw new ExecutorError("E_INVALID_INPUT", "task has no branch", { taskId: id });
|
|
1218
|
+
const tip = await this.readRefOrThrow(`refs/heads/${branch}`);
|
|
1219
|
+
if (tip === null) throw new ExecutorError("E_GIT", `task branch refs/heads/${branch} does not exist`, { taskId: id, branch });
|
|
1220
|
+
return tip;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
private tt(l: Readonly<LedgerV1>, id: TaskId, to: TaskState, trigger: TransitionTrigger, detail: string | null = null): ExecutorEventInput[] {
|
|
1224
|
+
const t = l.tasks[id];
|
|
1225
|
+
if (t === undefined || !TASK_TRANSITIONS[t.state].includes(to)) return [];
|
|
1226
|
+
return [{ type: "task-transition", taskId: id, from: t.state, to, trigger, detail }];
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
private ax(l: Readonly<LedgerV1>, id: TaskId, text: string): ExecutorEventInput[] {
|
|
1230
|
+
const t = l.tasks[id];
|
|
1231
|
+
const last = t?.attempts[t.attempts.length - 1];
|
|
1232
|
+
if (last === undefined) return [];
|
|
1233
|
+
return [{ type: "attempt-context", taskId: id, n: last.n, context: clipText(text) }];
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
/** True when no task of the entry other than `decided` is still `integrating` (row 30 `closes`, M19). */
|
|
1237
|
+
private closesWith(l: Readonly<LedgerV1>, live: LiveEntry, decided: readonly TaskId[]): boolean {
|
|
1238
|
+
return !live.entry.taskIds.some(id => !decided.includes(id) && l.tasks[id]?.state === "integrating");
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1242
|
+
// 4.2 Task or batch entry
|
|
1243
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1244
|
+
|
|
1245
|
+
/** Plan rows for a stack: tip and upstream (M14) per task, read before the journal. */
|
|
1246
|
+
private async stackPlan(ids: readonly TaskId[], head: string): Promise<Array<{ taskId: TaskId; tip: string; upstream: string }>> {
|
|
1247
|
+
const top = this.ledger.repo.toplevel;
|
|
1248
|
+
const out: Array<{ taskId: TaskId; tip: string; upstream: string }> = [];
|
|
1249
|
+
for (const id of ids) {
|
|
1250
|
+
const tip = await this.taskTip(id);
|
|
1251
|
+
let upstream: string;
|
|
1252
|
+
try {
|
|
1253
|
+
upstream = await this.d.igit.mergeBase(top, head, tip);
|
|
1254
|
+
} catch (e) {
|
|
1255
|
+
// Nit (QA-3.2 round 2): `git merge-base` exit 1 = no common ancestor: the task's branch is unrelated (owner repair,
|
|
1256
|
+
// a blocking item), not an infrastructure failure.
|
|
1257
|
+
const detail = e instanceof ExecutorError ? e.detail : null;
|
|
1258
|
+
if (detail !== null && typeof detail === "object" && !Array.isArray(detail) && detail.code === 1) {
|
|
1259
|
+
throw new ExecutorError("E_GIT", `task branch tip ${tip} has no common ancestor with the integration head ${head}`, { taskId: id });
|
|
1260
|
+
}
|
|
1261
|
+
throw new GitReadError(`merge-base ${head} ${tip}`, e);
|
|
1262
|
+
}
|
|
1263
|
+
try {
|
|
1264
|
+
upstream = await this.reintegrationUpstream(id, tip, upstream);
|
|
1265
|
+
} catch (e) {
|
|
1266
|
+
throw new GitReadError(`ancestry of ${tip}`, e);
|
|
1267
|
+
}
|
|
1268
|
+
out.push({ taskId: id, tip, upstream });
|
|
1269
|
+
}
|
|
1270
|
+
return out;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* QA-3.2-10 / QA-3.2-25: the rebase upstream of a task that was reverted. A retry built on the old task branch whose
|
|
1275
|
+
* original change lies below the merge base (fast-forwarded as is, then reverted) would replay only its fixes. Unless the
|
|
1276
|
+
* tip already contains the latest revert (a retry rebuilt on the head keeps the merge base), the upstream is the one
|
|
1277
|
+
* journaled in the task's first rebase step (its original base, ancestor of the tip), else the `from` of the OLDEST revert
|
|
1278
|
+
* whose `to` is below the merge base. Any number of reverts keeps the original change.
|
|
1279
|
+
*/
|
|
1280
|
+
private async reintegrationUpstream(id: TaskId, tip: string, mergeBase: string): Promise<string> {
|
|
1281
|
+
const reverts = await this.revertedRanges(id);
|
|
1282
|
+
const latest = reverts[reverts.length - 1];
|
|
1283
|
+
if (latest === undefined) return mergeBase;
|
|
1284
|
+
const top = this.ledger.repo.toplevel;
|
|
1285
|
+
if (latest.revertHead !== null && await this.d.igit.isAncestor(top, latest.revertHead, tip)) return mergeBase;
|
|
1286
|
+
const first = await this.firstUpstream(id);
|
|
1287
|
+
if (first !== null && first !== mergeBase && await this.d.igit.isAncestor(top, first, tip)) return first;
|
|
1288
|
+
for (const rv of reverts) {
|
|
1289
|
+
if (rv.to !== rv.from && await this.d.igit.isAncestor(top, rv.to, mergeBase)) return rv.from;
|
|
1290
|
+
}
|
|
1291
|
+
return mergeBase;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/** Every revert of `id` that reached the branch (closing `revert-fast-forward` ok), oldest first, from history. */
|
|
1295
|
+
private async revertedRanges(id: TaskId): Promise<Array<{ from: string; to: string; revertHead: string | null }>> {
|
|
1296
|
+
const steps = await this.loadSteps();
|
|
1297
|
+
const out: Array<{ from: string; to: string; revertHead: string | null }> = [];
|
|
1298
|
+
for (let i = 0; i < steps.length; i++) {
|
|
1299
|
+
const ev = steps[i];
|
|
1300
|
+
if (ev === undefined || ev.entry.kind !== "revert" || ev.step !== "revert-fast-forward" || !ev.closes || ev.result !== "ok") continue;
|
|
1301
|
+
if (ev.entry.taskIds[0] !== id) continue;
|
|
1302
|
+
let start: Record<string, unknown> | null = null;
|
|
1303
|
+
for (let k = i; k >= 0 && start === null; k--) {
|
|
1304
|
+
const s = steps[k];
|
|
1305
|
+
if (s !== undefined && s.entry.id === ev.entry.id && s.edge === "start" && s.step === "revert-fast-forward") start = parseDetail(s.detail);
|
|
1306
|
+
}
|
|
1307
|
+
const c = start?.culprit as Partial<RangeDetail> | undefined;
|
|
1308
|
+
if (c === undefined || c.taskId !== id || typeof c.from !== "string" || typeof c.to !== "string") continue;
|
|
1309
|
+
out.push({ from: c.from, to: c.to, revertHead: ev.entry.candidate });
|
|
1310
|
+
}
|
|
1311
|
+
return out;
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
/** The `upstream` journaled for `id` in the first rebase step that planned it (its original base), or null. */
|
|
1315
|
+
private async firstUpstream(id: TaskId): Promise<string | null> {
|
|
1316
|
+
for (const ev of await this.loadSteps()) {
|
|
1317
|
+
if (ev.step !== "rebase" || ev.edge !== "start" || (ev.entry.kind !== "task" && ev.entry.kind !== "batch")) continue;
|
|
1318
|
+
const tasks = parseDetail(ev.detail)?.tasks;
|
|
1319
|
+
if (!Array.isArray(tasks)) continue;
|
|
1320
|
+
for (const t of tasks as unknown[]) {
|
|
1321
|
+
const x = t as { taskId?: unknown; upstream?: unknown } | null;
|
|
1322
|
+
if (x !== null && typeof x === "object" && x.taskId === id && typeof x.upstream === "string") return x.upstream;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return null;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
private async runTaskEntry(ids: TaskId[], requeue: boolean): Promise<void> {
|
|
1329
|
+
const l0 = this.ledger;
|
|
1330
|
+
for (const id of ids) {
|
|
1331
|
+
this.taskWaits.get(id)?.end("dequeued");
|
|
1332
|
+
this.taskWaits.delete(id);
|
|
1333
|
+
}
|
|
1334
|
+
const observation = this.pendingService(l0, ids, l0.tasks[ids[0] ?? ""]?.phase ?? null, "rebase");
|
|
1335
|
+
const head = l0.integration.head;
|
|
1336
|
+
const lastId = ids[ids.length - 1];
|
|
1337
|
+
const slot = lastId === undefined ? null : l0.tasks[lastId]?.slot ?? null;
|
|
1338
|
+
let plan: Array<{ taskId: TaskId; tip: string; upstream: string }> | null = null;
|
|
1339
|
+
let infra: string | null = null;
|
|
1340
|
+
for (let n = 1; plan === null && n <= CHECK_TRIES; n++) {
|
|
1341
|
+
try {
|
|
1342
|
+
if (slot === null) throw new ExecutorError("E_INVALID_INPUT", "task has no slot", { taskId: lastId ?? null });
|
|
1343
|
+
plan = await this.stackPlan(ids, head);
|
|
1344
|
+
} catch (e) {
|
|
1345
|
+
if (e instanceof GitReadError) {
|
|
1346
|
+
// QA-3.2-9: git could not run (infrastructure), not a missing branch: retry, then pause with the tasks kept queued.
|
|
1347
|
+
infra = e.message;
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
// A missing branch or slot: nothing is journaled yet; the tasks cannot be dequeued until the owner repairs them.
|
|
1351
|
+
for (const id of ids) this.dropQueued(id);
|
|
1352
|
+
const now = this.d.clock.iso();
|
|
1353
|
+
const before = this.ledger.inbox.length;
|
|
1354
|
+
const next = await this.append(l => [this.inboxEvent(l, "failure", "blocking", ids[0] ?? null,
|
|
1355
|
+
`Integration could not read task ${ids.join(", ")}: ${message(e)}`, now)]);
|
|
1356
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if (plan === null) {
|
|
1361
|
+
if (requeue) this.requeued.unshift({ taskIds: [...ids], phaseId: l0.tasks[ids[0] ?? ""]?.phase ?? null, startSeq: 0 });
|
|
1362
|
+
await this.infraPauseQueued(`Integration of ${ids.join(", ")} could not read its branches ${CHECK_TRIES} times (${clipText(infra ?? "", 500)}).`);
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
try {
|
|
1366
|
+
const wait = observation?.start("service-wait", "repo-lock");
|
|
1367
|
+
try {
|
|
1368
|
+
await this.takeLock(null, true);
|
|
1369
|
+
wait?.end("acquired");
|
|
1370
|
+
} finally { wait?.end("error"); }
|
|
1371
|
+
} catch (e) {
|
|
1372
|
+
// The requeued group was taken off the list by pickSerial: put it back for the next pass.
|
|
1373
|
+
if (requeue) this.requeued.unshift({ taskIds: [...ids], phaseId: l0.tasks[ids[0] ?? ""]?.phase ?? null, startSeq: 0 });
|
|
1374
|
+
throw e;
|
|
1375
|
+
}
|
|
1376
|
+
// QA-3.2-32: a task cancelled (or otherwise moved on) while this lane read its branches or waited for the repo lock is
|
|
1377
|
+
// dropped here, before any journal line; the rest is integrated.
|
|
1378
|
+
const l1 = this.ledger;
|
|
1379
|
+
const want: TaskState = requeue ? "integrating" : "verified";
|
|
1380
|
+
const keep = ids.filter(id => l1.tasks[id]?.state === want);
|
|
1381
|
+
const dropped = ids.filter(id => !keep.includes(id));
|
|
1382
|
+
for (const id of ids) this.dropQueued(id);
|
|
1383
|
+
if (dropped.length > 0) {
|
|
1384
|
+
this.d.logger.warn(`integration queue: ${dropped.join(", ")} no longer ${want} after the repo-lock wait; dropped without an entry`);
|
|
1385
|
+
this.counters.push(counterEvent("integration.dequeue.skipped", dropped.length, { reason: "state-changed" }));
|
|
1386
|
+
}
|
|
1387
|
+
const keptLast = keep[keep.length - 1];
|
|
1388
|
+
const keptSlot = keptLast === undefined ? null : l1.tasks[keptLast]?.slot ?? null;
|
|
1389
|
+
if (keptLast === undefined || keptSlot === null) {
|
|
1390
|
+
if (this.serial === null && !this.holdLock) await this.releaseLock();
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
const keptPlan = plan.filter(p => keep.includes(p.taskId));
|
|
1394
|
+
const phaseId = l1.tasks[keep[0] ?? ""]?.phase ?? null;
|
|
1395
|
+
const live = await this.openEntry("serial",
|
|
1396
|
+
{ kind: keep.length > 1 ? "batch" : "task", phaseId, taskIds: keep, slot: keptSlot, baseHead: head, candidate: null },
|
|
1397
|
+
"rebase", { v: 1, onto: head, tasks: keptPlan },
|
|
1398
|
+
// Row 28: verified->integrating per task, then ISS(rebase); requeued tasks are already integrating (ISS only).
|
|
1399
|
+
l => {
|
|
1400
|
+
if (requeue) return [];
|
|
1401
|
+
const out: ExecutorEventInput[] = [];
|
|
1402
|
+
for (const id of keep) {
|
|
1403
|
+
if (l.tasks[id]?.state === "verified") {
|
|
1404
|
+
out.push(...this.tt(l, id, "integrating", "dequeued"));
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
// Nit (QA-3.2): never drop a row-28 transition silently; the ledger then judges the entry.
|
|
1408
|
+
this.d.logger.warn(`integration queue: ${id} is ${l.tasks[id]?.state ?? "unknown"}, not verified, at dequeue; no verified->integrating transition`);
|
|
1409
|
+
out.push(counterEvent("integration.dequeue.skipped", 1, { reason: "not-verified-at-batch" }));
|
|
1410
|
+
}
|
|
1411
|
+
return out;
|
|
1412
|
+
});
|
|
1413
|
+
await this.integrateStack(live, keep, keptPlan);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/** M13a with no entry open: [status-changed running->paused "integration-infrastructure", IA critical]; work stays queued. */
|
|
1417
|
+
private async infraPauseQueued(text: string): Promise<void> {
|
|
1418
|
+
const now = this.d.clock.iso();
|
|
1419
|
+
const before = this.ledger.inbox.length;
|
|
1420
|
+
const next = await this.append(l => [...this.pauseEvents(l, "integration-infrastructure"),
|
|
1421
|
+
this.inboxEvent(l, "failure", "critical", null, `${text} The plan is paused; unpause to retry.`, now)]);
|
|
1422
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
1423
|
+
this.pausedWork = true;
|
|
1424
|
+
this.ensurePoll();
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/** `integrateStack(T)` of memo §4.2. `plan` given = the rebase step is already open with that detail. */
|
|
1428
|
+
private async integrateStack(live: LiveEntry, T: readonly TaskId[],
|
|
1429
|
+
plan: Array<{ taskId: TaskId; tip: string; upstream: string }> | null): Promise<void> {
|
|
1430
|
+
const { stacked, deferred } = await this.stack(live, T, plan);
|
|
1431
|
+
if (stacked.length > 0) {
|
|
1432
|
+
const verdict = await this.check(live, T.length === 1 ? "checks" : "batch-checks", stacked);
|
|
1433
|
+
if (verdict === "pass") {
|
|
1434
|
+
if (T.length > 1) this.counters.push(counterEvent("integration.batch", stacked.length, { outcome: "pass" }));
|
|
1435
|
+
await this.integrate(live, stacked);
|
|
1436
|
+
} else {
|
|
1437
|
+
if (stacked.length > 1) this.counters.push(counterEvent("integration.batch", stacked.length, { outcome: "halved" }));
|
|
1438
|
+
this.probes = 0;
|
|
1439
|
+
await this.halve(live, stacked);
|
|
1440
|
+
if (stacked.length > 1) this.counters.push(counterEvent("integration.bisect.probes", this.probes, { kind: "halves" }));
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
if (deferred.length > 0) await this.integrateStack(live, deferred, null);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
private probes = 0;
|
|
1447
|
+
private taskWaits = new Map<TaskId, NonNullable<ReturnType<ServiceObservation["start"]>>>();
|
|
1448
|
+
private suiteWaits = new Map<PhaseId, NonNullable<ReturnType<ServiceObservation["start"]>>>();
|
|
1449
|
+
|
|
1450
|
+
private pendingService(l: Readonly<LedgerV1>, ids: readonly TaskId[], phaseId: PhaseId | null,
|
|
1451
|
+
component: ServiceIdentity["component"]): ServiceObservation | undefined {
|
|
1452
|
+
return executorServiceObservation(this.d.clock, this.d.planId, () => {
|
|
1453
|
+
const task = l.tasks[ids[0] ?? ""];
|
|
1454
|
+
return { planId: this.d.planId, taskId: task?.id ?? null, attempt: task?.attempts.at(-1)?.n ?? null,
|
|
1455
|
+
phaseId, entryId: null, taskIds: ids, component, candidate: null };
|
|
1456
|
+
});
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
private suiteWaiting(l: Readonly<LedgerV1>, phaseId: PhaseId): void {
|
|
1460
|
+
if (this.suiteWaits.has(phaseId)) return;
|
|
1461
|
+
const wait = this.pendingService(l, [], phaseId, "phase-suite")?.start("service-wait", "background-lane");
|
|
1462
|
+
if (wait !== undefined) this.suiteWaits.set(phaseId, wait);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
private endWaiting(result: string): void {
|
|
1466
|
+
for (const wait of this.taskWaits.values()) wait.end(result);
|
|
1467
|
+
for (const wait of this.suiteWaits.values()) wait.end(result);
|
|
1468
|
+
this.taskWaits.clear();
|
|
1469
|
+
this.suiteWaits.clear();
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
private service(live: LiveEntry, component: ServiceIdentity["component"], candidate: string | null): ServiceObservation | undefined {
|
|
1473
|
+
return executorServiceObservation(this.d.clock, this.d.planId, () => ({ planId: this.d.planId,
|
|
1474
|
+
taskId: null, attempt: null, phaseId: live.entry.phaseId, entryId: live.entry.id,
|
|
1475
|
+
taskIds: live.entry.taskIds, component, candidate }));
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
/** M17: stack T in the slot of T's last task. A conflict on the head is terminal (row 31); against a batch-mate it defers. */
|
|
1479
|
+
private async stack(live: LiveEntry, T: readonly TaskId[],
|
|
1480
|
+
given: Array<{ taskId: TaskId; tip: string; upstream: string }> | null): Promise<StackResult> {
|
|
1481
|
+
this.stackedCheckout = null;
|
|
1482
|
+
const head = this.ledger.integration.head;
|
|
1483
|
+
const lastId = T[T.length - 1];
|
|
1484
|
+
const slotId = lastId === undefined ? null : this.ledger.tasks[lastId]?.slot ?? null;
|
|
1485
|
+
if (slotId === null) throw new ExecutorError("E_INVALID_INPUT", "stack task has no slot", { taskId: lastId ?? null });
|
|
1486
|
+
let plan = given ?? await this.stackPlan(T, head);
|
|
1487
|
+
if (live.open === null) await this.start(live, "rebase", { v: 1, onto: head, tasks: plan }, { slot: slotId });
|
|
1488
|
+
const lease = await this.slotLease(slotId, lastId ?? live.entry.id);
|
|
1489
|
+
const stacked: RangeDetail[] = [];
|
|
1490
|
+
const deferred: TaskId[] = [];
|
|
1491
|
+
let prev = head;
|
|
1492
|
+
for (let i = 0; i < plan.length; i++) {
|
|
1493
|
+
const p = plan[i];
|
|
1494
|
+
if (p === undefined) continue;
|
|
1495
|
+
if (this.ctl.signal.aborted) throw new LaneStop("aborted");
|
|
1496
|
+
const observation = this.service(live, "rebase", p.tip);
|
|
1497
|
+
const preparation = observation?.start("service-prep", "checkout-reset");
|
|
1498
|
+
try {
|
|
1499
|
+
await this.guardWrite(live, lease.path, "slot");
|
|
1500
|
+
this.stackedCheckout = null;
|
|
1501
|
+
await this.d.pool.reset(lease.slot, p.tip);
|
|
1502
|
+
preparation?.end("completed");
|
|
1503
|
+
} finally { preparation?.end("error"); }
|
|
1504
|
+
// GitOps observes only the rebase process, after its pointer/config preparation and before conflict cleanup.
|
|
1505
|
+
const r = await (observation === undefined ? this.d.git.rebaseOnto(lease.path, prev, p.upstream)
|
|
1506
|
+
: this.d.git.rebaseOnto(lease.path, prev, p.upstream, observation));
|
|
1507
|
+
if (r.ok) {
|
|
1508
|
+
this.stackedCheckout = { slot: lease.slot, head: r.head };
|
|
1509
|
+
stacked.push({ taskId: p.taskId, from: prev, to: r.head });
|
|
1510
|
+
prev = r.head;
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
await this.assertLock(live); // QA-3.2-28: rebaseAbort is a write too
|
|
1514
|
+
await this.d.git.rebaseAbort(lease.path);
|
|
1515
|
+
this.stackedCheckout = null;
|
|
1516
|
+
if (prev !== head) {
|
|
1517
|
+
deferred.push(p.taskId);
|
|
1518
|
+
continue;
|
|
1519
|
+
}
|
|
1520
|
+
// Row 31: a conflict with the integration head itself.
|
|
1521
|
+
await this.conflict(live, p, r.conflicts, head, lease.path);
|
|
1522
|
+
const rest = plan.slice(i + 1);
|
|
1523
|
+
if (rest.length > 0) {
|
|
1524
|
+
plan = rest;
|
|
1525
|
+
i = -1;
|
|
1526
|
+
await this.start(live, "rebase", { v: 1, onto: head, tasks: rest }, { slot: slotId });
|
|
1527
|
+
} else {
|
|
1528
|
+
return { stacked, deferred };
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
await this.end(live, "ok", { v: 1, stacked: rangesOf(stacked), deferred: [...deferred] }, false);
|
|
1532
|
+
return { stacked, deferred };
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/** M15 summaries, then the row-31 batch [ISE(rebase, conflict), TT integrating->conflict, AX]. The slot is kept (M35). */
|
|
1536
|
+
private async conflict(live: LiveEntry, p: { taskId: TaskId; tip: string; upstream: string }, conflicts: readonly string[],
|
|
1537
|
+
head: string, cwd: string): Promise<void> {
|
|
1538
|
+
const paths = conflicts.slice(0, 20);
|
|
1539
|
+
const ours: Record<string, Array<{ sha: string; subject: string }>> = {};
|
|
1540
|
+
const theirs: Record<string, Array<{ sha: string; subject: string }>> = {};
|
|
1541
|
+
for (const path of paths) {
|
|
1542
|
+
ours[path] = await this.d.igit.logPaths(cwd, p.upstream, head, path, 5).catch(() => []);
|
|
1543
|
+
theirs[path] = await this.d.igit.logPaths(cwd, p.upstream, p.tip, path, 5).catch(() => []);
|
|
1544
|
+
}
|
|
1545
|
+
const lines = [`Rebase of ${p.taskId} onto the integration head ${head} conflicted in ${conflicts.length} path(s).`];
|
|
1546
|
+
for (const path of paths) {
|
|
1547
|
+
lines.push(`- ${path}`);
|
|
1548
|
+
for (const c of ours[path] ?? []) lines.push(` integrated ${c.sha.slice(0, 12)} ${c.subject}`);
|
|
1549
|
+
for (const c of theirs[path] ?? []) lines.push(` this task ${c.sha.slice(0, 12)} ${c.subject}`);
|
|
1550
|
+
}
|
|
1551
|
+
if (conflicts.length > paths.length) lines.push(`(${conflicts.length - paths.length} more paths not shown)`);
|
|
1552
|
+
lines.push("Rebase the task onto the integration head and resolve these paths.");
|
|
1553
|
+
const text = lines.join("\n");
|
|
1554
|
+
// Row 31 order (phase-1.4.md:942): ISE, AX, TT.
|
|
1555
|
+
await this.endDecide(live, "conflict",
|
|
1556
|
+
{ v: 1, taskId: p.taskId, paths, truncated: conflicts.length > paths.length, ours, theirs }, [p.taskId], [],
|
|
1557
|
+
l => [...this.ax(l, p.taskId, text), ...this.tt(l, p.taskId, "conflict", "rebase-conflict")]);
|
|
1558
|
+
if (!this.disposed) this.safe(() => this.d.listener.onConflict(p.taskId));
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/** ISE of the open step whose `closes` is computed against the ledger the batch applies to (row 30/31/32 rule). */
|
|
1562
|
+
private async endDecide(live: LiveEntry, result: IntegrationStepResult, detail: StepDetail, decided: readonly TaskId[],
|
|
1563
|
+
failingIds: readonly string[], post: Pre, onCloses?: (closes: boolean) => void): Promise<Readonly<LedgerV1>> {
|
|
1564
|
+
const step = live.open;
|
|
1565
|
+
if (step === null) throw new ExecutorError("E_INVALID_INPUT", "no step is open", { entry: live.entry.id });
|
|
1566
|
+
const ms = this.d.clock.now() - live.openedAt;
|
|
1567
|
+
const entry = live.entry;
|
|
1568
|
+
let closes = false;
|
|
1569
|
+
const next = await this.append(l => {
|
|
1570
|
+
closes = this.closesWith(l, live, decided);
|
|
1571
|
+
const extra: ExecutorEventInput[] = [counterEvent("integration.step", ms, { step, result })];
|
|
1572
|
+
if (closes) extra.push(counterEvent("integration.entry", 1, { kind: entry.kind, outcome: result }));
|
|
1573
|
+
return [ise(entry, step, result, detail, closes, failingIds), ...post(l), ...extra];
|
|
1574
|
+
});
|
|
1575
|
+
live.open = null;
|
|
1576
|
+
onCloses?.(closes);
|
|
1577
|
+
if (closes) await this.closed(live);
|
|
1578
|
+
return next;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
private lastFail = new Map<string, { ids: string[]; detail: CheckDetail }>();
|
|
1582
|
+
|
|
1583
|
+
/** One check run at the stack tip (M8-M13). Pass ends the step ok; fail leaves it open for the caller (row 32 or halving). */
|
|
1584
|
+
private async check(live: LiveEntry, step: CheckStep, S: readonly RangeDetail[]): Promise<"pass" | "fail"> {
|
|
1585
|
+
const head = this.ledger.integration.head;
|
|
1586
|
+
const tipRange = S[S.length - 1];
|
|
1587
|
+
if (tipRange === undefined) throw new ExecutorError("E_INVALID_INPUT", "empty stack", null);
|
|
1588
|
+
const candidate = tipRange.to;
|
|
1589
|
+
let checkout = this.stackedCheckout;
|
|
1590
|
+
this.stackedCheckout = null;
|
|
1591
|
+
const tasks = S.map(r => r.taskId);
|
|
1592
|
+
if (step === "bisect") this.probes++;
|
|
1593
|
+
const memo = this.verdicts.get(candidate);
|
|
1594
|
+
if (memo !== undefined) {
|
|
1595
|
+
await this.start(live, step, { v: 1, base: head, candidate, tasks, probe: "memo" }, { candidate });
|
|
1596
|
+
if (memo === "pass") {
|
|
1597
|
+
await this.end(live, "ok", { v: 1, verdict: "pass", components: [], failingFiles: [], flakyIds: [], note: null, error: null, output: "" }, false);
|
|
1598
|
+
return "pass";
|
|
1599
|
+
}
|
|
1600
|
+
return "fail";
|
|
1601
|
+
}
|
|
1602
|
+
const slotId = live.entry.slot;
|
|
1603
|
+
if (slotId === null) throw new ExecutorError("E_INVALID_INPUT", "entry has no slot", { entry: live.entry.id });
|
|
1604
|
+
const lease = await this.slotLease(slotId, live.entry.id);
|
|
1605
|
+
let n = 0;
|
|
1606
|
+
for (;;) {
|
|
1607
|
+
await this.start(live, step, { v: 1, base: head, candidate, tasks }, { candidate });
|
|
1608
|
+
await this.assertLock(live); // QA-3.2-28: the checks prepare (reset + clean) the slot first
|
|
1609
|
+
const observation = this.service(live, "checks", candidate);
|
|
1610
|
+
const reuseCheckout = (step === "checks" || step === "batch-checks") && checkout?.slot === lease.slot && checkout.head === candidate;
|
|
1611
|
+
checkout = null;
|
|
1612
|
+
const r = await this.d.checks.run({ slot: lease, base: head, candidate, priority: "foreground", extra: null, signal: this.ctl.signal,
|
|
1613
|
+
...(reuseCheckout ? { reuseCheckout: true } : {}),
|
|
1614
|
+
...(observation === undefined ? {} : { observation }) });
|
|
1615
|
+
// QA-3.2-13: once the outer signal fired the run is interrupted whatever it returned: no failed/onFailed during abort.
|
|
1616
|
+
if (this.ctl.signal.aborted) throw new LaneStop("checks interrupted");
|
|
1617
|
+
const scope = r.components.find(c => c.name === "tests")?.scope ?? "full";
|
|
1618
|
+
this.counters.push(counterEvent("integration.checks", r.durationMs, { verdict: r.verdict, scope }));
|
|
1619
|
+
if (r.verdict !== "error" && r.flakyIds.length > 0) this.counters.push(counterEvent("integration.flaky", r.flakyIds.length, { where: "checks" }));
|
|
1620
|
+
if (r.verdict === "pass") {
|
|
1621
|
+
if (r.note === "no-checks") this.counters.push(counterEvent("integration.checks.none", 1, {}));
|
|
1622
|
+
this.passed.add(candidate);
|
|
1623
|
+
this.verdicts.set(candidate, "pass");
|
|
1624
|
+
await this.end(live, "ok", checkDetail(r), false);
|
|
1625
|
+
return "pass";
|
|
1626
|
+
}
|
|
1627
|
+
if (r.verdict === "fail") {
|
|
1628
|
+
this.verdicts.set(candidate, "fail");
|
|
1629
|
+
this.lastFail.set(candidate, { ids: [...r.failingIds], detail: checkDetail(r) });
|
|
1630
|
+
return "fail";
|
|
1631
|
+
}
|
|
1632
|
+
if (r.reason === "interrupted" || this.ctl.signal.aborted) throw new LaneStop("checks interrupted");
|
|
1633
|
+
if (r.reason !== "preempted") n++;
|
|
1634
|
+
else this.counters.push(counterEvent("integration.preempt", 1, {}));
|
|
1635
|
+
await this.end(live, "refused", { v: 1, reason: r.reason, n, message: clipText(r.message, 1000) }, false);
|
|
1636
|
+
if (n >= CHECK_TRIES) await this.infraPause(live, `Integration checks of ${tasks.join(", ")} at ${candidate} could not run ${n} times (${r.reason}: ${clipText(r.message, 500)}).`);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
/** M13a exhaustion: [status-changed running->paused "integration-infrastructure" (only if running), IA(failure, critical)]; the entry stays open (M36). */
|
|
1641
|
+
private async infraPause(live: LiveEntry, text: string): Promise<never> {
|
|
1642
|
+
const now = this.d.clock.iso();
|
|
1643
|
+
const before = this.ledger.inbox.length;
|
|
1644
|
+
const next = await this.append(l => [...this.pauseEvents(l, "integration-infrastructure"),
|
|
1645
|
+
this.inboxEvent(l, "failure", "critical", null, `${text} The plan is paused; unpause to retry.`, now)]);
|
|
1646
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
1647
|
+
this.markStalled(live);
|
|
1648
|
+
await this.releaseForPause(live);
|
|
1649
|
+
throw new LaneStop("integration-infrastructure");
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/** M18 halving. pre: S on the current head, S's tip observed (or memoized) failing; its check step may still be open. */
|
|
1653
|
+
private async halve(live: LiveEntry, S: readonly RangeDetail[]): Promise<void> {
|
|
1654
|
+
const only = S[0];
|
|
1655
|
+
if (S.length === 1 && only !== undefined) {
|
|
1656
|
+
await this.culprit(live, only);
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
const tip = S[S.length - 1];
|
|
1660
|
+
if (live.open !== null && tip !== undefined) {
|
|
1661
|
+
const f = this.lastFail.get(tip.to);
|
|
1662
|
+
await this.end(live, "failed", f?.detail ?? { v: 1, reason: "memo" }, false, f?.ids ?? []);
|
|
1663
|
+
}
|
|
1664
|
+
const k = Math.ceil(S.length / 2);
|
|
1665
|
+
const L = S.slice(0, k);
|
|
1666
|
+
const R = S.slice(k);
|
|
1667
|
+
if (await this.check(live, "bisect", L) === "pass") {
|
|
1668
|
+
await this.integrate(live, L);
|
|
1669
|
+
await this.halve(live, R);
|
|
1670
|
+
} else {
|
|
1671
|
+
await this.halve(live, L);
|
|
1672
|
+
await this.integrateStack(live, R.map(r => r.taskId), null);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
/** Row 32: the task whose commit at exactly head + ... + task failed. */
|
|
1677
|
+
private async culprit(live: LiveEntry, r: RangeDetail): Promise<void> {
|
|
1678
|
+
const head = this.ledger.integration.head;
|
|
1679
|
+
if (live.open === null) {
|
|
1680
|
+
await this.start(live, "bisect", { v: 1, base: head, candidate: r.to, tasks: [r.taskId], probe: "memo" }, { candidate: r.to });
|
|
1681
|
+
}
|
|
1682
|
+
const f = this.lastFail.get(r.to);
|
|
1683
|
+
const detail: CheckDetail = f?.detail ?? { v: 1, verdict: "fail", components: [], failingFiles: [], flakyIds: [], note: null, error: null, output: "" };
|
|
1684
|
+
const ids = f?.ids ?? [];
|
|
1685
|
+
const text = [`Integration checks failed for ${r.taskId} at ${r.to} (on integration head ${head}).`,
|
|
1686
|
+
ids.length > 0 ? `Failing: ${ids.slice(0, 50).join(", ")}` : "",
|
|
1687
|
+
detail.failingFiles.length > 0 ? `Files: ${detail.failingFiles.slice(0, 50).join(", ")}` : "",
|
|
1688
|
+
detail.output !== "" ? `Output (tail):\n${tailBytes(detail.output, 2000)}` : ""].filter(s => s !== "").join("\n");
|
|
1689
|
+
// Row 32 order (phase-1.4.md:943): ISE, AX, TT.
|
|
1690
|
+
await this.endDecide(live, "failed", detail, [r.taskId], ids,
|
|
1691
|
+
l => [...this.ax(l, r.taskId, text), ...this.tt(l, r.taskId, "failed", "checks-failed")]);
|
|
1692
|
+
if (!this.disposed) this.safe(() => this.d.listener.onFailed(r.taskId));
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
/** Fast-forwards to the checked tip of S (I1), then the row-30 batch and the M35 releases. */
|
|
1696
|
+
private async integrate(live: LiveEntry, S: readonly RangeDetail[]): Promise<void> {
|
|
1697
|
+
const tip = S[S.length - 1];
|
|
1698
|
+
if (tip === undefined) return;
|
|
1699
|
+
const head = this.ledger.integration.head;
|
|
1700
|
+
await this.fastForward(live, "fast-forward", tip.to, { v: 1, from: head, to: tip.to, ranges: rangesOf(S) }, []);
|
|
1701
|
+
await this.completeIntegrated(live, head, tip.to, S);
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/** Row 30: [ISE(fast-forward ok), IH, per task task-integrated + TT integrating->integrated + TS(null)], then releases. */
|
|
1705
|
+
private async completeIntegrated(live: LiveEntry, from: string, to: string, S: readonly RangeDetail[]): Promise<void> {
|
|
1706
|
+
const ids = S.map(r => r.taskId);
|
|
1707
|
+
const slots = new Map<TaskId, string | null>(ids.map(id => [id, this.ledger.tasks[id]?.slot ?? null]));
|
|
1708
|
+
const phases = new Set<PhaseId>();
|
|
1709
|
+
await this.endDecide(live, "ok", { v: 1, from, to }, ids, [], l => {
|
|
1710
|
+
const out: ExecutorEventInput[] = [{ type: "integration-head", head: to }];
|
|
1711
|
+
for (const r of S) {
|
|
1712
|
+
const t = l.tasks[r.taskId];
|
|
1713
|
+
if (t === undefined || t.state !== "integrating") continue;
|
|
1714
|
+
if (t.phase !== null) phases.add(t.phase);
|
|
1715
|
+
out.push({ type: "task-integrated", taskId: r.taskId, from: r.from, to: r.to });
|
|
1716
|
+
out.push(...this.tt(l, r.taskId, "integrated", "fast-forwarded"));
|
|
1717
|
+
out.push({ type: "task-slot", taskId: r.taskId, slot: null, branch: t.branch });
|
|
1718
|
+
}
|
|
1719
|
+
return out;
|
|
1720
|
+
});
|
|
1721
|
+
if (this.disposed) return;
|
|
1722
|
+
for (const id of ids) {
|
|
1723
|
+
const slot = slots.get(id) ?? null;
|
|
1724
|
+
if (slot !== null) await this.d.pool.release(slot).catch((e: unknown) => this.d.logger.warn(`integration queue: slot release failed: ${message(e)}`));
|
|
1725
|
+
this.d.leases.releaseTask(id);
|
|
1726
|
+
this.safe(() => this.d.listener.onIntegrated(id));
|
|
1727
|
+
}
|
|
1728
|
+
for (const p of phases) await this.checkPhaseSafe(p);
|
|
1729
|
+
// QA-3.2-31: a phase with no task of its own integrates when the phases it depends on do: wake those dependents.
|
|
1730
|
+
for (const q of dependentPhases(this.ledger, phases)) await this.checkPhaseSafe(q);
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
/**
|
|
1734
|
+
* M6 / I1: the only code that moves the integration branch. ISS(step, candidate) -> branch at head? -> integration worktree at
|
|
1735
|
+
* head -> merge --ff-only -> CAS. The caller writes the closing batch.
|
|
1736
|
+
*/
|
|
1737
|
+
private async fastForward(live: LiveEntry, step: "fast-forward" | "revert-fast-forward", candidate: string, detail: StepDetail,
|
|
1738
|
+
failingIds: readonly string[]): Promise<void> {
|
|
1739
|
+
if (!this.passed.has(candidate)) {
|
|
1740
|
+
throw new ExecutorError("E_INVALID_INPUT", "I1: refusing to fast-forward to a commit whose checks did not pass in this entry",
|
|
1741
|
+
{ entry: live.entry.id, candidate });
|
|
1742
|
+
}
|
|
1743
|
+
const l = this.ledger;
|
|
1744
|
+
const head = l.integration.head;
|
|
1745
|
+
const wt = l.integration.worktree;
|
|
1746
|
+
await this.start(live, step, detail, { candidate }, failingIds);
|
|
1747
|
+
let tip: string | null;
|
|
1748
|
+
try {
|
|
1749
|
+
tip = await this.branchTip();
|
|
1750
|
+
} catch (e) {
|
|
1751
|
+
// QA-3.2-9: git could not run; infrastructure (M13a), never "moved".
|
|
1752
|
+
await this.end(live, "refused", { v: 1, reason: "git", message: clipText(message(e), 1000) }, false);
|
|
1753
|
+
return this.infraPause(live, `The integration branch ${l.integration.branch} could not be read before the fast-forward (${clipText(message(e), 500)}).`);
|
|
1754
|
+
}
|
|
1755
|
+
if (tip !== head) {
|
|
1756
|
+
await this.halt(live, "integration-branch-moved", tip === null
|
|
1757
|
+
? `The integration branch ref refs/heads/${l.integration.branch} does not exist (journaled head ${head}). The plan is paused.`
|
|
1758
|
+
: `The integration branch ${l.integration.branch} is at ${tip}, not at the journaled head ${head}. The plan is paused.`);
|
|
1759
|
+
}
|
|
1760
|
+
const observation = this.service(live, "fast-forward", candidate);
|
|
1761
|
+
const preparation = observation?.start("service-prep", "integration-checkout");
|
|
1762
|
+
try {
|
|
1763
|
+
const lease = await this.integrationSlot();
|
|
1764
|
+
await this.guardWrite(live, wt, "integration");
|
|
1765
|
+
let at: string | null = null;
|
|
1766
|
+
try {
|
|
1767
|
+
at = await this.d.git.revParse(wt, "HEAD");
|
|
1768
|
+
} catch {
|
|
1769
|
+
at = null;
|
|
1770
|
+
}
|
|
1771
|
+
const dirty = at === head ? (await this.d.git.statusPorcelain(wt)).length > 0 : true;
|
|
1772
|
+
if (at !== head || dirty) await this.d.pool.reset(lease.slot, head);
|
|
1773
|
+
preparation?.end("completed");
|
|
1774
|
+
} finally { preparation?.end("error"); }
|
|
1775
|
+
// QA-3.2-36: abort() fired: no merge and no CAS; the step stays open and abort() rolls the entry back.
|
|
1776
|
+
if (this.ctl.signal.aborted) throw new LaneStop("aborted before the merge");
|
|
1777
|
+
const merged = await (observation === undefined ? this.d.git.mergeFfOnly(wt, candidate)
|
|
1778
|
+
: this.d.git.mergeFfOnly(wt, candidate, observation));
|
|
1779
|
+
if (!merged.ok || merged.head !== candidate) {
|
|
1780
|
+
await this.halt(live, "ff-refused",
|
|
1781
|
+
`git merge --ff-only ${candidate} was refused in the integration worktree (head ${head}). The plan is paused; resume() rolls the entry back.`);
|
|
1782
|
+
}
|
|
1783
|
+
if (this.ctl.signal.aborted) throw new LaneStop("aborted before the CAS");
|
|
1784
|
+
// QA-3.2-28: the lock file is re-read (token compare) right before the CAS, not only the last heartbeat's verdict.
|
|
1785
|
+
const lockCheck = observation?.start("service-prep", "lock-validation");
|
|
1786
|
+
try {
|
|
1787
|
+
await this.assertLock(live, true);
|
|
1788
|
+
lockCheck?.end("completed");
|
|
1789
|
+
} finally { lockCheck?.end("error"); }
|
|
1790
|
+
try {
|
|
1791
|
+
await (observation === undefined ? this.d.git.branchForce(l.integration.branch, candidate, head)
|
|
1792
|
+
: this.d.git.branchForce(l.integration.branch, candidate, head, observation));
|
|
1793
|
+
} catch (e) {
|
|
1794
|
+
await this.halt(live, "integration-branch-moved",
|
|
1795
|
+
`The compare-and-swap of ${l.integration.branch} from ${head} to ${candidate} failed (${clipText(message(e), 300)}). The plan is paused.`);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1800
|
+
// IntegrationQueue API
|
|
1801
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1802
|
+
|
|
1803
|
+
enqueue(taskIds: readonly TaskId[]): void {
|
|
1804
|
+
if (this.disposed) throw new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId });
|
|
1805
|
+
if (this.aborting) throw new ExecutorError("E_PLAN_STATE", "the plan is aborting", { planId: this.d.planId });
|
|
1806
|
+
const l = this.ledger;
|
|
1807
|
+
if (l.status !== "running" && l.status !== "paused") {
|
|
1808
|
+
throw new ExecutorError("E_PLAN_STATE", "enqueue needs a running or paused plan", { planId: this.d.planId, status: l.status });
|
|
1809
|
+
}
|
|
1810
|
+
for (const id of taskIds) {
|
|
1811
|
+
if (this.fifo.includes(id) || this.requeued.some(g => g.taskIds.includes(id))) continue;
|
|
1812
|
+
if (this.serial?.entry.taskIds.includes(id) === true) continue;
|
|
1813
|
+
const t = l.tasks[id];
|
|
1814
|
+
if (t === undefined || t.state !== "verified" || t.slot === null || t.branch === null) {
|
|
1815
|
+
this.d.logger.warn(`integration queue: ignoring enqueue of ${id} (state ${t?.state ?? "unknown"})`);
|
|
1816
|
+
continue;
|
|
1817
|
+
}
|
|
1818
|
+
this.fifo.push(id);
|
|
1819
|
+
const wait = this.pendingService(l, [id], t.phase, "rebase")?.start("service-wait", "integration-queue");
|
|
1820
|
+
if (wait !== undefined) this.taskWaits.set(id, wait);
|
|
1821
|
+
}
|
|
1822
|
+
void this.pokeStalled();
|
|
1823
|
+
this.kick();
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
queued(): readonly TaskId[] {
|
|
1827
|
+
if (this.disposed) return [];
|
|
1828
|
+
return [...this.requeued.flatMap(g => g.taskIds), ...this.fifo];
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
async checkPhase(p: PhaseId): Promise<void> {
|
|
1832
|
+
if (this.disposed) throw new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId });
|
|
1833
|
+
if (this.aborting) return;
|
|
1834
|
+
void this.pokeStalled();
|
|
1835
|
+
const l = this.ledger;
|
|
1836
|
+
const ph = l.phases.find(x => x.id === p);
|
|
1837
|
+
if (ph === undefined || ph.paused) return;
|
|
1838
|
+
const open = this.d.writer.openIntegration().filter(o => o.entry.phaseId === p);
|
|
1839
|
+
if (l.status !== "running") {
|
|
1840
|
+
// QA-3.2-15: the last phase can pass after the plan completed; its tag entry still runs (serial lane, tags only).
|
|
1841
|
+
if (l.status === "completed" && ph.gate === "passed" && ph.tag === null && !open.some(o => o.entry.kind === "tag") && !this.tags.includes(p)) {
|
|
1842
|
+
this.tags.push(p);
|
|
1843
|
+
this.kick();
|
|
1844
|
+
}
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const head = l.integration.head;
|
|
1848
|
+
if (ph.gate === "pending") {
|
|
1849
|
+
if (!phaseIntegrated(l, p) || this.suites.some(s => s.phaseId === p) || this.background?.entry.phaseId === p) return;
|
|
1850
|
+
// QA-3.2-19: a phase with no task of its own (qa only) has nothing for a suite to attribute: it skips the suite.
|
|
1851
|
+
const res: SuiteResolution = phaseHasOwnTasks(l, p) ? await this.d.suite.resolve(l, p, head) : { kind: "none" };
|
|
1852
|
+
if (res.kind === "runs") {
|
|
1853
|
+
this.suites.push({ phaseId: p, gate: "start" });
|
|
1854
|
+
this.suiteWaiting(l, p);
|
|
1855
|
+
this.kick();
|
|
1856
|
+
return;
|
|
1857
|
+
}
|
|
1858
|
+
if (res.kind === "refused") {
|
|
1859
|
+
await this.suiteRefused(p, res.reason);
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
// Only the call whose batch opened the gate notifies: a concurrent checkPhase finds the gate already open (empty batch).
|
|
1863
|
+
let opened = false;
|
|
1864
|
+
const next = await this.append(lg => {
|
|
1865
|
+
const cur = lg.phases.find(x => x.id === p);
|
|
1866
|
+
opened = cur !== undefined && cur.gate === "pending";
|
|
1867
|
+
if (cur === undefined || !opened) return [];
|
|
1868
|
+
return [{ type: "gate-changed", phaseId: p, from: "pending", to: "awaiting-qa", trigger: "phase-integrated", qaRound: cur.qaRound },
|
|
1869
|
+
counterEvent("integration.suite", 0, { verdict: res.kind })];
|
|
1870
|
+
});
|
|
1871
|
+
if (opened && next.phases.find(x => x.id === p)?.gate === "awaiting-qa" && !this.disposed) this.safe(() => this.d.listener.onGate(p, "awaiting-qa"));
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
if (ph.gate === "suite-running") {
|
|
1875
|
+
if (open.some(o => o.entry.kind === "phase-suite") || this.background?.entry.phaseId === p || this.suites.some(s => s.phaseId === p)) return;
|
|
1876
|
+
this.suites.push({ phaseId: p, gate: "none" });
|
|
1877
|
+
this.suiteWaiting(l, p);
|
|
1878
|
+
this.kick();
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
if (ph.gate === "suite-failed") {
|
|
1882
|
+
if (open.length > 0 || this.reverts.some(r => r.phaseId === p) || this.suites.some(s => s.phaseId === p)) return;
|
|
1883
|
+
const pending = await this.revertFromHistory(p);
|
|
1884
|
+
if (pending !== null) this.reverts.unshift(pending);
|
|
1885
|
+
else {
|
|
1886
|
+
this.suites.push({ phaseId: p, gate: "rerun" });
|
|
1887
|
+
this.suiteWaiting(l, p);
|
|
1888
|
+
}
|
|
1889
|
+
this.kick();
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
if (ph.gate === "passed" && ph.tag === null) {
|
|
1893
|
+
if (open.some(o => o.entry.kind === "tag") || this.tags.includes(p)) return;
|
|
1894
|
+
this.tags.push(p);
|
|
1895
|
+
this.kick();
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
land(): Promise<{ landed: boolean; inbox: InboxItem | null }> {
|
|
1900
|
+
if (this.disposed) return Promise.reject(new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId }));
|
|
1901
|
+
if (this.landing !== null) return this.landing;
|
|
1902
|
+
const p = this.doLand().finally(() => { this.landing = null; });
|
|
1903
|
+
this.landing = p;
|
|
1904
|
+
return p;
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
resume(): Promise<ResumeReport> {
|
|
1908
|
+
if (this.disposed) return Promise.reject(new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId }));
|
|
1909
|
+
if (this.resumed && this.report !== null) return Promise.resolve(this.report);
|
|
1910
|
+
if (this.resuming !== null) return this.resuming;
|
|
1911
|
+
const p = this.doResume().finally(() => { this.resuming = null; });
|
|
1912
|
+
this.resuming = p;
|
|
1913
|
+
return p;
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
abort(): Promise<void> {
|
|
1917
|
+
if (this.disposed) return Promise.reject(new ExecutorError("E_DISPOSED", "integration queue disposed", { planId: this.d.planId }));
|
|
1918
|
+
if (this.aborted === null) this.aborted = this.doAbort();
|
|
1919
|
+
return this.aborted;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
async dispose(): Promise<void> {
|
|
1923
|
+
if (this.disposed) return;
|
|
1924
|
+
this.disposed = true;
|
|
1925
|
+
this.endWaiting("disposed");
|
|
1926
|
+
// The reason lets the suite runner report `interrupted by dispose` (not abort).
|
|
1927
|
+
this.ctl.abort("dispose");
|
|
1928
|
+
this.bgCtl.abort("dispose");
|
|
1929
|
+
this.lockCtl.abort("dispose");
|
|
1930
|
+
this.clearStalled();
|
|
1931
|
+
await new Promise<void>(resolve => {
|
|
1932
|
+
const h = this.d.clock.setTimer(30_000, resolve);
|
|
1933
|
+
void this.idle().then(() => { this.d.clock.clearTimer(h); resolve(); });
|
|
1934
|
+
});
|
|
1935
|
+
await this.releaseLock();
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
private landing: Promise<{ landed: boolean; inbox: InboxItem | null }> | null = null;
|
|
1939
|
+
private aborted: Promise<void> | null = null;
|
|
1940
|
+
private report: ResumeReport | null = null;
|
|
1941
|
+
private inResume = false;
|
|
1942
|
+
private serialTail: Promise<void> = Promise.resolve();
|
|
1943
|
+
private serialLoopP: Promise<void> = Promise.resolve();
|
|
1944
|
+
private backgroundLoopP: Promise<void> = Promise.resolve();
|
|
1945
|
+
|
|
1946
|
+
private async withSerial<T>(fn: () => Promise<T>): Promise<T> {
|
|
1947
|
+
const prev = this.serialTail;
|
|
1948
|
+
let free!: () => void;
|
|
1949
|
+
this.serialTail = new Promise<void>(resolve => { free = resolve; });
|
|
1950
|
+
await prev;
|
|
1951
|
+
try {
|
|
1952
|
+
return await fn();
|
|
1953
|
+
} finally {
|
|
1954
|
+
free();
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
private async idle(): Promise<void> {
|
|
1959
|
+
await Promise.allSettled([this.serialLoopP, this.backgroundLoopP, this.serialTail]);
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1963
|
+
// Lanes (M4)
|
|
1964
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
1965
|
+
|
|
1966
|
+
/**
|
|
1967
|
+
* Starts each lane loop that is not running. A kick that finds a loop running sets that lane's `wanted` flag, which the
|
|
1968
|
+
* loop's `.finally` re-checks: a loop that already decided it had nothing to do (pickSerial null, no suite) but has not
|
|
1969
|
+
* cleared its running flag yet would otherwise swallow the kick, and the work queued with it would wait for the next one.
|
|
1970
|
+
*/
|
|
1971
|
+
private kick(): void {
|
|
1972
|
+
if (this.disposed || this.stopped || this.aborting || !this.resumed) return;
|
|
1973
|
+
this.kickSerial();
|
|
1974
|
+
this.kickBackground();
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
/**
|
|
1978
|
+
* Each lane's `.finally` re-kicks only its own lane. A lane-agnostic re-kick let two idle lanes keep setting each other's
|
|
1979
|
+
* `wanted` flag (each loop ends within a few microtasks, while the other is still "running"), an endless microtask
|
|
1980
|
+
* ping-pong that starved timers and I/O whenever no work was dequeueable (e.g. only paused-phase tasks queued).
|
|
1981
|
+
*/
|
|
1982
|
+
private kickSerial(): void {
|
|
1983
|
+
if (this.disposed || this.stopped || this.aborting || !this.resumed) return;
|
|
1984
|
+
if (this.serialRunning) {
|
|
1985
|
+
this.serialWanted = true;
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
this.serialRunning = true;
|
|
1989
|
+
this.serialWanted = false;
|
|
1990
|
+
this.serialLoopP = this.serialLoop().finally(() => {
|
|
1991
|
+
this.serialRunning = false;
|
|
1992
|
+
if (this.serialWanted) {
|
|
1993
|
+
this.serialWanted = false;
|
|
1994
|
+
this.kickSerial();
|
|
1995
|
+
}
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
private kickBackground(): void {
|
|
2000
|
+
if (this.disposed || this.stopped || this.aborting || !this.resumed) return;
|
|
2001
|
+
if (this.backgroundRunning) {
|
|
2002
|
+
this.backgroundWanted = true;
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
this.backgroundRunning = true;
|
|
2006
|
+
this.backgroundWanted = false;
|
|
2007
|
+
this.backgroundLoopP = this.backgroundLoop().finally(() => {
|
|
2008
|
+
this.backgroundRunning = false;
|
|
2009
|
+
if (this.backgroundWanted) {
|
|
2010
|
+
this.backgroundWanted = false;
|
|
2011
|
+
this.kickBackground();
|
|
2012
|
+
}
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
private serialWanted = false;
|
|
2017
|
+
private backgroundWanted = false;
|
|
2018
|
+
|
|
2019
|
+
/** Lanes run while running; the serial lane also runs tag entries of a completed plan (QA-3.2-15). */
|
|
2020
|
+
private laneOpen(serial = false): boolean {
|
|
2021
|
+
const status = this.ledger.status;
|
|
2022
|
+
return this.resumed && !this.disposed && !this.stopped && !this.aborting
|
|
2023
|
+
&& (status === "running" || (serial && status === "completed" && this.tags.length > 0));
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
private async serialLoop(): Promise<void> {
|
|
2027
|
+
while (this.laneOpen(true) && this.stalled.size === 0) {
|
|
2028
|
+
const job = this.pickSerial(this.ledger);
|
|
2029
|
+
if (job === null) return;
|
|
2030
|
+
const ok = await this.withSerial(async () => {
|
|
2031
|
+
try {
|
|
2032
|
+
await job();
|
|
2033
|
+
return true;
|
|
2034
|
+
} catch (e) {
|
|
2035
|
+
this.laneError(e);
|
|
2036
|
+
if (!(e instanceof LaneStop)) await this.unexpected(this.serial, e);
|
|
2037
|
+
return false;
|
|
2038
|
+
}
|
|
2039
|
+
});
|
|
2040
|
+
if (!ok) return;
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
private async backgroundLoop(): Promise<void> {
|
|
2045
|
+
while (this.laneOpen()) {
|
|
2046
|
+
const job = this.suites.shift();
|
|
2047
|
+
if (job === undefined) return;
|
|
2048
|
+
try {
|
|
2049
|
+
await this.runSuite(job.phaseId, job.gate);
|
|
2050
|
+
} catch (e) {
|
|
2051
|
+
this.laneError(e);
|
|
2052
|
+
if (!(e instanceof LaneStop)) await this.unexpected(this.background, e);
|
|
2053
|
+
return;
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
/** An unexpected throw with an entry open: pause through M13a so resume (or the stalled path) rolls it back. */
|
|
2059
|
+
private async unexpected(live: LiveEntry | null, e: unknown): Promise<void> {
|
|
2060
|
+
if (live === null || this.disposed || this.stopped || this.aborting || this.stalled.get(live.lane) === live) return;
|
|
2061
|
+
if (errCode(e) === "E_DISPOSED" || errCode(e) === "E_LOCK_LOST") return;
|
|
2062
|
+
try {
|
|
2063
|
+
if (live.open !== null) await this.end(live, "refused", refusedError(e), false);
|
|
2064
|
+
await this.infraPause(live, `Integration entry ${live.entry.id} (${live.entry.kind}) stopped: ${clipText(stripUrlUserinfo(message(e)), 500)}.`);
|
|
2065
|
+
} catch (inner) {
|
|
2066
|
+
this.laneError(inner);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
/** M4 pick order: resume reruns, pending reverts, tags, task FIFO (batched). Land is driven by land(). */
|
|
2071
|
+
private pickSerial(l: Readonly<LedgerV1>): (() => Promise<void>) | null {
|
|
2072
|
+
if (l.status !== "running") {
|
|
2073
|
+
const tag = this.tags.shift();
|
|
2074
|
+
return tag === undefined ? null : () => this.runTag(tag);
|
|
2075
|
+
}
|
|
2076
|
+
for (let i = 0; i < this.requeued.length; i++) {
|
|
2077
|
+
const g = this.requeued[i];
|
|
2078
|
+
if (g === undefined) continue;
|
|
2079
|
+
const ids = g.taskIds.filter(id => l.tasks[id]?.state === "integrating");
|
|
2080
|
+
if (ids.length === 0) {
|
|
2081
|
+
this.requeued.splice(i, 1);
|
|
2082
|
+
i--;
|
|
2083
|
+
continue;
|
|
2084
|
+
}
|
|
2085
|
+
if (phasePaused(l, g.phaseId)) continue;
|
|
2086
|
+
this.requeued.splice(i, 1);
|
|
2087
|
+
return () => this.runTaskEntry(ids, true);
|
|
2088
|
+
}
|
|
2089
|
+
const rerunAt = this.reverts.findIndex(r => r.rerun !== null);
|
|
2090
|
+
const revertAt = rerunAt >= 0 ? rerunAt : this.reverts.length > 0 ? 0 : -1;
|
|
2091
|
+
if (revertAt >= 0) {
|
|
2092
|
+
const rv = this.reverts.splice(revertAt, 1)[0];
|
|
2093
|
+
if (rv !== undefined) return () => this.runRevert(rv);
|
|
2094
|
+
}
|
|
2095
|
+
const tag = this.tags.shift();
|
|
2096
|
+
if (tag !== undefined) return () => this.runTag(tag);
|
|
2097
|
+
const batch = pickBatch(l, this.fifo, l.config.batchMax);
|
|
2098
|
+
if (batch.length > 0) return () => this.runTaskEntry(batch, false);
|
|
2099
|
+
return null;
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2103
|
+
// 4.3 / 4.4 phase suite (background lane)
|
|
2104
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2105
|
+
|
|
2106
|
+
private gateEvent(l: Readonly<LedgerV1>, p: PhaseId, from: GateState, to: GateState, trigger: GateTrigger): ExecutorEventInput[] {
|
|
2107
|
+
const ph = l.phases.find(x => x.id === p);
|
|
2108
|
+
if (ph === undefined || ph.gate !== from) return [];
|
|
2109
|
+
return [{ type: "gate-changed", phaseId: p, from, to, trigger, qaRound: ph.qaRound }];
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
private async suiteRefused(p: PhaseId, reason: string): Promise<void> {
|
|
2113
|
+
const now = this.d.clock.iso();
|
|
2114
|
+
const before = this.ledger.inbox.length;
|
|
2115
|
+
const next = await this.append(l => [{ type: "phase-paused", phaseId: p, paused: true, reason: "suite-unresolvable" },
|
|
2116
|
+
this.inboxEvent(l, "failure", "critical", null, `The phase suite of ${p} cannot be resolved: ${reason}. Phase ${p} is paused.`, now)]);
|
|
2117
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
private phaseRanges(l: Readonly<LedgerV1>, p: PhaseId): TaskRange[] {
|
|
2121
|
+
const out: TaskRange[] = [];
|
|
2122
|
+
for (const t of Object.values(l.tasks)) {
|
|
2123
|
+
if (t.phase === p && t.state === "integrated" && t.integrated !== null) out.push({ taskId: t.id, from: t.integrated.from, to: t.integrated.to });
|
|
2124
|
+
}
|
|
2125
|
+
return out;
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
private async runSuite(p: PhaseId, gate: "start" | "rerun" | "none"): Promise<void> {
|
|
2129
|
+
this.suiteWaits.get(p)?.end("dequeued");
|
|
2130
|
+
this.suiteWaits.delete(p);
|
|
2131
|
+
const l = this.ledger;
|
|
2132
|
+
const ph = l.phases.find(x => x.id === p);
|
|
2133
|
+
if (ph === undefined || ph.paused) return;
|
|
2134
|
+
if (gate === "start" && ph.gate !== "pending") return;
|
|
2135
|
+
if (gate === "rerun" && ph.gate !== "suite-failed") return;
|
|
2136
|
+
if (gate === "none" && ph.gate !== "suite-running") return;
|
|
2137
|
+
const head = l.integration.head;
|
|
2138
|
+
const res: SuiteResolution = gate === "start" && !phaseHasOwnTasks(l, p) ? { kind: "none" } : await this.d.suite.resolve(l, p, head);
|
|
2139
|
+
if (res.kind === "refused") {
|
|
2140
|
+
await this.suiteRefused(p, res.reason);
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
if (res.kind !== "runs" && gate !== "start") {
|
|
2144
|
+
// QA-3.2-2: a suite state (suite-running with no entry, or suite-failed on a rerun) is never left without a run:
|
|
2145
|
+
// no gate event; the phase pauses with a critical item (M21 "never skipped silently", A2-1 "never stuck silently").
|
|
2146
|
+
// Nit A-3.2-1: `off` comes from the plan's approved `phaseSuite` setting, not from missing tests.
|
|
2147
|
+
const remedy = res.kind === "off"
|
|
2148
|
+
? "The plan's approved phaseSuite setting is \"off\": set phaseSuite (re-approve the plan's config) or move the gate on by hand"
|
|
2149
|
+
: "Restore the phase's tests";
|
|
2150
|
+
await this.suiteRefused(p, `the suite resolves to "${res.kind}" at head ${head} while the gate is ${ph.gate}, so it cannot run and the gate stays ${ph.gate}. ${remedy}, then unpause phase ${p} to run the suite`);
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
if (res.kind !== "runs") {
|
|
2154
|
+
// Off or no tests at this commit: the gate leaves pending without a run (M21).
|
|
2155
|
+
const next = await this.append(lg => [
|
|
2156
|
+
...(gate === "start" ? this.gateEvent(lg, p, "pending", "awaiting-qa", "phase-integrated") : []),
|
|
2157
|
+
counterEvent("integration.suite", 0, { verdict: res.kind })]);
|
|
2158
|
+
if (next.phases.find(x => x.id === p)?.gate === "awaiting-qa" && !this.disposed) this.safe(() => this.d.listener.onGate(p, "awaiting-qa"));
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
const base = phaseBase(await this.loadSteps(), p);
|
|
2162
|
+
const live = await this.openEntry("background",
|
|
2163
|
+
{ kind: "phase-suite", phaseId: p, taskIds: [], slot: "ci", baseHead: head, candidate: head }, "phase-suite",
|
|
2164
|
+
{ v: 1, commit: head, base, commands: res.commands.map(c => ({ label: c.label, ref: c.ref })) },
|
|
2165
|
+
lg => gate === "start" ? this.gateEvent(lg, p, "pending", "suite-running", "phase-integrated")
|
|
2166
|
+
: gate === "rerun" ? this.gateEvent(lg, p, "suite-failed", "suite-running", "suite-rerun") : []);
|
|
2167
|
+
if (gate !== "none" && !this.disposed) this.safe(() => this.d.listener.onGate(p, "suite-running"));
|
|
2168
|
+
const startedAt = this.d.clock.now();
|
|
2169
|
+
const preparation = this.service(live, "phase-suite", head)?.start("service-prep", "ci-slot");
|
|
2170
|
+
let ci: SlotLease;
|
|
2171
|
+
try {
|
|
2172
|
+
ci = await this.d.pool.acquireSpecial(this.d.planId, "ci");
|
|
2173
|
+
preparation?.end("completed");
|
|
2174
|
+
} finally { preparation?.end("error"); }
|
|
2175
|
+
try {
|
|
2176
|
+
const verdict = await this.d.suite.run({ planId: this.d.planId, phaseId: p, commit: head, base,
|
|
2177
|
+
ranges: this.phaseRanges(this.ledger, p), commands: res.commands, slot: ci }, this.journal(live, this.bgCtl.signal));
|
|
2178
|
+
await this.closeSuite(live, p, head, verdict, startedAt, res.commands);
|
|
2179
|
+
} finally {
|
|
2180
|
+
if (!this.disposed && this.background !== live) {
|
|
2181
|
+
await this.d.pool.release(ci.slot).catch((e: unknown) => this.d.logger.warn(`integration queue: ci release failed: ${message(e)}`));
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/** §4.4 step 9 closing batches; the runner leaves its final step open. */
|
|
2187
|
+
private async closeSuite(live: LiveEntry, p: PhaseId, commit: string, v: SuiteVerdict, startedAt: number,
|
|
2188
|
+
commands: readonly ResolvedCommand[]): Promise<void> {
|
|
2189
|
+
if (v.kind === "interrupted") throw new LaneStop(`suite interrupted by ${v.by}`);
|
|
2190
|
+
// QA-3.2-36: abort()/dispose() fired while the run returned: no gate, pause or inbox event; abort() closes the entry.
|
|
2191
|
+
if (this.bgCtl.signal.aborted || this.aborting) throw new LaneStop("suite closed after abort");
|
|
2192
|
+
if (v.kind === "error") {
|
|
2193
|
+
if (live.open !== null) await this.end(live, "refused", { v: 1, reason: v.reason, message: clipText(v.message, 1000) }, false);
|
|
2194
|
+
return this.infraPause(live, `The phase suite of ${p} could not run (${v.reason}: ${clipText(v.message, 500)}).`);
|
|
2195
|
+
}
|
|
2196
|
+
if (live.open === null) await this.start(live, "phase-suite", { v: 1, commit, base: null, commands: commands.map(c => ({ label: c.label, ref: c.ref })) });
|
|
2197
|
+
const ms = this.d.clock.now() - startedAt;
|
|
2198
|
+
const now = this.d.clock.iso();
|
|
2199
|
+
const before = this.ledger.inbox.length;
|
|
2200
|
+
let next: Readonly<LedgerV1>;
|
|
2201
|
+
let gate: GateState | null = null;
|
|
2202
|
+
if (v.kind === "passed") {
|
|
2203
|
+
gate = "awaiting-qa";
|
|
2204
|
+
next = await this.end(live, "ok", { v: 1, files: [], idsUnparsed: false, durationMs: ms, output: "" }, true, [],
|
|
2205
|
+
l => [...this.gateEvent(l, p, "suite-running", "awaiting-qa", "suite-passed"), counterEvent("integration.suite", ms, { verdict: "passed" })]);
|
|
2206
|
+
} else if (v.kind === "flaky" || v.kind === "pre-existing") {
|
|
2207
|
+
gate = "awaiting-qa";
|
|
2208
|
+
const flaky = v.kind === "flaky";
|
|
2209
|
+
next = await this.end(live, flaky ? "flaky" : "pre-existing", { v: 1, durationMs: ms, output: "" }, true, v.ids,
|
|
2210
|
+
l => [...this.gateEvent(l, p, "suite-running", "awaiting-qa", "suite-passed"),
|
|
2211
|
+
this.inboxEvent(l, flaky ? "flaky" : "failure", "info", null, flaky
|
|
2212
|
+
? `Phase ${p} suite at ${commit}: flaky tests passed on rerun: ${v.ids.slice(0, 50).join(", ")}.`
|
|
2213
|
+
: `Phase ${p} suite at ${commit}: failures that already fail at the phase base: ${v.ids.slice(0, 50).join(", ")}.`, now),
|
|
2214
|
+
counterEvent("integration.suite", ms, { verdict: v.kind }),
|
|
2215
|
+
...(flaky ? [counterEvent("integration.flaky", v.ids.length, { where: "suite" })] : [])]);
|
|
2216
|
+
} else if (v.kind === "culprit") {
|
|
2217
|
+
gate = "suite-failed";
|
|
2218
|
+
// QA-3.2-24: the failing files ride in the closing detail, so a revert rebuilt from history (restart) still has them.
|
|
2219
|
+
next = await this.end(live, "failed", { v: 1, verdict: "fail", probes: 0, culprit: { taskId: v.range.taskId, from: v.range.from, to: v.range.to },
|
|
2220
|
+
files: [...v.files] },
|
|
2221
|
+
true, v.ids, l => [...this.gateEvent(l, p, "suite-running", "suite-failed", "suite-culprit-found"),
|
|
2222
|
+
counterEvent("integration.suite", ms, { verdict: "culprit" })]);
|
|
2223
|
+
const resolved = await this.d.suite.resolve(this.ledger, p, commit).catch(() => null);
|
|
2224
|
+
this.reverts.unshift({ phaseId: p, culprit: { ...v.range }, suiteCommit: commit, ids: [...v.ids], files: [...v.files],
|
|
2225
|
+
commands: resolved !== null && resolved.kind === "runs" ? resolved.commands : [...commands], rerun: null });
|
|
2226
|
+
} else {
|
|
2227
|
+
const why = v.reason === "outside" ? "the failure lies outside the phase's task ranges (outside)"
|
|
2228
|
+
: v.reason === "no-base" ? "the phase has no recorded base to compare against (no-base)"
|
|
2229
|
+
: v.reason === "base-overlap" ? "every failing file also fails at the phase base, so the regression cannot be probed apart from the pre-existing failures (base-overlap)"
|
|
2230
|
+
: "the base check's output could not be parsed into test ids, so pre-existing failures cannot be told apart (base-unparsed)";
|
|
2231
|
+
next = await this.end(live, "failed", { v: 1, verdict: "fail", probes: 0, outside: v.reason === "outside" ? "last-passes" : undefined }, true, v.ids,
|
|
2232
|
+
l => [{ type: "phase-paused", phaseId: p, paused: true, reason: "suite-unattributed" },
|
|
2233
|
+
this.inboxEvent(l, "failure", "critical", null,
|
|
2234
|
+
`Phase ${p} suite at ${commit} failed (${v.ids.slice(0, 50).join(", ")}) and the failure is not attributable to a task of the phase: ${why}. Phase ${p} is paused.`, now),
|
|
2235
|
+
counterEvent("integration.suite", ms, { verdict: "unattributed" })]);
|
|
2236
|
+
}
|
|
2237
|
+
if (this.disposed) return;
|
|
2238
|
+
if (gate !== null) {
|
|
2239
|
+
const g = gate;
|
|
2240
|
+
this.safe(() => this.d.listener.onGate(p, g));
|
|
2241
|
+
}
|
|
2242
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2243
|
+
this.kick();
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
/** M25 crash path: the latest closed suite of P named a culprit and no revert entry of P since -> the revert. */
|
|
2247
|
+
private async revertFromHistory(p: PhaseId): Promise<PendingRevert | null> {
|
|
2248
|
+
const steps = await this.loadSteps();
|
|
2249
|
+
let suite: IntegrationStepEvent | null = null;
|
|
2250
|
+
for (const ev of steps) if (ev.entry.kind === "phase-suite" && ev.entry.phaseId === p && ev.closes) suite = ev;
|
|
2251
|
+
if (suite === null) return null;
|
|
2252
|
+
const seq = suite.seq;
|
|
2253
|
+
if (steps.some(ev => ev.entry.kind === "revert" && ev.entry.phaseId === p && ev.seq > seq)) return null;
|
|
2254
|
+
const detail = parseDetail(suite.detail);
|
|
2255
|
+
const c = detail?.culprit as Partial<RangeDetail> | undefined;
|
|
2256
|
+
if (c === undefined || typeof c.taskId !== "string" || typeof c.from !== "string" || typeof c.to !== "string") return null;
|
|
2257
|
+
const commit = suite.entry.candidate ?? suite.entry.baseHead;
|
|
2258
|
+
const resolved = await this.d.suite.resolve(this.ledger, p, commit).catch(() => null);
|
|
2259
|
+
// QA-3.2-24: ids from the closing end's failingIds, files from its detail (written since round 2).
|
|
2260
|
+
const files = detail?.truncated !== true && Array.isArray(detail?.files) ? (detail.files as unknown[]).filter((f): f is string => typeof f === "string") : []; // m1: truncated -> no files, the revert check runs the whole command
|
|
2261
|
+
return { phaseId: p, culprit: { taskId: c.taskId, from: c.from, to: c.to }, suiteCommit: commit, ids: [...suite.failingIds], files,
|
|
2262
|
+
commands: resolved !== null && resolved.kind === "runs" ? resolved.commands : [], rerun: null };
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2266
|
+
// 4.5 revert entry (serial)
|
|
2267
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2268
|
+
|
|
2269
|
+
private async runRevert(rv: PendingRevert): Promise<void> {
|
|
2270
|
+
const l = this.ledger;
|
|
2271
|
+
const culprit = l.tasks[rv.culprit.taskId];
|
|
2272
|
+
if (culprit === undefined || culprit.state !== "integrated") {
|
|
2273
|
+
if (rv.rerun === null) return;
|
|
2274
|
+
}
|
|
2275
|
+
try {
|
|
2276
|
+
await this.takeLock(rv.rerun?.entry.id ?? null, true);
|
|
2277
|
+
} catch (e) {
|
|
2278
|
+
this.reverts.unshift(rv); // taken off by pickSerial: keep it pending
|
|
2279
|
+
throw e;
|
|
2280
|
+
}
|
|
2281
|
+
const head = l.integration.head;
|
|
2282
|
+
const live = rv.rerun ?? await this.openEntry("serial",
|
|
2283
|
+
{ kind: "revert", phaseId: rv.phaseId, taskIds: [rv.culprit.taskId], slot: "integration", baseHead: head, candidate: null },
|
|
2284
|
+
"revert-build", { v: 1, culprit: { ...rv.culprit }, suiteCommit: rv.suiteCommit, head, files: [...rv.files] }, NONE, rv.ids);
|
|
2285
|
+
this.serial = live;
|
|
2286
|
+
const slot = await this.integrationSlot();
|
|
2287
|
+
// M26: built at the current head (a rerun entry may have been journaled before requeued tasks integrated).
|
|
2288
|
+
const buildHead = this.ledger.integration.head;
|
|
2289
|
+
const v = await this.d.suite.revert({ planId: this.d.planId, phaseId: rv.phaseId, culprit: { ...rv.culprit }, suiteCommit: rv.suiteCommit,
|
|
2290
|
+
head: buildHead, regression: { ids: [...rv.ids], files: [...rv.files], commands: [...rv.commands] }, slot },
|
|
2291
|
+
this.journal(live, this.ctl.signal));
|
|
2292
|
+
const now = this.d.clock.iso();
|
|
2293
|
+
const before = this.ledger.inbox.length;
|
|
2294
|
+
const p = rv.phaseId;
|
|
2295
|
+
if (v.kind === "interrupted") throw new LaneStop(`revert interrupted by ${v.by}`);
|
|
2296
|
+
if (v.kind === "error") {
|
|
2297
|
+
if (live.open !== null) await this.end(live, "refused", { v: 1, reason: v.reason, message: clipText(v.message, 1000) }, false);
|
|
2298
|
+
return this.infraPause(live, `The revert of ${rv.culprit.taskId} could not be built or checked (${v.reason}: ${clipText(v.message, 500)}).`);
|
|
2299
|
+
}
|
|
2300
|
+
if (v.kind === "conflict") {
|
|
2301
|
+
// The head the revert was built at (a rerun entry's baseHead can be older), so the commands reproduce this conflict.
|
|
2302
|
+
const commands = [`git -C "${l.integration.worktree}" switch --detach ${buildHead}`,
|
|
2303
|
+
`git -C "${l.integration.worktree}" revert --no-commit ${rv.culprit.to}`];
|
|
2304
|
+
if (live.open === null) await this.start(live, "revert-build", { v: 1, culprit: { ...rv.culprit }, suiteCommit: rv.suiteCommit, head: buildHead, files: [...rv.files] });
|
|
2305
|
+
const next = await this.end(live, "conflict", { v: 1, at: v.at, paths: v.paths.slice(0, 20), commands }, true, [],
|
|
2306
|
+
lg => [{ type: "phase-paused", phaseId: p, paused: true, reason: "revert-conflict" },
|
|
2307
|
+
this.inboxEvent(lg, "failure", "critical", rv.culprit.taskId,
|
|
2308
|
+
`Reverting ${rv.culprit.taskId} (${rv.culprit.from}..${rv.culprit.to}) for the phase ${p} suite failure conflicts at ${v.at} in: ${v.paths.slice(0, 20).join(", ")}. Phase ${p} is paused. Inspect with (never run by the executor):\n${commands.join("\n")}`, now),
|
|
2309
|
+
counterEvent("integration.revert", 1, { outcome: "conflict" })]);
|
|
2310
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
if (v.kind === "failed") {
|
|
2314
|
+
if (live.open === null) await this.start(live, "revert-checks", { v: 1, base: live.entry.baseHead, candidate: live.entry.candidate ?? live.entry.baseHead, extraFiles: [...rv.files] });
|
|
2315
|
+
const next = await this.end(live, "failed", { v: 1, verdict: "fail", components: [], failingFiles: [...v.files], flakyIds: [], note: null, error: null, output: v.output },
|
|
2316
|
+
true, v.ids, lg => [{ type: "phase-paused", phaseId: p, paused: true, reason: "revert-insufficient" },
|
|
2317
|
+
this.inboxEvent(lg, "failure", "critical", rv.culprit.taskId,
|
|
2318
|
+
`Reverting ${rv.culprit.taskId} did not make the integration checks pass (${v.ids.slice(0, 50).join(", ")}). The branch is unchanged; phase ${p} is paused.`, now),
|
|
2319
|
+
counterEvent("integration.revert", 1, { outcome: "insufficient" })]);
|
|
2320
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
// ok: revert-checks passed in the integration slot (I1), then M6 and the row-34 batch.
|
|
2324
|
+
if (live.open !== null) await this.end(live, "ok", { v: 1, base: live.entry.baseHead, candidate: v.revertHead, extraFiles: [...rv.files] }, false);
|
|
2325
|
+
this.passed.add(v.revertHead);
|
|
2326
|
+
const from = this.ledger.integration.head;
|
|
2327
|
+
await this.fastForward(live, "revert-fast-forward", v.revertHead,
|
|
2328
|
+
{ v: 1, from, to: v.revertHead, culprit: { ...rv.culprit }, suiteCommit: rv.suiteCommit }, rv.ids);
|
|
2329
|
+
await this.completeReverted(live, p, v.revertHead, rv.culprit, rv.suiteCommit, rv.ids);
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
/** Row 34 (M27): [ISE(revert-fast-forward ok, closes), IH, AX, TT integrated->reverted, R9 dependents, G suite-failed->pending]. */
|
|
2333
|
+
private async completeReverted(live: LiveEntry, p: PhaseId, to: string, culprit: TaskRange, suiteCommit: string,
|
|
2334
|
+
ids: readonly string[]): Promise<void> {
|
|
2335
|
+
const from = this.ledger.integration.head;
|
|
2336
|
+
const released: Array<{ id: TaskId; slot: string | null; live: boolean }> = [];
|
|
2337
|
+
const text = `Reverted from the integration branch: phase ${p} suite at ${suiteCommit} failed (${ids.slice(0, 50).join(", ")}); this task's range ${culprit.from}..${culprit.to} is the culprit. Fix the failing tests before integrating again.`;
|
|
2338
|
+
await this.end(live, "ok", { v: 1, from, to }, true, ids, l => {
|
|
2339
|
+
const out: ExecutorEventInput[] = [{ type: "integration-head", head: to }, ...this.ax(l, culprit.taskId, text),
|
|
2340
|
+
...this.tt(l, culprit.taskId, "reverted", "suite-culprit")];
|
|
2341
|
+
const g2 = new Set<PhaseId>();
|
|
2342
|
+
for (const e of l.edges) {
|
|
2343
|
+
if (e.from !== culprit.taskId) continue;
|
|
2344
|
+
const t = l.tasks[e.to];
|
|
2345
|
+
if (t === undefined || (t.state !== "ready" && t.state !== "dispatched" && t.state !== "running")) continue;
|
|
2346
|
+
if (released.some(r => r.id === t.id)) continue;
|
|
2347
|
+
// `blocked` holds no open attempt (A1-7 `open-attempt`): the in-flight attempt ends before the transition, or the
|
|
2348
|
+
// ledger rejects the whole row-34 batch.
|
|
2349
|
+
const last = t.attempts[t.attempts.length - 1];
|
|
2350
|
+
if (last !== undefined && last.outcome === null) {
|
|
2351
|
+
// A2-6: endedAt = max(now, startedAt); startedAt is never rewritten (QA-3.2-16).
|
|
2352
|
+
const now = this.d.clock.iso();
|
|
2353
|
+
const endedAt = Date.parse(last.startedAt) > Date.parse(now) ? last.startedAt : now;
|
|
2354
|
+
out.push({ type: "attempt-ended", taskId: t.id, n: last.n, outcome: "interrupted", endedAt, detail: "dep-reverted" });
|
|
2355
|
+
}
|
|
2356
|
+
out.push(...this.tt(l, t.id, "blocked", "dep-reverted"));
|
|
2357
|
+
if (t.slot !== null) out.push({ type: "task-slot", taskId: t.id, slot: null, branch: t.branch });
|
|
2358
|
+
// QA4 G2 (rows 13/19): a qa task leaving flight for blocked takes its phase's gate qa-running->awaiting-qa.
|
|
2359
|
+
if (t.kind === "qa" && t.state !== "ready" && t.phase !== null && !g2.has(t.phase)) {
|
|
2360
|
+
const g = this.gateEvent(l, t.phase, "qa-running", "awaiting-qa", "qa-requeued");
|
|
2361
|
+
if (g.length > 0) g2.add(t.phase);
|
|
2362
|
+
out.push(...g);
|
|
2363
|
+
}
|
|
2364
|
+
released.push({ id: t.id, slot: t.slot, live: t.state !== "ready" });
|
|
2365
|
+
}
|
|
2366
|
+
out.push(...this.gateEvent(l, p, "suite-failed", "pending", "culprit-reverted"));
|
|
2367
|
+
out.push(counterEvent("integration.revert", 1, { outcome: "ok" }));
|
|
2368
|
+
return out;
|
|
2369
|
+
});
|
|
2370
|
+
if (this.disposed) return;
|
|
2371
|
+
for (const r of released) {
|
|
2372
|
+
// M1: a blocked dependent's slot can hold unsaved work, so it goes back through the runtime's saved release, never
|
|
2373
|
+
// `pool.release`. The runtime releases a live dependent's slot itself once its cancelled child ended.
|
|
2374
|
+
const release = async (): Promise<void> => {
|
|
2375
|
+
if (r.slot !== null) await this.d.releaseSlot(r.id, r.slot).catch((e: unknown) => this.d.logger.warn(`integration queue: slot release failed: ${message(e)}`));
|
|
2376
|
+
this.d.leases.releaseTask(r.id);
|
|
2377
|
+
};
|
|
2378
|
+
if (r.live) this.d.settle(r.id, release);
|
|
2379
|
+
// N-1: the runtime saves a ready dependent's slot under its task's mutex; that release is never awaited in this
|
|
2380
|
+
// serial lane (a pipeline holding the mutex may wait on the lane through `checkPhase`).
|
|
2381
|
+
else void release().catch((e: unknown) => this.d.logger.warn(`integration queue: slot release failed: ${message(e)}`));
|
|
2382
|
+
}
|
|
2383
|
+
this.safe(() => this.d.listener.onReverted(culprit.taskId));
|
|
2384
|
+
this.safe(() => this.d.listener.onGate(p, "pending"));
|
|
2385
|
+
await this.checkPhaseSafe(p);
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2389
|
+
// 4.6 tag entry (serial)
|
|
2390
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2391
|
+
|
|
2392
|
+
private async runTag(p: PhaseId): Promise<void> {
|
|
2393
|
+
const l = this.ledger;
|
|
2394
|
+
const ph = l.phases.find(x => x.id === p);
|
|
2395
|
+
if (ph === undefined || ph.gate !== "passed" || ph.tag !== null) return;
|
|
2396
|
+
try {
|
|
2397
|
+
await this.takeLock(null, true);
|
|
2398
|
+
} catch (e) {
|
|
2399
|
+
if (!this.tags.includes(p)) this.tags.unshift(p); // taken off by pickSerial: keep it due
|
|
2400
|
+
throw e;
|
|
2401
|
+
}
|
|
2402
|
+
const head = l.integration.head;
|
|
2403
|
+
const name = this.d.lander.tagName(this.d.planId, p);
|
|
2404
|
+
const live = await this.openEntry("serial", { kind: "tag", phaseId: p, taskIds: [], slot: null, baseHead: head, candidate: head },
|
|
2405
|
+
"tag", { v: 1, name, commit: head });
|
|
2406
|
+
await this.finishTag(live, p, name, head);
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
private async finishTag(live: LiveEntry, p: PhaseId, name: string, commit: string): Promise<"tagged" | "none"> {
|
|
2410
|
+
const wt = this.ledger.integration.worktree;
|
|
2411
|
+
for (let n = 1; ; n++) {
|
|
2412
|
+
if (live.open === null) await this.start(live, "tag", { v: 1, name, commit }, { candidate: commit });
|
|
2413
|
+
await this.assertLock(live);
|
|
2414
|
+
let r: TagOutcome;
|
|
2415
|
+
try {
|
|
2416
|
+
await this.d.guard.assertWriteCwd(wt, "tag");
|
|
2417
|
+
r = await this.d.lander.tag({ cwd: wt, name, commit });
|
|
2418
|
+
} catch (e) {
|
|
2419
|
+
r = { kind: "error", message: message(e) };
|
|
2420
|
+
}
|
|
2421
|
+
if (r === "created" || r === "exists-same") {
|
|
2422
|
+
const outcome = r;
|
|
2423
|
+
await this.end(live, "ok", { v: 1, outcome }, true, [],
|
|
2424
|
+
l => [...(l.phases.find(x => x.id === p)?.tag === null ? [{ type: "phase-tagged" as const, phaseId: p, tag: name }] : []),
|
|
2425
|
+
counterEvent("integration.tag", 1, { outcome })]);
|
|
2426
|
+
return "tagged";
|
|
2427
|
+
}
|
|
2428
|
+
if (r.kind === "exists-other") {
|
|
2429
|
+
const at = r.at;
|
|
2430
|
+
const now = this.d.clock.iso();
|
|
2431
|
+
const before = this.ledger.inbox.length;
|
|
2432
|
+
const next = await this.end(live, "refused", { v: 1, outcome: "exists-other", at }, true, [],
|
|
2433
|
+
l => [this.inboxEvent(l, "failure", "info", null, `The phase tag ${name} already exists at ${at}, not at ${commit}; it is never moved.`, now),
|
|
2434
|
+
counterEvent("integration.tag", 1, { outcome: "exists-other" })]);
|
|
2435
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2436
|
+
return "none";
|
|
2437
|
+
}
|
|
2438
|
+
await this.end(live, "refused", { v: 1, reason: "error", n, message: clipText(r.message, 1000) }, false);
|
|
2439
|
+
if (n >= CHECK_TRIES) {
|
|
2440
|
+
if (this.ledger.status === "running") await this.infraPause(live, `The phase tag ${name} could not be created (${clipText(r.message, 500)}).`);
|
|
2441
|
+
// QA-3.2-30: a completed plan has no pause to lift: roll the entry back and retry later (bounded), then give up.
|
|
2442
|
+
await this.retryTagLater(live, p, name, commit, r.message);
|
|
2443
|
+
return "none";
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
/** QA-3.2-30: rolls a completed plan's failing tag entry back; retries after TAG_RETRY_BASE_MS * 2^k, at most TAG_RETRY_LIMIT times. */
|
|
2449
|
+
private async retryTagLater(live: LiveEntry, p: PhaseId, name: string, commit: string, why: string): Promise<void> {
|
|
2450
|
+
await this.rollbackEntry(this.toOpen(live), "stalled");
|
|
2451
|
+
const k = (this.tagRetries.get(p) ?? 0) + 1;
|
|
2452
|
+
this.tagRetries.set(p, k);
|
|
2453
|
+
if (k > TAG_RETRY_LIMIT) {
|
|
2454
|
+
const now = this.d.clock.iso();
|
|
2455
|
+
const before = this.ledger.inbox.length;
|
|
2456
|
+
const top = this.ledger.repo.toplevel;
|
|
2457
|
+
const next = await this.append(l => [this.inboxEvent(l, "failure", "blocking", null,
|
|
2458
|
+
`The phase tag ${name} could not be created after ${k} rounds of ${CHECK_TRIES} tries (${clipText(why, 500)}). The plan is complete, so integration stops retrying it. Create it by hand: git -C "${top}" tag ${name} ${commit}`, now),
|
|
2459
|
+
counterEvent("integration.tag", 1, { outcome: "gave-up" })]);
|
|
2460
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
this.d.clock.setTimer(TAG_RETRY_BASE_MS * 2 ** (k - 1), () => {
|
|
2464
|
+
if (this.disposed || this.aborting || this.tags.includes(p)) return;
|
|
2465
|
+
this.tags.push(p);
|
|
2466
|
+
this.kick();
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2471
|
+
// 4.7 land
|
|
2472
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2473
|
+
|
|
2474
|
+
private async doLand(): Promise<{ landed: boolean; inbox: InboxItem | null }> {
|
|
2475
|
+
const l0 = this.ledger;
|
|
2476
|
+
if (l0.status !== "completed") throw new ExecutorError("E_PLAN_STATE", "land needs a completed plan", { planId: this.d.planId, status: l0.status });
|
|
2477
|
+
const head = l0.integration.head;
|
|
2478
|
+
const steps = await this.loadSteps();
|
|
2479
|
+
let lastLand: IntegrationStepEvent | null = null;
|
|
2480
|
+
for (const ev of steps) if (ev.entry.kind === "land" && ev.closes) lastLand = ev;
|
|
2481
|
+
if (lastLand !== null && lastLand.result === "ok" && lastLand.entry.candidate === head) {
|
|
2482
|
+
const base = await this.d.igit.readRef(l0.repo.toplevel, `refs/heads/${l0.repo.baseBranch}`).catch(() => null);
|
|
2483
|
+
// QA-3.2-35: a base branch that already contains the landed head (the owner committed on top) is landed too.
|
|
2484
|
+
if (base !== null && await this.baseContains(base, head)) return { landed: true, inbox: null };
|
|
2485
|
+
}
|
|
2486
|
+
return this.withSerial(async () => {
|
|
2487
|
+
await this.takeLock(null);
|
|
2488
|
+
try {
|
|
2489
|
+
return await this.landEntry();
|
|
2490
|
+
} finally {
|
|
2491
|
+
if (this.serial === null) await this.releaseLock();
|
|
2492
|
+
}
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
private async landEntry(): Promise<{ landed: boolean; inbox: InboxItem | null }> {
|
|
2497
|
+
const l = this.ledger;
|
|
2498
|
+
const head = l.integration.head;
|
|
2499
|
+
const mode = l.config.land;
|
|
2500
|
+
const req: LandRequest = { toplevel: l.repo.toplevel, baseBranch: l.repo.baseBranch, candidate: head, integrationBranch: l.integration.branch };
|
|
2501
|
+
const live = await this.openEntry("serial", { kind: "land", phaseId: null, taskIds: [], slot: null, baseHead: head, candidate: head },
|
|
2502
|
+
"land", { v: 1, mode, toplevel: req.toplevel, baseBranch: req.baseBranch });
|
|
2503
|
+
const finish = async (result: IntegrationStepResult, detail: StepDetail, inbox: { kind: InboxKind; severity: InboxItem["severity"]; text: string } | null,
|
|
2504
|
+
outcome: string): Promise<{ landed: boolean; inbox: InboxItem | null }> => {
|
|
2505
|
+
const now = this.d.clock.iso();
|
|
2506
|
+
const before = this.ledger.inbox.length;
|
|
2507
|
+
const next = await this.end(live, result, detail, true, [], lg => [
|
|
2508
|
+
...(inbox === null ? [] : [this.inboxEvent(lg, inbox.kind, inbox.severity, null, inbox.text, now)]),
|
|
2509
|
+
counterEvent("integration.land", 1, { mode, outcome })]);
|
|
2510
|
+
const items = this.newInbox(next, before);
|
|
2511
|
+
this.notifyInbox(items);
|
|
2512
|
+
return { landed: result === "ok", inbox: items[0] ?? null };
|
|
2513
|
+
};
|
|
2514
|
+
let tip: string | null;
|
|
2515
|
+
try {
|
|
2516
|
+
tip = await this.branchTip();
|
|
2517
|
+
} catch (e) {
|
|
2518
|
+
// QA-3.2-9: git could not run (infrastructure), never "moved"; the entry ends refused and land() can be retried.
|
|
2519
|
+
return finish("refused", { v: 1, reason: "error", message: clipText(message(e), 1000) }, { kind: "landing", severity: "blocking",
|
|
2520
|
+
text: `Landing ${head} on ${req.baseBranch} stopped: ${clipText(message(e), 500)}. Nothing was landed; retry land() once git runs again.` }, "error");
|
|
2521
|
+
}
|
|
2522
|
+
if (tip !== head) {
|
|
2523
|
+
return finish("refused", { v: 1, reason: "integration-branch-moved" }, { kind: "failure", severity: "critical",
|
|
2524
|
+
text: `The integration branch ${l.integration.branch} is at ${tip ?? "(missing)"}, not at the journaled head ${head}; nothing was landed.` }, "branch-moved");
|
|
2525
|
+
}
|
|
2526
|
+
const ff = `git -C "${req.toplevel}" merge --ff-only ${head}`;
|
|
2527
|
+
if (mode === "manual") {
|
|
2528
|
+
return finish("refused", { v: 1, reason: "manual" }, { kind: "landing", severity: "info",
|
|
2529
|
+
text: `Plan ${this.d.planId} is complete; the integration branch ${l.integration.branch} is at ${head}. To land it on ${req.baseBranch}:\n${ff}` }, "manual");
|
|
2530
|
+
}
|
|
2531
|
+
const refusal = (r: LandRefusal): Promise<{ landed: boolean; inbox: InboxItem | null }> => {
|
|
2532
|
+
let commands: string[] = [];
|
|
2533
|
+
try {
|
|
2534
|
+
commands = this.d.lander.commands(req, r);
|
|
2535
|
+
} catch (e) {
|
|
2536
|
+
this.d.logger.warn(`integration queue: lander.commands threw: ${message(e)}`);
|
|
2537
|
+
}
|
|
2538
|
+
return finish("refused", { v: 1, refusal: r }, { kind: "landing", severity: "blocking",
|
|
2539
|
+
text: `Landing ${head} on ${req.baseBranch} in ${req.toplevel} was refused (${r.reason}).${commands.length > 0 ? `\n${commands.join("\n")}` : ""}` }, r.reason);
|
|
2540
|
+
};
|
|
2541
|
+
let inspection: LandInspection;
|
|
2542
|
+
try {
|
|
2543
|
+
inspection = await this.d.lander.inspect(req);
|
|
2544
|
+
} catch (e) {
|
|
2545
|
+
return finish("refused", { v: 1, reason: "error", message: clipText(message(e), 1000) }, { kind: "landing", severity: "blocking",
|
|
2546
|
+
text: `Landing ${head} failed: ${clipText(message(e), 500)}` }, "error");
|
|
2547
|
+
}
|
|
2548
|
+
if (!inspection.ok) return refusal(inspection.refusal);
|
|
2549
|
+
let o: LandOutcome;
|
|
2550
|
+
try {
|
|
2551
|
+
o = await this.d.lander.fastForward(req);
|
|
2552
|
+
} catch (e) {
|
|
2553
|
+
o = { kind: "error", message: message(e) };
|
|
2554
|
+
}
|
|
2555
|
+
if (o.kind === "landed") return finish("ok", { v: 1, from: o.from, to: o.to }, null, "landed");
|
|
2556
|
+
if (o.kind === "refused") return refusal(o.refusal);
|
|
2557
|
+
return finish("refused", { v: 1, reason: "error", message: clipText(o.message, 1000) }, { kind: "landing", severity: "blocking",
|
|
2558
|
+
text: `Landing ${head} on ${req.baseBranch} failed: ${clipText(o.message, 500)}\n${ff}` }, "error");
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2562
|
+
// 4.8 resume (A1-3, A2-5, M31) and the shared rollback (M36)
|
|
2563
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2564
|
+
|
|
2565
|
+
private liveFor(o: OpenIntegrationEntry): LiveEntry {
|
|
2566
|
+
for (const c of [this.serial, this.background, ...this.stalled.values()]) {
|
|
2567
|
+
if (c !== null && c.entry.id === o.entry.id) {
|
|
2568
|
+
c.open = o.edge === "start" ? o.step : null;
|
|
2569
|
+
return c;
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
const live: LiveEntry = { entry: { ...o.entry, taskIds: [...o.entry.taskIds] }, startSeq: o.startSeq,
|
|
2573
|
+
open: o.edge === "start" ? o.step : null, openedAt: this.d.clock.now(), lane: o.entry.kind === "phase-suite" ? "background" : "serial" };
|
|
2574
|
+
if (live.lane === "serial") this.serial = live;
|
|
2575
|
+
else this.background = live;
|
|
2576
|
+
return live;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
/** §4.8 step 1: normalize to a started rollback step, run the rollback git, close with ISE(rollback, rolled-back). */
|
|
2580
|
+
private async rollbackEntry(o: OpenIntegrationEntry, reason: "resume" | "abort" | "stalled"): Promise<LiveEntry> {
|
|
2581
|
+
const live = this.liveFor(o);
|
|
2582
|
+
if (!(o.step === "rollback" && o.edge === "start")) {
|
|
2583
|
+
const entry = live.entry;
|
|
2584
|
+
if (o.edge === "start") {
|
|
2585
|
+
const step = o.step;
|
|
2586
|
+
await this.append(() => [ise(entry, step, "rolled-back", { v: 1, reason }, false), iss(entry, "rollback", { v: 1, of: step, reason })]);
|
|
2587
|
+
live.open = "rollback";
|
|
2588
|
+
live.openedAt = this.d.clock.now();
|
|
2589
|
+
} else {
|
|
2590
|
+
await this.start(live, "rollback", { v: 1, of: o.step === "rollback" ? null : o.step, reason });
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
const reset = await this.rollbackGit(live.entry);
|
|
2594
|
+
await this.end(live, "rolled-back", { v: 1, reset }, true);
|
|
2595
|
+
return live;
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
/** The §4.8 table's rollback git: none for tag, land and phase-suite. Returns the commit the slot was reset to. */
|
|
2599
|
+
private async rollbackGit(entry: IntegrationEntry): Promise<string | null> {
|
|
2600
|
+
if (entry.kind === "task" || entry.kind === "batch") {
|
|
2601
|
+
if (entry.slot === null) return null;
|
|
2602
|
+
// QA-3.2-21: the slot is reset to the tip of the task that owns it (the latest `entry.slot` may belong to a sub-batch's
|
|
2603
|
+
// last task, not the batch's). A slot no task of the entry owns any more was released: it is not ours to touch.
|
|
2604
|
+
const slot = entry.slot;
|
|
2605
|
+
const owner = entry.taskIds.find(id => this.ledger.tasks[id]?.slot === slot);
|
|
2606
|
+
if (owner === undefined) return null;
|
|
2607
|
+
const lease = await this.slotLease(slot, entry.id).catch(() => null);
|
|
2608
|
+
if (lease === null) return null;
|
|
2609
|
+
await this.guardWrite(null, lease.path, "slot");
|
|
2610
|
+
await this.d.git.rebaseAbort(lease.path).catch(() => undefined);
|
|
2611
|
+
const tip = await this.taskTip(owner).catch(() => null);
|
|
2612
|
+
if (tip !== null) await this.d.pool.reset(slot, tip);
|
|
2613
|
+
return tip;
|
|
2614
|
+
}
|
|
2615
|
+
if (entry.kind === "revert") {
|
|
2616
|
+
const l = this.ledger;
|
|
2617
|
+
const lease = await this.integrationSlot();
|
|
2618
|
+
await this.guardWrite(null, l.integration.worktree, "integration");
|
|
2619
|
+
await this.d.igit.revertAbort(l.integration.worktree).catch(() => undefined);
|
|
2620
|
+
await this.d.pool.reset(lease.slot, l.integration.head);
|
|
2621
|
+
return l.integration.head;
|
|
2622
|
+
}
|
|
2623
|
+
return null;
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
/** §4.8 table, "after the fsync": requeue (task/batch), journal the revert rerun, or collect the phase for checkPhase. */
|
|
2627
|
+
private async followUp(live: LiveEntry, report: ResumeReport | null, phases: Set<PhaseId>): Promise<void> {
|
|
2628
|
+
const e = live.entry;
|
|
2629
|
+
if (e.kind === "task" || e.kind === "batch") {
|
|
2630
|
+
const ids = e.taskIds.filter(id => this.ledger.tasks[id]?.state === "integrating");
|
|
2631
|
+
if (ids.length > 0) {
|
|
2632
|
+
this.requeued.push({ taskIds: ids, phaseId: e.phaseId, startSeq: live.startSeq });
|
|
2633
|
+
this.requeued.sort((a, b) => a.startSeq - b.startSeq);
|
|
2634
|
+
}
|
|
2635
|
+
report?.rolledBack.push(...ids);
|
|
2636
|
+
report?.entries.push({ id: e.id, kind: e.kind, action: "rolled-back" });
|
|
2637
|
+
return;
|
|
2638
|
+
}
|
|
2639
|
+
if (e.kind === "revert" && e.phaseId !== null) {
|
|
2640
|
+
const steps = await this.loadSteps();
|
|
2641
|
+
let first: IntegrationStepEvent | null = null;
|
|
2642
|
+
for (const ev of steps) if (ev.entry.id === e.id && ev.step === "revert-build" && ev.edge === "start") { first = ev; break; }
|
|
2643
|
+
const d = parseDetail(first?.detail);
|
|
2644
|
+
const c = d?.culprit as Partial<RangeDetail> | undefined;
|
|
2645
|
+
const taskId = e.taskIds[0];
|
|
2646
|
+
const fallback = taskId === undefined ? null : this.ledger.tasks[taskId]?.integrated ?? null;
|
|
2647
|
+
const culprit: TaskRange | null = c !== undefined && typeof c.taskId === "string" && typeof c.from === "string" && typeof c.to === "string"
|
|
2648
|
+
? { taskId: c.taskId, from: c.from, to: c.to }
|
|
2649
|
+
: taskId !== undefined && fallback !== null ? { taskId, from: fallback.from, to: fallback.to } : null;
|
|
2650
|
+
if (culprit === null) {
|
|
2651
|
+
report?.entries.push({ id: e.id, kind: e.kind, action: "rolled-back" });
|
|
2652
|
+
return;
|
|
2653
|
+
}
|
|
2654
|
+
const suiteCommit = typeof d?.suiteCommit === "string" ? d.suiteCommit : e.baseHead;
|
|
2655
|
+
const files = d?.truncated !== true && Array.isArray(d?.files) ? (d.files as unknown[]).filter((f): f is string => typeof f === "string") : []; // m1: truncated -> no files
|
|
2656
|
+
const ids = [...(first?.failingIds ?? [])];
|
|
2657
|
+
const resolved = await this.d.suite.resolve(this.ledger, e.phaseId, suiteCommit).catch(() => null);
|
|
2658
|
+
const head = this.ledger.integration.head;
|
|
2659
|
+
// Journal the rerun now; its git runs only while running (M31).
|
|
2660
|
+
const rerun = await this.openEntry("serial",
|
|
2661
|
+
{ kind: "revert", phaseId: e.phaseId, taskIds: [culprit.taskId], slot: "integration", baseHead: head, candidate: null },
|
|
2662
|
+
"revert-build", { v: 1, culprit, suiteCommit, head, files }, NONE, ids);
|
|
2663
|
+
this.reverts.unshift({ phaseId: e.phaseId, culprit, suiteCommit, ids, files,
|
|
2664
|
+
commands: resolved !== null && resolved.kind === "runs" ? resolved.commands : [], rerun });
|
|
2665
|
+
report?.entries.push({ id: e.id, kind: e.kind, action: "rerun" });
|
|
2666
|
+
return;
|
|
2667
|
+
}
|
|
2668
|
+
if (e.kind === "phase-suite" && e.phaseId !== null) {
|
|
2669
|
+
phases.add(e.phaseId);
|
|
2670
|
+
const l = this.ledger;
|
|
2671
|
+
const started = l.status === "running" && !phasePaused(l, e.phaseId);
|
|
2672
|
+
report?.entries.push({ id: e.id, kind: e.kind, action: started ? "rerun" : "rolled-back" });
|
|
2673
|
+
return;
|
|
2674
|
+
}
|
|
2675
|
+
// QA-3.2-15: a tag entry rolled back (stalled poll) comes due again through checkPhase (gate passed, no tag).
|
|
2676
|
+
if (e.kind === "tag" && e.phaseId !== null) phases.add(e.phaseId);
|
|
2677
|
+
report?.entries.push({ id: e.id, kind: e.kind, action: "none" });
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
/** §4.8 step 0 (b): complete a fast-forward that landed with the row-30 or row-34 batch. */
|
|
2681
|
+
private async completeOpen(o: OpenIntegrationEntry, report: ResumeReport): Promise<void> {
|
|
2682
|
+
const steps = await this.loadSteps();
|
|
2683
|
+
const live = this.liveFor(o);
|
|
2684
|
+
const head = this.ledger.integration.head;
|
|
2685
|
+
const tip = o.entry.candidate ?? head;
|
|
2686
|
+
const d = latestStartDetail(steps, o.entry.id) as Record<string, unknown> | null;
|
|
2687
|
+
if (o.step === "fast-forward") {
|
|
2688
|
+
const raw = Array.isArray(d?.ranges) ? d.ranges as unknown[] : [];
|
|
2689
|
+
const ranges: RangeDetail[] = [];
|
|
2690
|
+
for (const r of raw) {
|
|
2691
|
+
const x = r as Partial<RangeDetail> | null;
|
|
2692
|
+
if (x !== null && typeof x.taskId === "string" && typeof x.from === "string" && typeof x.to === "string") ranges.push({ taskId: x.taskId, from: x.from, to: x.to });
|
|
2693
|
+
}
|
|
2694
|
+
await this.completeIntegrated(live, head, tip, ranges);
|
|
2695
|
+
report.completed.push(...ranges.map(r => r.taskId));
|
|
2696
|
+
} else {
|
|
2697
|
+
const c = d?.culprit as Partial<RangeDetail> | undefined;
|
|
2698
|
+
const taskId = typeof c?.taskId === "string" ? c.taskId : o.entry.taskIds[0] ?? "";
|
|
2699
|
+
const culprit: TaskRange = { taskId, from: typeof c?.from === "string" ? c.from : "", to: typeof c?.to === "string" ? c.to : "" };
|
|
2700
|
+
const suiteCommit = typeof d?.suiteCommit === "string" ? d.suiteCommit : o.entry.baseHead;
|
|
2701
|
+
let ids: string[] = [];
|
|
2702
|
+
for (let i = steps.length - 1; i >= 0; i--) {
|
|
2703
|
+
const ev = steps[i];
|
|
2704
|
+
if (ev !== undefined && ev.entry.id === o.entry.id && ev.edge === "start") { ids = [...ev.failingIds]; break; }
|
|
2705
|
+
}
|
|
2706
|
+
if (o.entry.phaseId === null) throw new ExecutorError("E_INVALID_INPUT", "revert entry without a phase", { entry: o.entry.id });
|
|
2707
|
+
await this.completeReverted(live, o.entry.phaseId, tip, culprit, suiteCommit, ids);
|
|
2708
|
+
report.completed.push(taskId);
|
|
2709
|
+
}
|
|
2710
|
+
report.entries.push({ id: o.entry.id, kind: o.entry.kind, action: "completed" });
|
|
2711
|
+
}
|
|
2712
|
+
|
|
2713
|
+
private async resumeTag(o: OpenIntegrationEntry, report: ResumeReport): Promise<void> {
|
|
2714
|
+
const live = this.liveFor(o);
|
|
2715
|
+
const p = o.entry.phaseId;
|
|
2716
|
+
if (p === null || o.step === "rollback") {
|
|
2717
|
+
const r = await this.rollbackEntry(o, "resume");
|
|
2718
|
+
report.entries.push({ id: r.entry.id, kind: r.entry.kind, action: "none" });
|
|
2719
|
+
return;
|
|
2720
|
+
}
|
|
2721
|
+
const d = latestStartDetail(await this.loadSteps(), o.entry.id) as Record<string, unknown> | null;
|
|
2722
|
+
const name = typeof d?.name === "string" ? d.name : this.d.lander.tagName(this.d.planId, p);
|
|
2723
|
+
const commit = o.entry.candidate ?? o.entry.baseHead;
|
|
2724
|
+
if (live.open !== null && live.open !== "tag") await this.end(live, "rolled-back", { v: 1, reason: "resume" }, false);
|
|
2725
|
+
const action = await this.finishTag(live, p, name, commit);
|
|
2726
|
+
report.entries.push({ id: o.entry.id, kind: o.entry.kind, action: action === "tagged" ? "tagged" : "none" });
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
private async resumeLand(o: OpenIntegrationEntry, report: ResumeReport): Promise<boolean> {
|
|
2730
|
+
const live = this.liveFor(o);
|
|
2731
|
+
const l = this.ledger;
|
|
2732
|
+
const candidate = o.entry.candidate ?? o.entry.baseHead;
|
|
2733
|
+
const base = await this.d.igit.readRef(l.repo.toplevel, `refs/heads/${l.repo.baseBranch}`).catch(() => null);
|
|
2734
|
+
if (live.open !== null && live.open !== "land") await this.end(live, "rolled-back", { v: 1, reason: "resume" }, false);
|
|
2735
|
+
if (live.open === null) await this.start(live, "land", { v: 1, mode: l.config.land, toplevel: l.repo.toplevel, baseBranch: l.repo.baseBranch });
|
|
2736
|
+
// QA-3.2-35: landed when the base branch is at the candidate or already contains it (owner commits on top), the same
|
|
2737
|
+
// rule as land.ts's no-op inspection.
|
|
2738
|
+
if (base !== null && await this.baseContains(base, candidate)) {
|
|
2739
|
+
// One no-op convention with land.ts: from = to = the candidate (every landed outcome's `to` is the candidate).
|
|
2740
|
+
await this.end(live, "ok", { v: 1, from: candidate, to: candidate }, true, [], () => [counterEvent("integration.land", 1, { mode: l.config.land, outcome: "landed" })]);
|
|
2741
|
+
report.entries.push({ id: o.entry.id, kind: o.entry.kind, action: "completed" });
|
|
2742
|
+
return false;
|
|
2743
|
+
}
|
|
2744
|
+
await this.end(live, "rolled-back", { v: 1, reason: "resume" }, true);
|
|
2745
|
+
report.entries.push({ id: o.entry.id, kind: o.entry.kind, action: "rerun" });
|
|
2746
|
+
return true;
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
/** QA-3.2-35: the base tip is the candidate or a descendant of it (read-only; a git failure counts as "not landed"). */
|
|
2750
|
+
private async baseContains(base: string, candidate: string): Promise<boolean> {
|
|
2751
|
+
if (base === candidate) return true;
|
|
2752
|
+
return this.d.igit.isAncestor(this.ledger.repo.toplevel, candidate, base).catch(() => false);
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
/** §4.8 step 0 (c): [status-changed running->paused (only if running), IA critical]; halted, without the latch. */
|
|
2756
|
+
private async resumeHalt(report: ResumeReport, reason: string, text: string): Promise<void> {
|
|
2757
|
+
const now = this.d.clock.iso();
|
|
2758
|
+
const before = this.ledger.inbox.length;
|
|
2759
|
+
const next = await this.append(l => [...this.pauseEvents(l, reason),
|
|
2760
|
+
this.inboxEvent(l, "failure", "critical", null, text, now),
|
|
2761
|
+
counterEvent("integration.resume", 1, { action: "halted" })]);
|
|
2762
|
+
this.notifyInbox(this.newInbox(next, before));
|
|
2763
|
+
report.halted = true;
|
|
2764
|
+
}
|
|
2765
|
+
|
|
2766
|
+
private async doResume(): Promise<ResumeReport> {
|
|
2767
|
+
const report: ResumeReport = { completed: [], rolledBack: [], halted: false, entries: [] };
|
|
2768
|
+
const l0 = this.ledger;
|
|
2769
|
+
if (l0.status === "aborted") return report;
|
|
2770
|
+
if (l0.status !== "running" && l0.status !== "paused" && l0.status !== "completed") {
|
|
2771
|
+
throw new ExecutorError("E_PLAN_STATE", "resume needs a running, paused or completed plan", { planId: this.d.planId, status: l0.status });
|
|
2772
|
+
}
|
|
2773
|
+
let landAgain = false;
|
|
2774
|
+
const phases = new Set<PhaseId>();
|
|
2775
|
+
const halted = await this.withSerial(async () => {
|
|
2776
|
+
try {
|
|
2777
|
+
await this.takeLock(null);
|
|
2778
|
+
} catch (e) {
|
|
2779
|
+
// QA-3.2-33: the lock could not be taken; takeLock already paused with an item. Halted without the latch.
|
|
2780
|
+
if (!(e instanceof LaneStop)) throw e;
|
|
2781
|
+
report.halted = true;
|
|
2782
|
+
return true;
|
|
2783
|
+
}
|
|
2784
|
+
this.holdLock = true;
|
|
2785
|
+
try {
|
|
2786
|
+
// Step 0: reconcile the branch tip with integration.head.
|
|
2787
|
+
const head = this.ledger.integration.head;
|
|
2788
|
+
const ref = `refs/heads/${this.ledger.integration.branch}`;
|
|
2789
|
+
const read = await this.readRefRetry(ref);
|
|
2790
|
+
if (read.kind === "infra") {
|
|
2791
|
+
// QA-3.2-9: git could not run; infrastructure, never "moved". Halted without the latch: a later resume() retries.
|
|
2792
|
+
await this.resumeHalt(report, "integration-infrastructure",
|
|
2793
|
+
`resume() could not read ${ref} in ${this.ledger.repo.toplevel} ${CHECK_TRIES} times (${clipText(read.message, 500)}); this is an infrastructure failure, the branch was not judged. Integration is halted; nothing was changed. Fix git access, unpause and resume.`);
|
|
2794
|
+
return true;
|
|
2795
|
+
}
|
|
2796
|
+
const tip = read.at;
|
|
2797
|
+
if (tip === null) {
|
|
2798
|
+
await this.resumeHalt(report, "integration-branch-missing",
|
|
2799
|
+
`The integration branch ref ${ref} does not exist in ${this.ledger.repo.toplevel} (journaled head ${head}). The plan's compile/start step (5.1) must create the integration branch and its integration worktree slot before integration can run. Integration is halted; nothing was changed.`);
|
|
2800
|
+
return true;
|
|
2801
|
+
}
|
|
2802
|
+
if (tip !== head) {
|
|
2803
|
+
let ahead: boolean;
|
|
2804
|
+
try {
|
|
2805
|
+
ahead = await this.d.igit.isAncestor(this.ledger.repo.toplevel, head, tip);
|
|
2806
|
+
} catch (e) {
|
|
2807
|
+
// Nit: a git failure is infrastructure, never "moved".
|
|
2808
|
+
await this.resumeHalt(report, "integration-infrastructure",
|
|
2809
|
+
`resume() could not compare ${head} with the branch tip ${tip} (${clipText(message(e), 500)}); this is an infrastructure failure, the branch was not judged. Integration is halted; nothing was changed. Fix git access, unpause and resume.`);
|
|
2810
|
+
return true;
|
|
2811
|
+
}
|
|
2812
|
+
const o = ahead
|
|
2813
|
+
? this.d.writer.openIntegration().find(x => (x.step === "fast-forward" || x.step === "revert-fast-forward") && x.edge === "start" && x.entry.candidate === tip)
|
|
2814
|
+
: undefined;
|
|
2815
|
+
if (o === undefined) {
|
|
2816
|
+
await this.resumeHalt(report, "integration-branch-moved",
|
|
2817
|
+
`The integration branch ${this.ledger.integration.branch} is at ${tip}, not at the journaled head ${head}, and no journaled fast-forward explains it. Integration is halted; nothing was changed.`);
|
|
2818
|
+
return true;
|
|
2819
|
+
}
|
|
2820
|
+
await this.completeOpen(o, report);
|
|
2821
|
+
}
|
|
2822
|
+
// Step 1: open entries, oldest first.
|
|
2823
|
+
const opens = [...this.d.writer.openIntegration()].sort((a, b) => a.startSeq - b.startSeq);
|
|
2824
|
+
for (const o of opens) {
|
|
2825
|
+
if (this.reverts.some(r => r.rerun?.entry.id === o.entry.id)) continue;
|
|
2826
|
+
try {
|
|
2827
|
+
if (o.entry.kind === "tag") {
|
|
2828
|
+
await this.resumeTag(o, report);
|
|
2829
|
+
} else if (o.entry.kind === "land") {
|
|
2830
|
+
landAgain = await this.resumeLand(o, report) || landAgain;
|
|
2831
|
+
} else {
|
|
2832
|
+
const live = await this.rollbackEntry(o, "resume");
|
|
2833
|
+
await this.followUp(live, report, phases);
|
|
2834
|
+
}
|
|
2835
|
+
} catch (e) {
|
|
2836
|
+
if (!(e instanceof LaneStop)) throw e;
|
|
2837
|
+
report.entries.push({ id: o.entry.id, kind: o.entry.kind, action: "none" });
|
|
2838
|
+
// QA-3.2-28: after a lost-lock halt no later entry is rolled back without the lock: stop, halted, no latch.
|
|
2839
|
+
if (this.lockLost) {
|
|
2840
|
+
report.halted = true;
|
|
2841
|
+
return true;
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
// Step 2: orphans (integrating, in no open entry, exempt), after the step-1 requeues, in plan order.
|
|
2846
|
+
const queuedIds = new Set(this.requeued.flatMap(g => g.taskIds));
|
|
2847
|
+
for (const t of Object.values(this.ledger.tasks)) {
|
|
2848
|
+
if (t.state !== "integrating" || queuedIds.has(t.id)) continue;
|
|
2849
|
+
this.requeued.push({ taskIds: [t.id], phaseId: t.phase, startSeq: Number.MAX_SAFE_INTEGER });
|
|
2850
|
+
report.rolledBack.push(t.id);
|
|
2851
|
+
}
|
|
2852
|
+
// Step 3: phases to check.
|
|
2853
|
+
const l = this.ledger;
|
|
2854
|
+
for (const ph of l.phases) {
|
|
2855
|
+
if ((ph.gate === "pending" && phaseIntegrated(l, ph.id)) || ph.gate === "suite-running" || ph.gate === "suite-failed"
|
|
2856
|
+
|| (ph.gate === "passed" && ph.tag === null)) phases.add(ph.id);
|
|
2857
|
+
}
|
|
2858
|
+
for (const entry of report.entries) this.counters.push(counterEvent("integration.resume", 1, { action: entry.action }));
|
|
2859
|
+
return false;
|
|
2860
|
+
} finally {
|
|
2861
|
+
this.holdLock = false;
|
|
2862
|
+
await this.releaseLock();
|
|
2863
|
+
}
|
|
2864
|
+
});
|
|
2865
|
+
if (halted) return report;
|
|
2866
|
+
for (const p of phases) await this.checkPhaseSafe(p);
|
|
2867
|
+
// Step 4: latch, kick, pending land.
|
|
2868
|
+
this.resumed = true;
|
|
2869
|
+
this.report = report;
|
|
2870
|
+
this.kick();
|
|
2871
|
+
const l = this.ledger;
|
|
2872
|
+
if (landAgain && l.status === "completed" && l.config.land === "ff-when-clean") {
|
|
2873
|
+
void this.land().catch((e: unknown) => this.d.logger.warn(`integration queue: land after resume failed: ${message(e)}`));
|
|
2874
|
+
}
|
|
2875
|
+
return report;
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2879
|
+
// 4.9 abort
|
|
2880
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
2881
|
+
|
|
2882
|
+
private async doAbort(): Promise<void> {
|
|
2883
|
+
this.aborting = true;
|
|
2884
|
+
// QA-3.2-34: queued work behind an infrastructure pause would otherwise keep the 5 s poll armed forever.
|
|
2885
|
+
this.pausedWork = false;
|
|
2886
|
+
this.clearStalled();
|
|
2887
|
+
this.ctl.abort();
|
|
2888
|
+
this.bgCtl.abort();
|
|
2889
|
+
await Promise.allSettled([this.serialLoopP, this.backgroundLoopP]);
|
|
2890
|
+
if (this.disposed) return;
|
|
2891
|
+
await this.withSerial(async () => {
|
|
2892
|
+
await this.takeLock(null);
|
|
2893
|
+
this.holdLock = true;
|
|
2894
|
+
try {
|
|
2895
|
+
const l = this.ledger;
|
|
2896
|
+
const head = l.integration.head;
|
|
2897
|
+
const opens = [...this.d.writer.openIntegration()].sort((a, b) => a.startSeq - b.startSeq);
|
|
2898
|
+
const lives = opens.map(o => this.liveFor(o));
|
|
2899
|
+
const inEntries = new Set(opens.flatMap(o => o.entry.taskIds));
|
|
2900
|
+
const orphans = Object.values(l.tasks).filter(t => t.state === "integrating" && !inEntries.has(t.id));
|
|
2901
|
+
const synth: LiveEntry[] = [];
|
|
2902
|
+
// Batch A: per entry [ISE(open step, rolled-back)] if a step is started, then ISS(rollback); synthetic task entries for orphans.
|
|
2903
|
+
await this.append(lg => {
|
|
2904
|
+
const out: ExecutorEventInput[] = [];
|
|
2905
|
+
synth.length = 0;
|
|
2906
|
+
opens.forEach((o, i) => {
|
|
2907
|
+
const live = lives[i];
|
|
2908
|
+
if (live === undefined || (o.step === "rollback" && o.edge === "start")) return;
|
|
2909
|
+
if (o.edge === "start") out.push(ise(live.entry, o.step, "rolled-back", { v: 1, reason: "abort" }, false));
|
|
2910
|
+
out.push(iss(live.entry, "rollback", { v: 1, of: o.step === "rollback" ? null : o.step, reason: "abort" }));
|
|
2911
|
+
});
|
|
2912
|
+
for (const t of orphans) {
|
|
2913
|
+
const entry: IntegrationEntry = { id: entryIdAt(lg, out.length), kind: "task", phaseId: t.phase, taskIds: [t.id], slot: t.slot,
|
|
2914
|
+
baseHead: head, candidate: null };
|
|
2915
|
+
synth.push({ entry, startSeq: lg.seq + 1 + out.length, open: "rollback", openedAt: 0, lane: "serial" });
|
|
2916
|
+
out.push(iss(entry, "rollback", { v: 1, of: null, reason: "abort" }));
|
|
2917
|
+
}
|
|
2918
|
+
return out;
|
|
2919
|
+
});
|
|
2920
|
+
for (const live of lives) live.open = "rollback";
|
|
2921
|
+
const all = [...lives, ...synth];
|
|
2922
|
+
const resets = new Map<string, string | null>();
|
|
2923
|
+
for (const live of all) {
|
|
2924
|
+
// QA-3.2-28: after a lost-lock halt no further rollback git runs; the entries stay open (rollback started) for
|
|
2925
|
+
// the next writer's resume(), and abort() rejects (A1-8: the runtime logs it).
|
|
2926
|
+
if (this.lockLost) throw new LaneStop("repo lock lost during abort");
|
|
2927
|
+
try {
|
|
2928
|
+
resets.set(live.entry.id, await this.rollbackGit(live.entry));
|
|
2929
|
+
} catch (e) {
|
|
2930
|
+
this.d.logger.warn(`integration queue: rollback of ${live.entry.id} failed: ${message(e)}`);
|
|
2931
|
+
resets.set(live.entry.id, null);
|
|
2932
|
+
}
|
|
2933
|
+
}
|
|
2934
|
+
// Batch B, the row-33 batch: per entry [ISE(rollback, rolled-back, closes)], per still-integrating task [TT ->cancelled, TS(null)].
|
|
2935
|
+
const released: Array<{ id: TaskId; slot: string | null }> = [];
|
|
2936
|
+
await this.append(lg => {
|
|
2937
|
+
const out: ExecutorEventInput[] = [];
|
|
2938
|
+
released.length = 0;
|
|
2939
|
+
for (const live of all) {
|
|
2940
|
+
out.push(ise(live.entry, "rollback", "rolled-back", { v: 1, reset: resets.get(live.entry.id) ?? null }, true));
|
|
2941
|
+
for (const id of live.entry.taskIds) {
|
|
2942
|
+
const t = lg.tasks[id];
|
|
2943
|
+
if (t === undefined || t.state !== "integrating" || released.some(r => r.id === id)) continue;
|
|
2944
|
+
out.push(...this.tt(lg, id, "cancelled", "abort"));
|
|
2945
|
+
out.push({ type: "task-slot", taskId: id, slot: null, branch: t.branch });
|
|
2946
|
+
released.push({ id, slot: t.slot });
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
return out;
|
|
2950
|
+
});
|
|
2951
|
+
for (const live of all) live.open = null;
|
|
2952
|
+
this.serial = null;
|
|
2953
|
+
this.background = null;
|
|
2954
|
+
this.fifo.length = 0;
|
|
2955
|
+
this.endWaiting("aborted");
|
|
2956
|
+
this.requeued.length = 0;
|
|
2957
|
+
this.reverts.length = 0;
|
|
2958
|
+
this.tags.length = 0;
|
|
2959
|
+
this.suites.length = 0;
|
|
2960
|
+
for (const r of released) {
|
|
2961
|
+
if (r.slot !== null) await this.d.pool.release(r.slot).catch((e: unknown) => this.d.logger.warn(`integration queue: slot release failed: ${message(e)}`));
|
|
2962
|
+
this.d.leases.releaseTask(r.id);
|
|
2963
|
+
}
|
|
2964
|
+
} finally {
|
|
2965
|
+
this.holdLock = false;
|
|
2966
|
+
await this.releaseLock();
|
|
2967
|
+
}
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
private holdLock = false;
|
|
2972
|
+
|
|
2973
|
+
private dropQueued(id: TaskId): void {
|
|
2974
|
+
this.taskWaits.get(id)?.end("dropped");
|
|
2975
|
+
this.taskWaits.delete(id);
|
|
2976
|
+
const i = this.fifo.indexOf(id);
|
|
2977
|
+
if (i >= 0) this.fifo.splice(i, 1);
|
|
2978
|
+
}
|
|
2979
|
+
|
|
2980
|
+
private async checkPhaseSafe(p: PhaseId): Promise<void> {
|
|
2981
|
+
try {
|
|
2982
|
+
await this.checkPhase(p);
|
|
2983
|
+
} catch (e) {
|
|
2984
|
+
this.laneError(e);
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
}
|
|
2988
|
+
|
|
2989
|
+
/** M1: entry id of the entry whose first ISS is the k-th (0-based) event of the next batch. */
|
|
2990
|
+
export function entryIdAt(l: Readonly<LedgerV1>, k: number): string {
|
|
2991
|
+
return "i-" + String(l.seq + 1 + k);
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2994
|
+
/**
|
|
2995
|
+
* M20 (working reading of §3.3): every non-qa task of the phase is integrated, done or cancelled. A phase with no non-qa
|
|
2996
|
+
* task waits for the phases it depends on (QA-3.2-19); `path` guards dependency cycles.
|
|
2997
|
+
*/
|
|
2998
|
+
export function phaseIntegrated(l: Readonly<LedgerV1>, p: PhaseId, path: readonly PhaseId[] = []): boolean {
|
|
2999
|
+
let any = false;
|
|
3000
|
+
for (const t of Object.values(l.tasks)) {
|
|
3001
|
+
if (t.phase !== p || t.kind === "qa") continue;
|
|
3002
|
+
any = true;
|
|
3003
|
+
if (t.state !== "integrated" && t.state !== "done" && t.state !== "cancelled") return false;
|
|
3004
|
+
}
|
|
3005
|
+
if (any) return true;
|
|
3006
|
+
// QA-3.2-19: a phase with no non-qa task of its own is integrated only once every phase it depends on is (cycle-safe).
|
|
3007
|
+
const ph = l.phases.find(x => x.id === p);
|
|
3008
|
+
if (ph === undefined || path.includes(p)) return false;
|
|
3009
|
+
return ph.dependsOn.every(dep => phaseIntegrated(l, dep, [...path, p]));
|
|
3010
|
+
}
|
|
3011
|
+
|
|
3012
|
+
/** QA-3.2-31: the phases that depend on any of `ps`, transitively (each once, in plan order), excluding `ps` themselves. */
|
|
3013
|
+
export function dependentPhases(l: Readonly<LedgerV1>, ps: Iterable<PhaseId>): PhaseId[] {
|
|
3014
|
+
const seen = new Set<PhaseId>(ps);
|
|
3015
|
+
const out: PhaseId[] = [];
|
|
3016
|
+
for (let grew = true; grew;) {
|
|
3017
|
+
grew = false;
|
|
3018
|
+
for (const ph of l.phases) {
|
|
3019
|
+
if (seen.has(ph.id) || !ph.dependsOn.some(d => seen.has(d))) continue;
|
|
3020
|
+
seen.add(ph.id);
|
|
3021
|
+
out.push(ph.id);
|
|
3022
|
+
grew = true;
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
return out;
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
/** True when phase `p` has at least one non-qa task of its own (a suite has something to attribute). */
|
|
3029
|
+
export function phaseHasOwnTasks(l: Readonly<LedgerV1>, p: PhaseId): boolean {
|
|
3030
|
+
return Object.values(l.tasks).some(t => t.phase === p && t.kind !== "qa");
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
function phasePaused(l: Readonly<LedgerV1>, p: PhaseId | null): boolean {
|
|
3034
|
+
if (p === null) return false;
|
|
3035
|
+
return l.phases.find(ph => ph.id === p)?.paused === true;
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
/** A task the serial lane may dequeue: still `verified`, and its phase is not paused (A1-8 gates dequeue only). */
|
|
3039
|
+
function dequeueable(l: Readonly<LedgerV1>, id: TaskId): boolean {
|
|
3040
|
+
const t = l.tasks[id];
|
|
3041
|
+
return t !== undefined && t.state === "verified" && t.branch !== null && !phasePaused(l, t.phase);
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
/**
|
|
3045
|
+
* M16 + A1-8: the first dequeueable task, plus (only when 2+ tasks are dequeueable) the following dequeueable tasks
|
|
3046
|
+
* of the same phase, in queue order, up to `batchMax`. `batchMax = 1` disables batching. Never waits for a batch to fill.
|
|
3047
|
+
*/
|
|
3048
|
+
export function pickBatch(l: Readonly<LedgerV1>, queue: readonly TaskId[], batchMax: number): TaskId[] {
|
|
3049
|
+
const ready = queue.filter(id => dequeueable(l, id));
|
|
3050
|
+
const first = ready[0];
|
|
3051
|
+
if (first === undefined) return [];
|
|
3052
|
+
const max = Math.max(1, Math.floor(batchMax));
|
|
3053
|
+
if (ready.length < 2 || max === 1) return [first];
|
|
3054
|
+
const phase = l.tasks[first]?.phase ?? null;
|
|
3055
|
+
const out: TaskId[] = [];
|
|
3056
|
+
for (const id of ready) {
|
|
3057
|
+
if (out.length >= max) break;
|
|
3058
|
+
if ((l.tasks[id]?.phase ?? null) === phase) out.push(id);
|
|
3059
|
+
}
|
|
3060
|
+
return out;
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
/** M23: `baseHead` of the earliest task or batch entry of the phase in history; null if there is none. */
|
|
3064
|
+
export function phaseBase(steps: readonly IntegrationStepEvent[], p: PhaseId): string | null {
|
|
3065
|
+
let best: { seq: number; base: string } | null = null;
|
|
3066
|
+
for (const ev of steps) {
|
|
3067
|
+
const e = ev.entry;
|
|
3068
|
+
if (ev.edge !== "start" || e.phaseId !== p || (e.kind !== "task" && e.kind !== "batch")) continue;
|
|
3069
|
+
if (best === null || ev.seq < best.seq) best = { seq: ev.seq, base: e.baseHead };
|
|
3070
|
+
}
|
|
3071
|
+
return best?.base ?? null;
|
|
3072
|
+
}
|
|
3073
|
+
|
|
3074
|
+
/** M19: the parsed detail of the latest start edge of `entryId`, or null. */
|
|
3075
|
+
export function latestStartDetail(steps: readonly IntegrationStepEvent[], entryId: string): StepDetail | null {
|
|
3076
|
+
for (let i = steps.length - 1; i >= 0; i--) {
|
|
3077
|
+
const ev = steps[i];
|
|
3078
|
+
if (ev === undefined || ev.entry.id !== entryId || ev.edge !== "start") continue;
|
|
3079
|
+
const parsed = parseDetail(ev.detail);
|
|
3080
|
+
return parsed === null ? null : parsed as unknown as StepDetail;
|
|
3081
|
+
}
|
|
3082
|
+
return null;
|
|
3083
|
+
}
|