opencode-model-router 1.14.0 → 2.0.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.
@@ -0,0 +1,2226 @@
1
+ // src/verify/batch.ts
2
+ // S5 batching coordinator (plan Phase 2.2). The header below is the design of task 2.2.1; the
3
+ // pure helpers (2.2.2.b) and createBatchCoordinator (2.2.2.c, 2.2.2.d) implement it.
4
+ //
5
+ // ===============================================================================================
6
+ // BATCHING COORDINATOR: design (plan Phase 2.2, task 2.2.1)
7
+ //
8
+ // Consumes only the 2.1.1 contract in src/verify/types.ts, block "testsPass pipeline contract"
9
+ // (cherry-picked from vrb/p21 as 5be8c85 and never edited here): Deadline, ScopedOutcome,
10
+ // RecheckOutcome, VerificationScope, OpenVerificationScope, TestsPassRequest, TestsPassRun,
11
+ // TestsPassHook. Runner facts come from src/verify/runner.ts sections G, H, I (step 2a), J and
12
+ // Q 2.2. The pipeline and the verdict algebra are specified in the "testsPass PIPELINE" header of
13
+ // src/verify/deterministic.ts (vrb/p21, 7cd793d), cited below as 2.1-T<n>. Plan: section 1.3 (S5),
14
+ // 1.4 (batchWindowMs), 1.5-13 (deadline), 1.5-18/19 (router_verify and background mode reuse this
15
+ // coordinator), Phase 2.2. Record: docs/qa/verification-resource-budget/phase-2.2.md.
16
+ //
17
+ // -----------------------------------------------------------------------------------------------
18
+ // B1. GOAL AND GUARANTEES
19
+ //
20
+ // Concurrent testsPass checks that would run the same program with the same options become one
21
+ // scoped run over the union of their changed files. Each requester still gets the TestsPassRun
22
+ // it would have got running alone. hook(runtime) returns exactly a TestsPassHook, so 2.2.3 swaps
23
+ // the coordinator in behind 2.1's direct hook with no signature change. router_verify (2.4.3)
24
+ // and background mode (2.4.5) reach it through the same hook.
25
+ //
26
+ // B-G1 Equivalence. Under a deterministic runner, with no deadline expiry and no slot
27
+ // contention, each request's TestsPassRun judges (2.1-T5) to the same ok, the same
28
+ // unverifiable and the same introduced/preexisting/unknown sets as the direct hook gives
29
+ // that request alone (B12).
30
+ // B-G2 Only toward caution. When the runner is not deterministic (flaky tests), the batch may
31
+ // turn a would-be pass into unverifiable. It never turns anything into a pass (B7.5).
32
+ // B-G3 One slot hold per batch (QA-1.4-18). Each batch opens one VerificationScope, once, and
33
+ // holds it across the union run, the attribution runs and every recheck. Scopes are never
34
+ // nested. A split batch opens none: it hands each member to a batch of its own (B5.6).
35
+ // B-G4 A requester's own deadline bounds every step it waits for. One requester's expiry or
36
+ // abort never cancels the batch for the others. When every requester is gone, the running
37
+ // tree is killed.
38
+ // B-G5 The hook never rejects (TestsPassHook contract). Any internal failure becomes a
39
+ // ScopedOutcome "error" for the requests it affects (fail-closed, 2.1-T6 R8).
40
+ // B-G6 State is bounded. No timer outlives its window, and nothing outlives dispose().
41
+ // B-G7 Deadline pressure (QA-2.2-17). A batched request does not end weaker than it would with
42
+ // batchWindowMs: 0 under the same budget, as far as a cheap estimate can ensure. By default
43
+ // an unverifiable verdict is accepted with a caveat (strictUnverifiable off), so a batch
44
+ // that turned a rejection into a deadline-induced unverifiable would weaken the gate. A
45
+ // lone request never waits (W7). The window never eats into a member's reserve (W3). When
46
+ // any member's budget cannot cover the batched schedule, every member runs alone, exactly
47
+ // as its direct hook would (B5.2a, B5.6). Residuals: B15.
48
+ //
49
+ // -----------------------------------------------------------------------------------------------
50
+ // B2. BYPASSES (no window, no union), checked in this order on arrival
51
+ //
52
+ // 1. The coordinator is disposed -> { scoped: aborted BATCH_REASONS.disposed }.
53
+ // 2. request.testScope === "full" -> runtime.direct(request). The resolved command runs as
54
+ // written (2.1-T2 P5f). It cannot be merged, and S6 forbids widening a scoped run into it.
55
+ // 3. runtime.batchWindowMs <= 0 -> runtime.direct(request). "batchWindowMs: 0 disables
56
+ // batching": every request runs alone, still scoped.
57
+ // 4. plan = runtime.plan(request, request.deadline), that is, planScopedRun (B6). Then:
58
+ // NoAffected -> { scoped: { kind: "no-affected", note }, recheck: undefined }
59
+ // Unverifiable -> { scoped: { kind: "unverifiable", code, reason }, recheck: undefined }
60
+ // (S6; changedFiles "unavailable" lands here as attribution-unavailable)
61
+ // rejection -> { scoped: { kind: "error", reason }, recheck: undefined }
62
+ // These are exactly 2.1-T2 P3: none of them takes the slot or waits for a window. Planning
63
+ // comes first even when the deadline is already aborted, as in 2.1's direct hook, so those
64
+ // requests get the same planning outcome as alone (QA-2.2-9).
65
+ // 5. ScopedSpec, but the coordinator was disposed meanwhile -> B2.1; the deadline is aborted ->
66
+ // aborted BATCH_REASONS.beforeRun (2.1's ABORTED_BEFORE_RUN: its execute answers so with an
67
+ // aborted deadline). Nothing is spawned.
68
+ // 6. ScopedSpec -> the request joins the window of batchKey(spec) (B3, B4).
69
+ //
70
+ // -----------------------------------------------------------------------------------------------
71
+ // B3. BATCH KEY
72
+ //
73
+ // batchKey(spec) = JSON of [gitRoot, runner, entry, file, cwd, envSignature(spec.env),
74
+ // argvTemplate(spec)], with every path folded to lower case on win32.
75
+ // - gitRoot, runner, entry and envSignature (key-sorted JSON of spec.env) are the plan's key
76
+ // (runner.ts Q 2.2).
77
+ // - Three fields are added (deviation D1): file (node, or the native pytest/uv), cwd (the
78
+ // runnerCwd, which is also the id key space, runner.ts I) and argvTemplate. Two commands
79
+ // that resolve to the same entry can still differ in their kept arguments (-t, --project,
80
+ // -k, -m), in the worker cap, or in pytest's pinned -c/--rootdir (runner.ts D.4). A union
81
+ // run with one request's options would not be the run the other request gets alone (B-G1).
82
+ // - argvTemplate(spec) = spec.args with every element equal to one of spec.inputs removed,
83
+ // and every occurrence of spec.reportPath replaced by "<report>". Inputs are absolute and
84
+ // canonical (runner.ts N.2), so they never collide with an option token.
85
+ // Requests with equal keys run the same program, in the same directory, with the same options
86
+ // and environment. Only their inputs differ.
87
+ //
88
+ // -----------------------------------------------------------------------------------------------
89
+ // B4. WINDOWS
90
+ //
91
+ // W1 A window opens when the first request for a key finishes planning with a ScopedSpec. Its
92
+ // close time is set at that moment: openedAt + batchWindowMs, using the opener's runtime
93
+ // value. A config reload does not stretch a window that is already open. Each window has
94
+ // exactly one timer. The wiring caps batchWindowMs at gateBudgetMs / 10 (QA-2.2-21), so the
95
+ // window itself is never most of a gate's budget.
96
+ // W2 The window closes at that time, or at once when it holds maxBatchSize requests
97
+ // (BATCH_MAX_REQUESTS = 8 by default), whichever comes first. The close time never moves
98
+ // later: arrivals do not push it back (no debounce). So a steady stream cannot keep a window
99
+ // open, and no request waits in a window for longer than batchWindowMs (2.1-T3's bound for
100
+ // the batch wait). This is the starvation bound. W3 and W7 only close it earlier.
101
+ // W3 The reserve (QA-2.2-17 b, QA-2.2-24). A member's floor is its
102
+ // runtime.recheckMinRemainingMs when it can recheck at all (failureRecheck on and a captured
103
+ // reference), else 0, plus BATCH_RESERVE_MARGIN_MS (1 s: union planning and scheduling).
104
+ // With e = the key's last measured run duration (0 before the first run of the key), the
105
+ // window closes no later than the moment the member at arrival index k (0 for the first)
106
+ // would be left with less than
107
+ // floor + e x (2k + 1).
108
+ // That is what the schedule after the close needs when the batch splits (B5.6) and the slot
109
+ // is one: the k members that joined before it run and recheck first, then its own run, then
110
+ // its recheck. Their direct hooks would have queued in that order too. QA-2.2-24: the former
111
+ // reserve, floor + e for each member alone, let a window held open by W7's signal spend the
112
+ // recheck of the second tight member. When a member joins, and when a run of the key is measured,
113
+ // the close time moves earlier if needed (the timer is re-armed, still one per window), or
114
+ // the window closes at once when that moment has passed. A joiner whose remaining() is
115
+ // within its floor therefore closes the window at once, as the former W3 did for a joiner
116
+ // that could not outlive the wait.
117
+ // W4 At close, the window is removed from the key map before anything asynchronous happens. A
118
+ // request for the same key that finishes planning later opens the NEXT window. "Later"
119
+ // covers the whole life of the batch: planning its union, waiting for the slot, running,
120
+ // rechecking. A running union is never extended; its inputs are fixed at close.
121
+ // W5 A request whose deadline aborts while it waits in a window is settled at once with
122
+ // aborted BATCH_REASONS.window, and removed. A window left empty clears its timer and is
123
+ // deleted.
124
+ // W6 Batches for different keys (roots, runners, templates) are independent. Each opens its
125
+ // own scope and competes for the machine-wide slot like any other verification, so they run
126
+ // in parallel only as far as maxConcurrentVerifications allows. Two batches for the SAME
127
+ // key (window N running, window N+1 closed) are just as independent, and serialize on the
128
+ // slot when there is only one.
129
+ // W7 Idle close (QA-2.2-17 a, QA-2.2-18). When no request is planning (between its arrival and
130
+ // its window or planning outcome) and no batch is running, nothing can join an open window
131
+ // and the slot is free, so every open window closes at once. It is checked when a request
132
+ // joins, when a planning ends without a spec, and when a batch ends or is evicted. A lone
133
+ // request therefore pays no window latency: its window closes as it joins, and it runs as
134
+ // the direct path (B5.1). Requests that arrive while a batch runs gather in the next window,
135
+ // which closes when that batch ends, at its timer, or by W2/W3 (group commit: under one slot
136
+ // they would have waited for it anyway). The signal is the coordinator's own. The wiring
137
+ // cannot see a gate that has not reached testsPass yet without index.ts and 2.4 bracketing
138
+ // every gate, so concurrent gates batch when they reach testsPass together or while another
139
+ // batch runs. BatchCoordinatorOptions.idleClose: false keeps only the timed close, for the
140
+ // tests of W1-W6.
141
+ //
142
+ // -----------------------------------------------------------------------------------------------
143
+ // B5. BATCH RUN SEQUENCE
144
+ //
145
+ // At close, with members M (in arrival order) and the batch deadline D (B9):
146
+ // 1. |M| = 1: skip steps 2a and 2. Step 4 runs the member's own spec with the member's own
147
+ // deadline. Steps 5 and 7 have nothing to do, and step 8 is a single-member recheck. This is
148
+ // exactly the direct path.
149
+ // 2a. Deadline check (QA-2.2-17 c, QA-2.2-23, QA-2.2-25), before union planning. Take the
150
+ // members in deadline order, and e and each member's floor as in W3. The batch pools only
151
+ // when every member's remaining() is at least
152
+ // floor + e x (2n + i),
153
+ // where n is the number of members and i the member's index. That sum is the worst case of
154
+ // the batched schedule ahead of its recheck: the union (n x e), every member's own run (mode
155
+ // B; a member can be held until the last of them, B5.7) and one recheck for each member
156
+ // ahead of it. Otherwise the batch splits (step 6), and every member runs alone.
157
+ // QA-2.2-25: the union is priced at n runs, never at one. It runs each of the members'
158
+ // related test files once, where their own runs run each at least once; e itself is usually
159
+ // one member's own run, and the union's run grows with its inputs. The check repeats after
160
+ // union planning (step 2) and once the hold is taken (step 3), the schedule's two unmeasured
161
+ // parts, and both are bounded by the time the check has left: past it, the members split.
162
+ // QA-2.2-23: 9ed2abb instead ran the short members first inside the batch's scope. The
163
+ // scope's first execute takes its one hold, and 2.1's scope reports a failed hold attempt to
164
+ // every later call at once (P4). So a short member's cut slot wait became slot-busy for every
165
+ // other member, including members with a minute left. No member now runs in a scope whose
166
+ // hold another member's deadline decides: a pooled scope's first execute is the union under
167
+ // D, and a split member's scope is its own.
168
+ // Before the first measured run of a key, e is 0 and only the floor counts (a residual,
169
+ // B15).
170
+ // 2. Union planning (B6): runtime.plan({ command and cwd of the first member, changedFiles:
171
+ // unionChangedFiles(M) }, D'), where D' is D cut off when step 2a's check would fail
172
+ // (QA-2.2-25). The batch splits (step 6) in four cases: the result is not a ScopedSpec;
173
+ // batchKey(unionSpec) differs from the batch key; its inputs are not exactly the union of
174
+ // the members' inputs (set equality on platform keys); or step 2a's check fails afterwards.
175
+ // 3. scope = runtime.openScope({ cwd, command }) of the first member. It is opened once, and
176
+ // every execute and rechecker below goes through it (B10). QA-2.2-25: when the scope has
177
+ // hold() (2.1's scopes do), the batch takes the hold first, under D' again, and repeats step
178
+ // 2a's check once it holds the slot. A hold not taken in time, or a failed check, closes the
179
+ // scope and splits. The union's execute then reuses the hold (2.1's scope memoizes its one
180
+ // hold attempt), so a batch never takes two.
181
+ // 4. U = scope.execute(unionSpec, D). By kind:
182
+ // slot-busy -> every member gets U. (The scope would report it again without
183
+ // waiting anyway.)
184
+ // aborted -> D aborted, so every member was already settled (B9).
185
+ // ran -> attribution per member (B7).
186
+ // timed-out, error -> every member is "own-run".
187
+ // 5. One queue under the hold (QA-2.2-3). Own runs and rechecks run one command at a time,
188
+ // EARLIEST DEADLINE FIRST across both kinds: at each step the member with the least
189
+ // remaining() among those with a runnable step goes next (arrival order breaks ties). Its
190
+ // step is either
191
+ // - its own run (the members marked "own-run"): scope.execute(memberSpec,
192
+ // member.deadline), whose outcome is the member's scoped outcome, verbatim; or
193
+ // - its recheck (B8), as soon as its outcome is final (step 7).
194
+ // So a member never waits for a step it does not need: the member with the least time left
195
+ // runs, rechecks and settles first, and the queue never nests a scope. A member settled in
196
+ // the meantime (an abort) is skipped, and nothing is spawned for it.
197
+ // 6. Split (QA-2.2-23): there is no union run, and this batch opens no scope. Every member runs
198
+ // alone, as a batch of one (step 1) with its own gate's runtime: its own scope, whose hold it
199
+ // takes under its own deadline, its own run and its own recheck. That is each member's
200
+ // direct path, so the cost is the same as without batching, and so is every verdict, apart
201
+ // from the time the member spent in the window (W3). The batches of one start in arrival
202
+ // order, the order in which the members' direct hooks would have queued for the slot, and
203
+ // each competes for the slot as its direct hook would: in parallel as far as
204
+ // maxConcurrentVerifications allows. The split is logged once per batch. Causes: step 2a's
205
+ // deadline check, or an inconsistent union plan (step 2).
206
+ // 7. Finality and the flaky taint (B7.5). A member's outcome is known after step 4 (derived) or
207
+ // after its own run. It is FINAL once no taint can change it: the union was green or did not
208
+ // run, or every union failing id is reproduced (by a finished own run or a static
209
+ // derivation, B7.5), or no own run is left, in which case the taint is applied once. Until
210
+ // then the member holds its outcome.
211
+ // 8. A final outcome settles AT ONCE when it needs no recheck (2.1-T2 P7: "ran" with >= 1
212
+ // failing id and >= 1 failing file), when its reference decides it (B8.1), or when a recheck
213
+ // already run in this batch at the same reference answers it (B8.6). Otherwise the member
214
+ // queues for its recheck (step 5). A green member of a green union therefore settles right
215
+ // after step 4, and a member whose own run reproduces every union failure rechecks right
216
+ // after that run, before the own runs of members with more time left.
217
+ // 9. When the queue is empty every member is settled. Then `void scope.close()`: a requester
218
+ // never waits for the close (2.1-T2 P9). The batch leaves the registry.
219
+ //
220
+ // -----------------------------------------------------------------------------------------------
221
+ // B6. UNION SPEC AND DEDUPLICATION
222
+ //
223
+ // unionChangedFiles(M) takes each member's ChangedPath entries and resolves path and
224
+ // previousPath against THAT member's request.cwd. ChangedPath paths may be relative to the
225
+ // planner's cwd, and members with the same runnerCwd can have different check cwds. Entries
226
+ // are deduplicated by the platform key of (path, previousPath), in first-seen order, keeping
227
+ // the first entry's status (it is informational: runner.ts G.6 decides existence through the
228
+ // fs). A file edited by two producers appears once.
229
+ // The union is planned by planScopedRun itself (runner.ts Q 2.2), never assembled by hand. That
230
+ // keeps argv construction, the argv-length cap, config triggers and pytest pinning in one
231
+ // place. The step-2 consistency checks catch every way the union plan can differ from the
232
+ // members' plans:
233
+ // - a union-only S6: argv-too-long, too-many-searches, config-too-large;
234
+ // - a pytest pin computed from a different common ancestor;
235
+ // - a search that answered differently;
236
+ // - a file that changed between the plans.
237
+ // Each of these falls back to the split, never to a different run.
238
+ // Cost: union planning repeats the members' test searches (git only, low priority, bounded by
239
+ // D). Merging the members' plans instead would need a new runner.ts entry point (rejected, see
240
+ // phase-2.2.md).
241
+ //
242
+ // -----------------------------------------------------------------------------------------------
243
+ // B7. ATTRIBUTION
244
+ //
245
+ // Mode B (runner.ts J, Spike C). vitest has no non-executing related listing, and a jest-only
246
+ // listing (mode A) was rejected. pytest needs no process at all: its spec inputs ARE the test
247
+ // files (inputsAreTests), so a failing file belongs to the members whose inputs contain it.
248
+ // attributeUnion(U.result, counts, memberSpec) decides for each member between "derived" (a
249
+ // RunResult computed from the union's) and "own-run" (the member's own planScopedRun spec runs,
250
+ // B5.5).
251
+ // Keys: fileKeyOf(spec.cwd, abs) is the id-space file key (cwd-relative, "/" separators), the
252
+ // construction readResult uses. fileKeyOfId(id) is 2.1-T5's rule, imported from baseline.ts
253
+ // (2.2.3): the part before the EARLIEST " > " or "::", else the whole id, with "/" separators
254
+ // (QA-2.2-11: a pytest name may contain " > ", as in tests/test_x.py::test_cmp[1 > 0], and its
255
+ // file is still the part before "::"). It is the only id-to-file rule in this module (7.3a, 7.5,
256
+ // B8.5), so the batch and 2.1's judge can never key an id differently.
257
+ //
258
+ // 7.1 Not comparable: !U.complete, U.collectionError, or U.source !== "report" -> own-run
259
+ // (cause "not-comparable"). A vitest syntax error in any test file aborts `related` without
260
+ // a report, which gives a text source and a collection error. Each member's own run then
261
+ // shows whether that member hits the error alone.
262
+ // 7.2 Green union (complete, no collection error, no failing id):
263
+ // a. A member that is not guard-sensitive -> derived green: no ids, complete, total =
264
+ // U.total, exit 0. isGuardSensitive is false when the spec has no lexicalPaths, is not
265
+ // inputsAreTests, and has no JS test file among its inputs (runner.ts G.8 rule). The
266
+ // member's own related set is a subset of the union's (related is monotone in its
267
+ // inputs, and vitest and jest run each test file in its own module scope), so its own
268
+ // run is green too. Its own total may be 0: that is a pass with note n1 instead of
269
+ // evidence e1, which is the same verdict.
270
+ // b. A guard-sensitive member. Its own run would be made incomplete by readResult's
271
+ // zero-test guard (runner.ts I 2a) if IT ran 0 tests, and the union's total cannot show
272
+ // that. With per-file counts (counts = U.testsByFile, prerequisite P1 below):
273
+ // inputsAreTests (pytest): n = the sum of counts over its inputs. n > 0 -> derived
274
+ // green with total n. n = 0 -> derived incomplete with the guard's own note "<runner>
275
+ // ran no tests although a test file was passed", which is exactly its own result.
276
+ // JS test-file inputs (a test file given to related runs itself, runner.ts R): n = the
277
+ // sum of counts over its test-file inputs. n > 0 -> derived green. n = 0 -> own-run
278
+ // (cause "zero-test-ambiguous"): its source inputs may or may not have related tests.
279
+ // lexicalPaths: as the JS rule. Keys that do not match give n = 0, hence own-run.
280
+ // Without counts (P1 not landed, or a text source) -> own-run. This is the
281
+ // "confirmation run".
282
+ // 7.3 Failing union (complete, no collection error, >= 1 failing id):
283
+ // a. inputsAreTests (pytest, static attribution): ids = the U.failingIds whose file key is
284
+ // one of the member's input keys; files = the U.failingFiles among its inputs. ids
285
+ // non-empty -> derived, with complete, no collection error, exit 1, and total = the
286
+ // count sum when counts exist (else U.total). ids empty -> the pytest rule of 7.2b (its
287
+ // files all passed, or ran nothing).
288
+ // This is only sound because the union's ids name the file that really ran each case:
289
+ // runner.ts I step 3 maps a classname by its exact rootdir-relative path, and a classname
290
+ // two inputs could own makes the union incomplete (7.1), never a guess (QA-2.2-1: with
291
+ // "the first input wins", tests/test_x.py's failure landed on sub/tests/test_x.py).
292
+ // b. vitest/jest -> own-run (cause "mode-b"). vitest cannot intersect `related` with a file
293
+ // filter, so the member's own spec runs, covering its whole affected set. That run
294
+ // contains exactly the failures the member would see alone.
295
+ // 7.4 So every member's final scoped outcome is one of two things. Either it is its own run's
296
+ // outcome, verbatim. Or it is a derived "ran" outcome that judges the same: its spec is
297
+ // the member's own spec, and its notes are the member's plan notes plus
298
+ // "batched: 1 run for <n> requests".
299
+ // 7.5 Flaky taint (B-G2). When U had failing ids, unreproduced = U.failingIds minus the ids of
300
+ // every finished own run and every static derivation (7.3a). A derivation counts even for
301
+ // a member that left during the union run, because pytest attribution is exact (QA-2.2-3);
302
+ // an own run counts even when its member left before it returned. The set only shrinks, so
303
+ // it is decided once it is empty or no own run is left (B5.7). If it is then non-empty,
304
+ // some union failure was reproduced by no member's own run, and taintUnreproduced makes
305
+ // EVERY live member's "ran" result complete = false, with the note "batched run failure not
306
+ // reproduced by any request's own run: <ids>". A complete union keeps every id (QA-2.2-11: an
307
+ // id no derivation reproduces taints, whatever its key). Only an incomplete pytest union leaves
308
+ // out an id that names none of its inputs (a classname readResult could not map, runner.ts I
309
+ // step 3): its raw form cannot equal any own run's id, and every member of an incomplete union
310
+ // runs its own spec verbatim (7.1). Per 2.1-T6, complete = false never passes (R4 u12; R2i u10 or u8), and a
311
+ // proven introduced id still rejects (R2i x X- = F r1). The unreproduced id could belong to
312
+ // any member's related set, and for vitest/jest a green own run cannot rule that out.
313
+ //
314
+ // P1. Proposed write-set addition in runner.ts (task 2.2.2.a); it enables the cheap path of
315
+ // 7.2b. RunResult gains `testsByFile?: Readonly<Record<string, number>>`: the number of
316
+ // tests the report lists for each file key, so that the values sum to total. vitest/jest:
317
+ // assertionResults.length of each suite. pytest: the testcases mapped to each input,
318
+ // without the collection pseudo-cases. Only report sources fill it; the text fallback
319
+ // leaves it undefined. The change is additive, and 2.1's judgeScoped ignores it.
320
+ // Without P1 the coordinator is still correct, but it pays one confirmation run for each
321
+ // guard-sensitive member of a green batch. Implementation delegations usually touch test
322
+ // files, so that would remove most of the saving.
323
+ //
324
+ // -----------------------------------------------------------------------------------------------
325
+ // B8. SHARED RECHECK (S2)
326
+ //
327
+ // Only members whose scoped outcome is "ran" with >= 1 failing id and >= 1 failing file take
328
+ // part.
329
+ // 1. Pre-decisions for each member, with no spawn (2.1-T4), in 2.1's direct-hook order:
330
+ // ReferenceState "disabled", OR the member's own gate-time runtime.failureRecheck is off ->
331
+ // { kind: "disabled" }; "none" -> { kind: "unusable", cause: "no-reference", reason }.
332
+ // failureRecheck is read from the runtime of the hook that submitted the member, never from
333
+ // the window opener's (QA-2.2-2): a reference captured at dispatch while the setting was on
334
+ // is disabled when the setting is off at the gate (a config reload, or a later
335
+ // router_verify), as the direct hook does.
336
+ // 2. "captured" members are grouped by referenceKey(reference): root, commit, and the sorted
337
+ // untracked, tracked and captureReasons entries (capturedAt is excluded). A recheck at one
338
+ // reference proves nothing about another, so ONE recheck is shared per distinct reference,
339
+ // not per batch (deviation D3). These share one reference:
340
+ // - the members of one dispatch (an escalation retry keeps the first reference, and
341
+ // router_verify may name several handles of one dispatch);
342
+ // - captures of the same clean HEAD with the same untracked files.
343
+ // Distinct stash commits never share.
344
+ // 3. Rechecks are steps of the B5.5 queue. When a member's recheck turn comes, every member
345
+ // ready at that moment at the same reference joins it (its group, earliest deadline first).
346
+ // A member whose deadline.remaining() is below runtime.recheckMinRemainingMs (2.1's
347
+ // RECHECK_MIN_REMAINING_MS, injected) gets { kind: "skipped-deadline", remainingMs } and
348
+ // leaves its group, as it would alone (2.1-T3): a member whose budget cannot fit its
349
+ // recheck is never passed on a guess.
350
+ // 4. A group of one member -> scope.rechecker(command, cwd, its currentTree)(reference, its
351
+ // failingFiles, its own deadline). This is the direct path. (QA-2.2-8, 2.2.3: every recheck
352
+ // forwards the requesting gate's tree snapshot, runtime.currentTree, as 2.1's direct hook
353
+ // does; a shared recheck forwards its first member's.)
354
+ // 5. A group of several members:
355
+ // files = the deduplicated union of their failingFiles;
356
+ // Rg = a batch deadline over the group (B9);
357
+ // shared = scope.rechecker(first member's command, cwd)(reference, files, Rg).
358
+ // Each member's outcome is deriveSharedRecheck(shared, counts, its failingFiles,
359
+ // its spec.cwd):
360
+ // - approximate, disabled, timed-out, skipped-deadline, and unusable with a
361
+ // reference-level cause (no-reference, materialize-failed, reference-vanished,
362
+ // unreproduced-inputs, runner-unsupported, error) -> the same outcome for every member.
363
+ // - unusable with a run-level cause (incomplete, collection-error, no-tests,
364
+ // rerun-unplannable) -> "split". Another member's files may be the cause: a collection
365
+ // error at the reference, or argv-too-long for the union list. Each member then gets
366
+ // its own recheck (step 4), in deadline order.
367
+ // - exact -> ranFiles and absentFiles are intersected with the member's file keys; the
368
+ // result is filtered to the ids and files with those keys (still complete and without a
369
+ // collection error, as "exact" requires); it is undefined when all of the member's files
370
+ // are absent. Zero-test check, as in 7.2b:
371
+ // with counts, a member whose ran files hold 0 tests at the reference gets unusable
372
+ // "incomplete", because its own rerun would have tripped the rerun zero-test guard
373
+ // (QA-1.3-17);
374
+ // without counts, a member that has ran files but no failing id among them at the
375
+ // reference -> "split".
376
+ // 6. Reuse (QA-2.2-3). A member that becomes ready AFTER a recheck ran at its reference (it
377
+ // finished its own run later) first derives its outcome from each recorded outcome at that
378
+ // reference with the rule of step 5; the first answer that is not "split" settles it with
379
+ // no spawn. Only outcomes that hold for any member are recorded: exact, approximate, and
380
+ // unusable "reference-vanished", "unreproduced-inputs" or "runner-unsupported". Never
381
+ // timed-out or skipped-deadline (the deadline of the member that ran it), nor
382
+ // "materialize-failed" (an aborted materialize reports it) or "error" (transient).
383
+ // 7. pytest: 2.1's Rechecker returns unusable "runner-unsupported" without spawning (2.1
384
+ // decision 5), so sharing it costs nothing.
385
+ // Recheck calls per window: at most one per distinct reference among the failing members when
386
+ // each later member's failing files are covered by an earlier recheck at its reference, plus
387
+ // split rechecks and rechecks of files no earlier recheck covered (at most one per member, as
388
+ // alone). The plan's "single shared recheck" holds when the members share a reference and a
389
+ // pre-existing failure, the plan's case.
390
+ //
391
+ // -----------------------------------------------------------------------------------------------
392
+ // B9. DEADLINES AND CANCELLATION
393
+ //
394
+ // - Each member keeps its own Deadline (request.deadline: one per gate or router_verify call,
395
+ // 1.5-13). Nothing extends it.
396
+ // - The batch deadline D = createBatchDeadline(members):
397
+ // remaining() the largest remaining() among the members not yet settled (0 when none);
398
+ // bound(x) min(x, remaining());
399
+ // budgetMs the largest member budget;
400
+ // signal aborts once every member still attached has aborted, or at dispose.
401
+ // A settled member is released from D, so a requester that is done never keeps the batch
402
+ // alive with its long budget. D has no timer of its own: when the last attached member's
403
+ // signal aborts at its expiry, D aborts too. dispose() removes every listener.
404
+ // - Which deadline bounds what:
405
+ // union planning and the union's hold D', D cut off where the pooled schedule stops
406
+ // fitting (B5.2a, QA-2.2-25)
407
+ // the union run D
408
+ // a member's own run that member's deadline, exactly as alone
409
+ // a single-member recheck that member's deadline, exactly as alone
410
+ // a shared recheck Rg, D restricted to the group
411
+ // - A member whose signal aborts is settled at once. The result depends on its phase:
412
+ // waiting in the window aborted BATCH_REASONS.window
413
+ // union planning or union run aborted BATCH_REASONS.run (2.1-T2 P5's phrase)
414
+ // queued for its own run aborted BATCH_REASONS.attribution
415
+ // its own run is running that run's outcome (the executor kills it and
416
+ // reports aborted); a "ran" outcome is settled as
417
+ // in the next row
418
+ // holding a known outcome (B5.7) QA-2.2-3: that outcome, never a bare abort. While
419
+ // a union failure is still unexplained it is made
420
+ // incomplete by taintUnreproduced with those ids
421
+ // (never a pass); a needed recheck becomes its
422
+ // reference decision, else skipped-deadline
423
+ // final, waiting for its recheck turn { scoped: its outcome, recheck: its reference
424
+ // decision, else skipped-deadline }, as alone
425
+ // below the recheck threshold
426
+ // its recheck is running { scoped: its outcome, recheck: { kind:
427
+ // "timed-out", boundMs: its remaining() when the
428
+ // recheck started } }, as 2.1-T4.j reports an
429
+ // aborted rerun
430
+ // The member is then released from D, and the batch continues for the others.
431
+ // - Wording (QA-2.2-9). BATCH_REASONS.beforeRun and .run are 2.1's ABORTED_BEFORE_RUN and
432
+ // ABORTED_DURING_RUN, verbatim. A member cut during the union step gets ABORTED_DURING_RUN
433
+ // even while the union still waits for the slot, where alone it would get slot-busy with
434
+ // deadlineCut (u14, SLOT_DEADLINE_REASON): the scope does not expose when its first execute
435
+ // took the hold, and the union IS the member's scoped run. Both are unverifiable (u13, u14).
436
+ // .window and .attribution have no direct-path equivalent: those waits exist only in a batch.
437
+ // QA-2.2-27 (nit, recorded, not changed): the solo phase it was raised against is gone with
438
+ // QA-2.2-23. The same wording applies to the steps that remain: a member cut while a pooled
439
+ // batch plans its union or waits for its hold (step 3) is still in phase run and gets .run,
440
+ // as during the union run, where alone it would get slot-busy (u14); a member cut while it
441
+ // waits behind the union for its own run (mode B) gets .attribution. A member of a split
442
+ // starts its own run at once, in its batch of one, and so never waits in own-wait. Every
443
+ // one of these outcomes is unverifiable (u13), as the direct path's would be.
444
+ // - When all members have aborted, D aborts. The running execute or rechecker kills its tree
445
+ // (exec.ts), and nothing more is spawned: an aborted signal never spawns. The batch then
446
+ // finishes and closes its scope.
447
+ // - A batch that runs longer than one requester's budget costs that requester an unverifiable
448
+ // verdict at its deadline (2.1-T6 R5 u13, or u6 during the recheck). It never makes the
449
+ // requester wait past its deadline.
450
+ // - QA-2.2-17: under the default policy (strictUnverifiable off) such a verdict is accepted, so
451
+ // the batch must not be what runs a member out of budget. W3 keeps each member's floor and
452
+ // the split schedule ahead of it out of the window wait. B5.2a pools the members only when every member's budget
453
+ // covers the worst-case batched schedule ahead of its recheck; otherwise each runs alone
454
+ // (B5.6). W7 removes the window from a lone request altogether. What remains is an
455
+ // estimate's error (B15).
456
+ //
457
+ // -----------------------------------------------------------------------------------------------
458
+ // B10. SLOT DISCIPLINE (S3, QA-1.4-18)
459
+ //
460
+ // Each batch has one VerificationScope: runtime.openScope of the first member, with that
461
+ // member's cwd and command as meta. The first execute takes the hold. The union run, the own
462
+ // runs and every recheck then run inside it, one command at a time, and close() follows the
463
+ // last of them. The coordinator never opens a scope while it waits on another (no nesting),
464
+ // and no requester's gate waits for a batch's close. Batches for different keys hold separate
465
+ // slots, but only as far as maxConcurrentVerifications allows (W6). A batch never waits for
466
+ // another batch, so batches cannot deadlock each other. A split (B5.6) opens no scope and hands
467
+ // each member to a batch of one, which holds at most one slot, as the member's direct hook
468
+ // would; it never waits for those batches either.
469
+ // Early-settled members (QA-2.2-5, accepted cost). A member settles as soon as its outcome is
470
+ // final (B5.8) while its batch may still hold the slot for the other members' runs and
471
+ // rechecks. Its gate then goes on to its next S3 check (lintClean, run, ...), which opens its
472
+ // own scope and waits for the slot like any other verification: under
473
+ // maxConcurrentVerifications 1 that wait lasts until the batch closes, bounded by the check's
474
+ // slot wait and the gate deadline, so the check can end slot-busy (u14). It cannot deadlock:
475
+ // the batch never waits on a gate or on another scope, a settled member is released from D
476
+ // and never extends it, and every step of the batch is bounded by a remaining member's
477
+ // deadline. Holding the member until the hold ends would spend the same wait inside testsPass
478
+ // instead, and would give back QA-2.2-3's early settlement. 2.2.3's wiring test asserts the
479
+ // behaviour (deferred by plan), with the order forced (QA-2.2-22). QA-2.2-17 revisits the
480
+ // premise: that next check may end slot-busy behind its own batch where alone it could have run
481
+ // and failed. That stays an accepted residual (B15). The wait is bounded by the batch's
482
+ // remaining steps, which B5.2a and W3 already keep within the members' budgets, and a
483
+ // slot-busy check is unverifiable, never a pass.
484
+ //
485
+ // -----------------------------------------------------------------------------------------------
486
+ // B11. MEMORY AND DISPOSAL
487
+ //
488
+ // State:
489
+ // - windows: a Map from key to window, each with <= maxBatchSize members and one timer;
490
+ // - running batches: a Set;
491
+ // - per member: the request, its plan and its resolver;
492
+ // - the last measured run duration per batch key (W3, B5.2a), at most 64 keys (the oldest
493
+ // is dropped), and the number of requests in planning (W7).
494
+ // Everything else is dropped when the member settles or the batch ends. Memory is O(live
495
+ // requests) plus that bounded map, and no window outlives its timer.
496
+ // sweep() is called by the wiring's TTL sweep (2.2.3). It evicts defensively:
497
+ // - windows with no live member;
498
+ // - batches whose members are all settled but whose seam never returned (a hung executor
499
+ // that ignored its signal) for longer than BATCH_STALE_GRACE_MS. D aborted when the last
500
+ // member settled, so the tree was killed that long ago. The coordinator stops tracking the
501
+ // batch and asks its scope to close, which is logged. QA-2.2-19: 2.1's scope closes only
502
+ // once its in-flight seams have returned (deterministic.ts close()), so the slot stays
503
+ // held until the hung seam exits. Nothing else runs beside a tree that may still be alive,
504
+ // which is the safer behaviour, and it is kept.
505
+ // It logs each eviction and returns the number of evictions.
506
+ // The slot is never released before the running tree has exited (QA-2.2-4): runBatch's
507
+ // finally closes the scope after its last seam returned, and an eviction's close waits for
508
+ // the seam too.
509
+ // dispose():
510
+ // 1. marks the coordinator disposed (later requests get B2.1);
511
+ // 2. clears every window timer;
512
+ // 3. settles every pending member with aborted BATCH_REASONS.disposed;
513
+ // 4. aborts every batch deadline, which kills the running trees;
514
+ // 5. awaits every running batch, that is its in-flight seam (the killed tree's exit) and
515
+ // then its scope close, within one grace of BATCH_STALE_GRACE_MS (one timer, cleared
516
+ // after); a batch still running after that is evicted as by sweep();
517
+ // 6. awaits the scope closes within the rest of the same grace (QA-2.2-19). A close still
518
+ // pending after it waits for a hung seam: dispose stops waiting and logs it, and that
519
+ // slot is released when the seam exits.
520
+ // It is idempotent, never rejects, and returns within one grace. The default timers are
521
+ // unref'd, so an open window never keeps the process alive.
522
+ //
523
+ // -----------------------------------------------------------------------------------------------
524
+ // B12. THE EQUIVALENCE PROPERTY AND ITS TEST
525
+ //
526
+ // Statement (B-G1): for any set of requests submitted inside one window, and every member R,
527
+ // judge(coordinator(R)) equals judge(direct(R)) on ok, on unverifiable and on the three
528
+ // FailureClassification sets. direct(R) is the one-request path.
529
+ // It holds under three conditions: the runner is deterministic (each file's outcome does not
530
+ // depend on which other files run), no deadline expires, and there is no slot contention.
531
+ // Timing outcomes (slot-busy, timed-out, aborted, skipped-deadline) are outside it, and so are
532
+ // texts (the count in e1, notes).
533
+ // Test (2.2.2.e, test/unit/batch.test.ts): >= 300 cases from a seeded PRNG (mulberry32, as in
534
+ // test/unit/guards.test.ts).
535
+ // - Fake repo: sources S and test files T; related(s) is a subset of T, and every test file
536
+ // relates to itself. Each test file has a test count >= 0 and a failing set, both now and
537
+ // at each reference; some files are absent at a reference. The runner is vitest-like
538
+ // (related) or pytest-like (inputs are tests). Change sets are random and may overlap.
539
+ // References are random too: shared or distinct, captured, none or disabled.
540
+ // - Fake seams, each counting its calls:
541
+ // plan: inputs = the existing changed files; S6 for a trigger file; NoAffected for none.
542
+ // openScope: execute returns the model's RunResult, applies readResult's zero-test guard
543
+ // and fills testsByFile; rechecker returns exact/absent/ran from the model.
544
+ // - direct(R) is the test's own one-request path over the same seams.
545
+ // - judge: until 2.2.3, an oracle of 2.1-T5/T6 written in the test; from 2.2.3 on, 2.1's
546
+ // judgeScoped as well, and both must agree.
547
+ // - Each case asserts: equal judgements; exactly one scope per batch; spawns within the
548
+ // cost model (B13); no leaked timers after dispose (vi.getTimerCount() === 0).
549
+ // A flaky variant adds a failure that appears only in the union run, and asserts B-G2: no
550
+ // member judges ok.
551
+ //
552
+ // -----------------------------------------------------------------------------------------------
553
+ // B13. COST MODEL (spawns through the argv seam, per window of n members)
554
+ //
555
+ // green union, P1 present 1 scoped run, +1 for each zero-test-ambiguous member (7.2b)
556
+ // green union, P1 absent 1 + the number of guard-sensitive members
557
+ // pytest, failing, report complete 1 scoped run; rechecks spawn nothing (runner-unsupported)
558
+ // vitest/jest, failing 1 + n scoped runs (mode B), + 1 recheck per distinct
559
+ // reference among the failing members when later members'
560
+ // files are covered (B8.6), else up to 1 per member
561
+ // split (union inconsistent, or n scoped runs and n scopes, as without batching (B5.6)
562
+ // the B5.2a deadline check)
563
+ // n = 1 exactly the direct path (W7: no window wait when alone)
564
+ // The plan's acceptance criterion, "<= 1 scoped run + <= 1 recheck per window", is asserted on
565
+ // the green and pytest paths and with a shared reference. On the vitest/jest failing path the
566
+ // test asserts 1 + n runs and one recheck per distinct reference (deviation D2).
567
+ //
568
+ // -----------------------------------------------------------------------------------------------
569
+ // B14. DEVIATIONS FROM THE PLAN
570
+ //
571
+ // D1 The batch key adds file, cwd and the argv template (B3).
572
+ // D2 On a failing vitest/jest union, mode B spends n attribution runs, so the plan's "<= 1
573
+ // scoped run per window" holds on the green and static paths only. Mode B's per-request run
574
+ // is the request's own planScopedRun spec, not "only the failing files": `related` cannot
575
+ // be intersected with a file filter (runner.ts J).
576
+ // D3 One shared recheck per distinct reference, not one per batch (B8.2).
577
+ // D4 The maximum window size is a coordinator option (BATCH_MAX_REQUESTS = 8), not a config
578
+ // key. config.ts and the section 1.4 surface are outside 2.2's write set, and the value
579
+ // only bounds the worst-case slot hold (1 + 8 runs).
580
+ // D5 A guard-sensitive member of a green batch needs per-file counts (P1, runner.ts) or a
581
+ // confirmation run.
582
+ // D6 One coordinator exists per plugin instance, but it receives its runtime per gate
583
+ // (hook(runtime)). A config reload therefore reaches new windows without a new coordinator.
584
+ //
585
+ // -----------------------------------------------------------------------------------------------
586
+ // B15. RESIDUAL RISKS (accepted; QA may challenge)
587
+ //
588
+ // - Cross-file state. pytest runs all of the union's files in one process, so a test that
589
+ // pollutes another file's state can change outcomes compared with a run alone. vitest and
590
+ // jest isolate each file by default; a config that turns isolation off carries the same
591
+ // risk. A failure caused by pollution makes the member unverifiable, because pytest failures
592
+ // are never proven introduced (2.1 decision 5). Pollution that hides a failure is a risk the
593
+ // user's own suite run has too.
594
+ // - Flaky tests on the own-run path. A failure that appears only in a member's own run is
595
+ // judged exactly as it would be alone (2.1-T11's flaky row).
596
+ // - Distinct stash commits never share a recheck, even when their trees are identical. A
597
+ // tree-hash key would need git at capture time, which is out of scope.
598
+ // - A config reload in the middle of a window keeps the opener's window length and scope
599
+ // options.
600
+ // - Deadline estimates (QA-2.2-17, B-G7). W3 and B5.2a rely on the key's last measured run
601
+ // duration, with a recheck estimated as one more run and a union as one run per member.
602
+ // - Before the first measured run of a key in a plugin instance, e is 0: the first
603
+ // concurrent window of a key pools any member that has its floor, and a failing
604
+ // vitest/jest union can still cost a tight member its recheck there (the QA's R5 with
605
+ // every gate in one window). A lone gate (W7), or any earlier batch of the key, measures
606
+ // e. The first window of a key was not made to split by default: that would give up the
607
+ // saving of every first fan-out.
608
+ // - A member's own run slower than the last measured run, or a recheck slower than a run
609
+ // (materialize), can exceed the estimate by more than BATCH_RESERVE_MARGIN_MS.
610
+ // - The first run of a scope includes its slot wait. That only overstates e, and costs
611
+ // batching, not verdicts, until the next measurement. A union's run also measures e, and
612
+ // a union is at least as long as one own run, so it too only overstates it.
613
+ // - Union planning and the union's slot wait are bounded by D' (B5.2a); a planner step that
614
+ // does not honour its deadline's bound can still overrun it, and the check after planning
615
+ // then splits a batch that is already late.
616
+ // - The window itself (W3). Under a first-come slot, a request that queues while a member waits
617
+ // in its window is served before that member, where the member's direct hook would have
618
+ // queued first. W3 keeps the member's split schedule out of the wait, but not the runs of such
619
+ // later requests. The wait is bounded by batchWindowMs (at most a tenth of the gate budget,
620
+ // QA-2.2-21), and W7 removes it when nothing else is in flight in the coordinator.
621
+ // - Serial runs under one hold. With maxConcurrentVerifications > 1, the direct path could run
622
+ // members in parallel where a batch runs their own runs and rechecks one at a time. B5.2a
623
+ // pools only when each member's worst case fits its own budget, whatever the slot count, and
624
+ // a split runs every member in its own scope, in parallel as far as the slots allow.
625
+ // - QA-2.2-5 (B10): an early-settled member's next S3 check may end slot-busy behind its own
626
+ // batch where alone it could have run.
627
+ //
628
+ // -----------------------------------------------------------------------------------------------
629
+ // B16. IMPLEMENTATION TASKS (each <= ~20 tool calls; commit and push each one green)
630
+ //
631
+ // 2.2.2 runs on vrb/p22, in parallel with 2.1.2-2.1.6. It does not touch wiring.ts, index.ts or
632
+ // deterministic.ts. Tests run scoped: npx vitest run test/unit/batch.test.ts.
633
+ // 2.2.2.a runner.ts P1, only with the orchestrator's approval of the write-set addition;
634
+ // otherwise skip it and keep the confirmation-run path. readResult fills
635
+ // RunResult.testsByFile for JSON and junit reports. Tests in test/unit/runner.test.ts
636
+ // on the Spike C reports in test/fixtures/runner/reports: the sum equals total, the
637
+ // text fallback leaves it undefined, and pytest pseudo-cases are excluded.
638
+ // 2.2.2.b batch.ts pure helpers: envSignature, argvTemplate, batchKey, referenceKey,
639
+ // unionChangedFiles, isGuardSensitive, fileKeyOf, attributeUnion, deriveSharedRecheck,
640
+ // taintUnreproduced and createBatchDeadline. Table tests for each:
641
+ // - win32 and posix keys;
642
+ // - relative ChangedPath resolution;
643
+ // - every attributeUnion row;
644
+ // - every deriveSharedRecheck kind and cause;
645
+ // - D's release, abort and dispose, with no listener left behind.
646
+ // 2.2.2.c createBatchCoordinator core: B2 bypasses, W1-W6, B5 steps 1-4 and 6, B9 and B11, with
647
+ // injected timers and clock. Tests (fake timers):
648
+ // - 5 requests -> 1 union run and 5 results;
649
+ // - different keys -> separate scopes;
650
+ // - window 0 -> direct;
651
+ // - an arrival during a running batch -> the next window;
652
+ // - max size closes the window early; so does W3;
653
+ // - an abort in the window;
654
+ // - one member aborts mid-run -> the others still get results;
655
+ // - all abort -> the execute seam sees an aborted signal, and nothing is spawned
656
+ // afterwards;
657
+ // - dispose -> 0 timers, pending requests settled;
658
+ // - the hook never rejects when a seam throws.
659
+ // 2.2.2.d attribution and recheck: B5 steps 5 and 7-9, B7 and B8. Tests:
660
+ // - the union fails in a file of one member -> only that member's own run fails;
661
+ // - a failing file shared by two members -> both are rechecked;
662
+ // - a pre-existing failure shared by all members with one reference -> one recheck,
663
+ // and every member derives "exact";
664
+ // - distinct references -> one recheck each;
665
+ // - a run-level unusable recheck -> split;
666
+ // - skipped-deadline below the threshold;
667
+ // - the flaky taint;
668
+ // - pytest static attribution, with and without counts;
669
+ // - deduplication of an overlapping change set.
670
+ // 2.2.2.e the property test (B12), coverage >= 90% of batch.ts lines and branches, and the QA
671
+ // report section in phase-2.2.md.
672
+ // 2.2.3 starts after 2.1 is merged into vrb/wave-2. It writes wiring.ts, whose only writer it is
673
+ // at that point.
674
+ // 2.2.3.a wiring.ts:
675
+ // - one coordinator per plugin instance (createBatchCoordinator);
676
+ // - per gate, runtime = {
677
+ // direct: 2.1's createDirectTestsPassHook(...),
678
+ // plan: planScopedRun with the gate's PlannerFs, a TestSearchSeam bound to the
679
+ // given deadline, the budget and the host,
680
+ // openScope: 2.1's scope opener,
681
+ // batchWindowMs: budget.batchWindowMs,
682
+ // recheckMinRemainingMs: RECHECK_MIN_REMAINING_MS };
683
+ // - buildGateDeps' testsPass hook becomes coordinator.hook(runtime);
684
+ // - the existing TTL sweep also calls coordinator.sweep();
685
+ // - plugin disposal, if the host offers one, calls dispose().
686
+ // batch.ts: replace the private idFileKey with 2.1's fileKeyOfId.
687
+ // Done (2.2.3): wiring.ts creates the coordinator in createVerificationWiring. With
688
+ // batchWindowMs > 0, buildGateDeps' testsPass is coordinator.hook(runtime), and 2.1's
689
+ // direct hook stays as runtime.direct; with batchWindowMs <= 0 the direct hook is used
690
+ // as is. The runtime shares the direct hook's opener, PlannerFs and budget, and adds
691
+ // the gate-time failureRecheck and the gate's tree (QA-2.2-8: BatchRuntime.currentTree,
692
+ // OpenBatchScope). index.ts's idle-TTL sweeper calls sweepVerification() (the
693
+ // coordinator's sweep), and plugin dispose awaits disposeVerification().
694
+ // QA-2.2-21: the runtime's batchWindowMs is effectiveBatchWindowMs(budget), that is
695
+ // min(batchWindowMs, gateBudgetMs / 10): 2000 ms at the defaults.
696
+ // 2.2.3.b test/unit/batch-wiring.test.ts, with 5 concurrent testsPass gates through
697
+ // buildGateDeps:
698
+ // - the argv seam sees 1 scoped run per window (+ <= 1 recheck with a shared
699
+ // reference) on the green and pytest paths, and 1 + n on the vitest failing path;
700
+ // - verdicts equal those with batchWindowMs: 0;
701
+ // - the B12 property with 2.1's judgeScoped next to the oracle;
702
+ // - one slot acquisition per batch, never nested.
703
+ // ===============================================================================================
704
+
705
+ import { posix, win32 } from "node:path";
706
+ import type { PluginLogger } from "../router/logger";
707
+ import { fileKeyOfId } from "./baseline";
708
+ import type { TreeSnapshot } from "./dispatch";
709
+ import type { DispatchReference } from "./reference";
710
+ import type { ChangedPath, RunResult, ScopedSpec, ScopingPlan } from "./runner";
711
+ import type {
712
+ Deadline,
713
+ OpenVerificationScope,
714
+ Rechecker,
715
+ RecheckOutcome,
716
+ ScopedOutcome,
717
+ TestsPassHook,
718
+ TestsPassRequest,
719
+ TestsPassRun,
720
+ VerificationScope,
721
+ } from "./types";
722
+
723
+ // ---------------------------------------------------------------------------------------------
724
+ // Constants
725
+ // ---------------------------------------------------------------------------------------------
726
+
727
+ /** W2: the default maximum number of members in one window (deviation D4). */
728
+ export const BATCH_MAX_REQUESTS = 8;
729
+
730
+ /** B11: how long sweep() tolerates a batch whose members are all settled but whose seam never returned. */
731
+ export const BATCH_STALE_GRACE_MS = 60_000;
732
+
733
+ /**
734
+ * W3 and B5.2a (QA-2.2-17): the margin a member keeps on top of its recheck threshold and the
735
+ * key's run estimate. It covers union planning and scheduling, the overhead the batch adds.
736
+ */
737
+ export const BATCH_RESERVE_MARGIN_MS = 1_000;
738
+
739
+ /** B11: at most this many batch keys keep a measured run duration (the oldest is dropped). */
740
+ const DURATION_KEYS_MAX = 64;
741
+
742
+ /**
743
+ * Stable ScopedOutcome "aborted" reasons (B2, B9). They reach the orchestrator through 2.1-T7 u13.
744
+ * beforeRun and run are 2.1's ABORTED_BEFORE_RUN and ABORTED_DURING_RUN, verbatim (QA-2.2-9).
745
+ */
746
+ export const BATCH_REASONS = {
747
+ disposed: "verification coordinator disposed",
748
+ beforeRun: "gate budget exhausted before the scoped run",
749
+ window: "gate budget exhausted waiting for the batch window",
750
+ run: "gate budget exhausted during the scoped run",
751
+ attribution: "gate budget exhausted during batch attribution",
752
+ } as const;
753
+
754
+ // ---------------------------------------------------------------------------------------------
755
+ // Contract
756
+ // ---------------------------------------------------------------------------------------------
757
+
758
+ /** What the planner needs from a request (B2.5, B6). */
759
+ export type BatchPlanInput = Pick<TestsPassRequest, "command" | "cwd" | "changedFiles">;
760
+
761
+ /**
762
+ * planScopedRun bound to one deadline. The wiring (2.2.3) supplies the PlannerFs with the native
763
+ * realpath, a TestSearchSeam whose calls use deadline.bound(10_000) and deadline.signal, the
764
+ * RunnerBudget and the host. It may reject; the coordinator turns a rejection into a ScopedOutcome
765
+ * "error" (B2.5).
766
+ */
767
+ export type BatchPlanner = (input: BatchPlanInput, deadline: Deadline) => Promise<ScopingPlan>;
768
+
769
+ /**
770
+ * A VerificationScope whose rechecker also takes the gate's current tree snapshot, as 2.1's
771
+ * CheckScope does (QA-2.2-8). A two-argument rechecker (any OpenVerificationScope) still fits.
772
+ */
773
+ export interface BatchScope extends VerificationScope {
774
+ rechecker(command: string, cwd: string, currentTree?: TreeSnapshot): Rechecker;
775
+ /**
776
+ * 2.1's CheckScope.hold: the scope's one hold, taken without running anything; true when held
777
+ * (B5.3, QA-2.2-25). A scope without it takes its hold on the union's execute, under D.
778
+ */
779
+ hold?(deadline: Deadline): Promise<boolean>;
780
+ }
781
+
782
+ /** runtime.openScope: 2.1's scope opener, or any OpenVerificationScope. */
783
+ export type OpenBatchScope = (meta: Parameters<OpenVerificationScope>[0]) => BatchScope;
784
+
785
+ /** The seams and settings of one gate (deviation D6). The window opener's values apply to its batch. */
786
+ export interface BatchRuntime {
787
+ /** 2.1's one-request hook, used for testScope "full" and batchWindowMs <= 0 (B2). */
788
+ readonly direct: TestsPassHook;
789
+ readonly plan: BatchPlanner;
790
+ readonly openScope: OpenBatchScope;
791
+ /** enforcement.verify.batchWindowMs (VerifyBudget). <= 0 disables batching. */
792
+ readonly batchWindowMs: number;
793
+ /** 2.1's RECHECK_MIN_REMAINING_MS (B8.3), injected so this module has no runtime import of deterministic.ts. */
794
+ readonly recheckMinRemainingMs: number;
795
+ /**
796
+ * The gate-time enforcement.verify.failureRecheck (VerifyBudget), read per request (B8.1,
797
+ * QA-2.2-2): off turns every reference, even a captured one, into "disabled", exactly as 2.1's
798
+ * direct hook decides at the gate.
799
+ */
800
+ readonly failureRecheck: boolean;
801
+ /**
802
+ * QA-2.2-8 (2.2.3): the submitting gate's current tree snapshot, kept per request and forwarded
803
+ * to its recheck as 2.1's direct hook does (materialize's same-repository guard). A shared
804
+ * recheck forwards its first member's, with that member's command and cwd: every member of a
805
+ * group shares the reference, and so its root (B8.2). Absent: materialize gets undefined.
806
+ */
807
+ readonly currentTree?: TreeSnapshot;
808
+ }
809
+
810
+ /** Timer seam for the window timers (W1). */
811
+ export interface BatchTimers {
812
+ setTimeout(callback: () => void, ms: number): unknown;
813
+ clearTimeout(handle: unknown): void;
814
+ }
815
+
816
+ export interface BatchCoordinatorOptions {
817
+ /** W2. Default BATCH_MAX_REQUESTS; a value that is not a safe integer >= 1 means 1 (no batching). */
818
+ readonly maxBatchSize?: number;
819
+ /** Path-key folding (case-insensitive on win32). Default: process.platform. */
820
+ readonly platform?: NodeJS.Platform;
821
+ /** Clock for W3 and B11. Default: Date.now. */
822
+ readonly now?: () => number;
823
+ /** Default: the global setTimeout/clearTimeout, with each handle unref'd (B11). */
824
+ readonly timers?: BatchTimers;
825
+ /** A logger whose warn throws is dropped for the coordinator's life (B-G5, QA-2.2-10). */
826
+ readonly logger?: Pick<PluginLogger, "warn">;
827
+ /**
828
+ * W7 (QA-2.2-17 a). Default true: a window closes as soon as nothing else is in flight in the
829
+ * coordinator. false keeps only the timed close, for tests of the W1-W6 mechanics.
830
+ */
831
+ readonly idleClose?: boolean;
832
+ }
833
+
834
+ /** Live state and cumulative counters, for tests and QA (B11, B13). */
835
+ export interface BatchStats {
836
+ readonly openWindows: number;
837
+ readonly runningBatches: number;
838
+ /** Requests submitted to a window and not yet settled. */
839
+ readonly pendingRequests: number;
840
+ /** Cumulative since creation. */
841
+ readonly unionRuns: number;
842
+ readonly ownRuns: number;
843
+ readonly rechecks: number;
844
+ readonly splits: number;
845
+ readonly taints: number;
846
+ }
847
+
848
+ export interface BatchCoordinator {
849
+ /** The S5 hook for one gate's runtime. It is exactly a TestsPassHook and never rejects (B-G5). */
850
+ hook(runtime: BatchRuntime): TestsPassHook;
851
+ /** B11 defensive eviction. Returns the number of windows and batches evicted. */
852
+ sweep(): number;
853
+ stats(): BatchStats;
854
+ /** B11. Idempotent; never rejects. */
855
+ dispose(): Promise<void>;
856
+ }
857
+
858
+ // ---------------------------------------------------------------------------------------------
859
+ // Coordinator (tasks 2.2.2.c and 2.2.2.d)
860
+ // ---------------------------------------------------------------------------------------------
861
+
862
+ /**
863
+ * Where a member stands; B9's table maps each phase to what an abort settles it with.
864
+ * window waiting in a window (W5);
865
+ * run union planning or the union run (B5 steps 2-4);
866
+ * own-wait queued for its own run (B5.5);
867
+ * own-run its own run is running: the executor kills it and reports (B9);
868
+ * held its outcome is known but a union failure is still unexplained (B5.7);
869
+ * recheck-wait its outcome is final and it waits for its recheck turn (B5.8);
870
+ * recheck its recheck is running (B8).
871
+ */
872
+ type MemberPhase = "window" | "run" | "own-wait" | "own-run" | "held" | "recheck-wait" | "recheck";
873
+
874
+ type RanOutcome = Extract<ScopedOutcome, { readonly kind: "ran" }>;
875
+
876
+ /** A member whose final outcome waits for a recheck at a captured reference (B5.8). */
877
+ interface Ready {
878
+ readonly scoped: RanOutcome;
879
+ readonly reference: DispatchReference;
880
+ /** referenceKey(reference): the group and the reuse key (B8.2, B8.6). */
881
+ readonly key: string;
882
+ }
883
+
884
+ interface Member {
885
+ readonly request: TestsPassRequest;
886
+ /** The submitting gate's runtime: a member that runs alone (B5.6) runs with it, as its direct hook would. */
887
+ readonly runtime: BatchRuntime;
888
+ /** The member's own planScopedRun spec. */
889
+ readonly spec: ScopedSpec;
890
+ /** B8.1 (QA-2.2-2): the submitting gate's runtime.failureRecheck, not the window opener's. */
891
+ readonly failureRecheck: boolean;
892
+ /** QA-2.2-8: the submitting gate's runtime.currentTree, forwarded to the member's recheck. */
893
+ readonly currentTree: TreeSnapshot | undefined;
894
+ /** W3 (QA-2.2-17): the submitting gate's runtime.recheckMinRemainingMs, for its reserve. */
895
+ readonly recheckMinRemainingMs: number;
896
+ /** Arrival order: the tie-break of every deadline ordering, and the order of a split (B5.6). */
897
+ readonly seq: number;
898
+ phase: MemberPhase;
899
+ settled: boolean;
900
+ window: BatchWindow | undefined;
901
+ batch: Batch | undefined;
902
+ /** The member's scoped outcome once known (B5 steps 4-7). */
903
+ scoped: ScopedOutcome | undefined;
904
+ /** Set in phase recheck-wait (B5.8). */
905
+ ready: Ready | undefined;
906
+ /** B9: its remaining() when its recheck started, reported if it aborts while it runs. */
907
+ recheckBoundMs: number;
908
+ readonly resolve: (run: TestsPassRun) => void;
909
+ readonly onAbort: () => void;
910
+ }
911
+
912
+ interface BatchWindow {
913
+ readonly key: string;
914
+ /** The opener's runtime (W1, D6). */
915
+ readonly runtime: BatchRuntime;
916
+ /** Set at opening (W1). It never moves later (W2); a member's reserve can move it earlier (W3). */
917
+ closeAt: number;
918
+ readonly members: Member[];
919
+ timer: unknown;
920
+ closed: boolean;
921
+ }
922
+
923
+ interface Batch {
924
+ readonly key: string;
925
+ readonly runtime: BatchRuntime;
926
+ /** Fixed at close, in arrival order (W4). */
927
+ readonly members: readonly Member[];
928
+ /** D (B9). */
929
+ readonly deadline: BatchDeadline;
930
+ /** Rg of the shared recheck in flight (B8.5). */
931
+ group: BatchDeadline | undefined;
932
+ scope: BatchScope | undefined;
933
+ closing: Promise<void> | undefined;
934
+ /** When the last member settled (B11 sweep). */
935
+ settledAt: number | undefined;
936
+ /** B7.5: the failing ids of a "ran" union; empty when the union was green or did not run. */
937
+ unionIds: readonly string[];
938
+ /** B7.5: union ids some finished own run or static derivation reproduces (it only grows). */
939
+ readonly reproduced: Set<string>;
940
+ /** B5.7: no taint can change a member's outcome anymore. */
941
+ final: boolean;
942
+ /** B8.6: recheck outcomes that hold for any member at the same reference, by referenceKey. */
943
+ readonly rechecked: Map<string, RecheckOutcome[]>;
944
+ /** runBatch's promise: it ends after the last seam returned, and closes the scope (B11, QA-2.2-4). */
945
+ run: Promise<void> | undefined;
946
+ }
947
+
948
+ function message(e: unknown): string {
949
+ return e instanceof Error ? e.message : String(e);
950
+ }
951
+
952
+ function abortedRun(reason: string): TestsPassRun {
953
+ return { scoped: { kind: "aborted", reason }, recheck: undefined };
954
+ }
955
+
956
+ function errorRun(reason: string): TestsPassRun {
957
+ return { scoped: { kind: "error", reason }, recheck: undefined };
958
+ }
959
+
960
+ /** 2.1-T2 P7: a recheck is attempted for a "ran" outcome with >= 1 failing id and >= 1 failing file. */
961
+ function needsRecheck(scoped: ScopedOutcome): scoped is RanOutcome {
962
+ return scoped.kind === "ran" && scoped.result.failingIds.length > 0 && scoped.result.failingFiles.length > 0;
963
+ }
964
+
965
+ /** Deadline order (B5.5, B8.3): the least remaining first, then arrival order. */
966
+ function byDeadline(a: Member, b: Member): number {
967
+ return a.request.deadline.remaining() - b.request.deadline.remaining() || a.seq - b.seq;
968
+ }
969
+
970
+ /**
971
+ * A member's own deadline that also aborts with `kill` (the batch deadline D, which aborts at
972
+ * dispose or when every member is gone), so that dispose() kills own runs and single rechecks too
973
+ * (B11.4). While the member is attached to D, D aborts only at dispose or after the member's own
974
+ * signal, so the result bounds exactly as the member's deadline alone.
975
+ */
976
+ function linkDeadline(base: Deadline, kill: AbortSignal): { readonly deadline: Deadline; unlink(): void } {
977
+ const controller = new AbortController();
978
+ const onAbort = () => {
979
+ unlink();
980
+ controller.abort();
981
+ };
982
+ const unlink = () => {
983
+ base.signal.removeEventListener("abort", onAbort);
984
+ kill.removeEventListener("abort", onAbort);
985
+ };
986
+ if (base.signal.aborted || kill.aborted) controller.abort();
987
+ else {
988
+ base.signal.addEventListener("abort", onAbort, { once: true });
989
+ kill.addEventListener("abort", onAbort, { once: true });
990
+ }
991
+ const remaining = () => (controller.signal.aborted ? 0 : base.remaining());
992
+ return {
993
+ deadline: { budgetMs: base.budgetMs, remaining, bound: (ownBudgetMs) => Math.min(ownBudgetMs, remaining()), signal: controller.signal },
994
+ unlink,
995
+ };
996
+ }
997
+
998
+ /** B11: the global timers, each handle unref'd so that an open window never keeps the process alive. */
999
+ const defaultTimers: BatchTimers = {
1000
+ setTimeout(callback, ms) {
1001
+ const handle = setTimeout(callback, ms);
1002
+ handle.unref();
1003
+ return handle;
1004
+ },
1005
+ clearTimeout(handle) {
1006
+ clearTimeout(handle as Parameters<typeof clearTimeout>[0]);
1007
+ },
1008
+ };
1009
+
1010
+ /** One coordinator per plugin instance (2.2.3). */
1011
+ export function createBatchCoordinator(options: BatchCoordinatorOptions = {}): BatchCoordinator {
1012
+ const requestedSize = options.maxBatchSize ?? BATCH_MAX_REQUESTS;
1013
+ const maxBatchSize = Number.isSafeInteger(requestedSize) && requestedSize >= 1 ? requestedSize : 1;
1014
+ const platform = options.platform ?? process.platform;
1015
+ const now = options.now ?? (() => Date.now());
1016
+ const timers = options.timers ?? defaultTimers;
1017
+ const idleClose = options.idleClose ?? true;
1018
+ let logger = options.logger;
1019
+
1020
+ const windows = new Map<string, BatchWindow>();
1021
+ const running = new Set<Batch>();
1022
+ const closing = new Set<Promise<void>>();
1023
+ /** QA-2.2-17: the last measured scoped-run duration of each batch key (bounded, B11). */
1024
+ const durations = new Map<string, number>();
1025
+ const counters = { unionRuns: 0, ownRuns: 0, rechecks: 0, splits: 0, taints: 0 };
1026
+ let disposed = false;
1027
+ let pending = 0;
1028
+ let arrivals = 0;
1029
+ /** W7: requests between arrival and their window (or their planning outcome). */
1030
+ let planning = 0;
1031
+
1032
+ /**
1033
+ * B-G5 (QA-2.2-10): logging never throws into the coordinator. A logger that throws is dropped
1034
+ * for the coordinator's life, so it cannot reject runBatch, a scope close or dispose().
1035
+ */
1036
+ const warn = (text: string, extra?: Record<string, unknown>): void => {
1037
+ const current = logger;
1038
+ if (current === undefined) return;
1039
+ try {
1040
+ current.warn(text, extra);
1041
+ } catch {
1042
+ logger = undefined;
1043
+ }
1044
+ };
1045
+ /** The members a batch still answers for: a split (B5.6) hands each member to a batch of its own. */
1046
+ const live = (b: Batch) => b.members.filter((m) => !m.settled && m.batch === b);
1047
+
1048
+ // -- settlement ------------------------------------------------------------------------------
1049
+
1050
+ function settle(m: Member, run: TestsPassRun): void {
1051
+ if (m.settled) return;
1052
+ m.settled = true;
1053
+ pending--;
1054
+ m.request.deadline.signal.removeEventListener("abort", m.onAbort);
1055
+ const b = m.batch;
1056
+ if (b !== undefined) {
1057
+ // B9: a settled member no longer keeps the batch alive. Two members may share one Deadline
1058
+ // (one router_verify call naming several handles): it is released with the last of them.
1059
+ const deadline = m.request.deadline;
1060
+ if (!b.members.some((x) => !x.settled && x.request.deadline === deadline)) {
1061
+ b.group?.release(deadline);
1062
+ b.deadline.release(deadline);
1063
+ }
1064
+ if (b.members.every((x) => x.settled)) b.settledAt = now();
1065
+ }
1066
+ m.resolve(run);
1067
+ }
1068
+
1069
+ /** B9's table. */
1070
+ function onAbort(m: Member): void {
1071
+ if (m.settled) return;
1072
+ switch (m.phase) {
1073
+ case "window":
1074
+ leaveWindow(m);
1075
+ settle(m, abortedRun(BATCH_REASONS.window));
1076
+ return;
1077
+ case "run":
1078
+ settle(m, abortedRun(BATCH_REASONS.run));
1079
+ return;
1080
+ case "own-wait":
1081
+ settle(m, abortedRun(BATCH_REASONS.attribution));
1082
+ return;
1083
+ case "own-run":
1084
+ // The executor kills the run on the member's signal and reports it (runOwn settles).
1085
+ return;
1086
+ case "held":
1087
+ case "recheck-wait":
1088
+ // QA-2.2-3: its outcome is known, so it is never reported as a bare abort.
1089
+ if (m.batch !== undefined) settleLate(m.batch, m);
1090
+ return;
1091
+ case "recheck":
1092
+ if (m.ready !== undefined) settle(m, { scoped: m.ready.scoped, recheck: { kind: "timed-out", boundMs: m.recheckBoundMs } });
1093
+ return;
1094
+ }
1095
+ }
1096
+
1097
+ // -- windows (B4) ----------------------------------------------------------------------------
1098
+
1099
+ function leaveWindow(m: Member): void {
1100
+ const w = m.window;
1101
+ if (w === undefined) return;
1102
+ m.window = undefined;
1103
+ const i = w.members.indexOf(m);
1104
+ if (i >= 0) w.members.splice(i, 1);
1105
+ // W5: a window left empty clears its timer and is deleted.
1106
+ if (w.members.length === 0 && !w.closed) {
1107
+ w.closed = true;
1108
+ timers.clearTimeout(w.timer);
1109
+ if (windows.get(w.key) === w) windows.delete(w.key);
1110
+ }
1111
+ }
1112
+
1113
+ /** QA-2.2-17: the key's last measured scoped-run duration, 0 before the first. */
1114
+ function estimate(key: string): number {
1115
+ return durations.get(key) ?? 0;
1116
+ }
1117
+
1118
+ /** Records a run's duration and applies the new estimate to the key's open window (W3). */
1119
+ function noteDuration(key: string, ms: number): void {
1120
+ durations.delete(key);
1121
+ durations.set(key, Math.max(0, ms));
1122
+ if (durations.size > DURATION_KEYS_MAX) {
1123
+ const oldest = durations.keys().next();
1124
+ if (oldest.done !== true) durations.delete(oldest.value);
1125
+ }
1126
+ const w = windows.get(key);
1127
+ if (w !== undefined) fitWindow(w);
1128
+ }
1129
+
1130
+ /**
1131
+ * W3 (QA-2.2-17 b): what a member keeps besides its runs: its recheck threshold when it can
1132
+ * recheck at all (failureRecheck on and a captured reference), plus BATCH_RESERVE_MARGIN_MS.
1133
+ */
1134
+ function floorOf(m: Member): number {
1135
+ const rechecks = m.failureRecheck && m.request.reference.kind === "captured";
1136
+ return (rechecks ? m.recheckMinRemainingMs : 0) + BATCH_RESERVE_MARGIN_MS;
1137
+ }
1138
+
1139
+ /**
1140
+ * W3 (QA-2.2-17 b, QA-2.2-24): the window closes no later than the moment some member would be
1141
+ * left with less than the schedule it may then run: a split (B5.6) where, on one slot, every
1142
+ * member that joined before it runs and rechecks first. For the member at arrival index k that
1143
+ * is its floor plus e x (2k + 1). The close time only ever moves earlier (W2).
1144
+ */
1145
+ function fitWindow(w: BatchWindow): void {
1146
+ if (w.closed) return;
1147
+ const t = now();
1148
+ const e = estimate(w.key);
1149
+ let closeAt = w.closeAt;
1150
+ let k = 0;
1151
+ for (const m of w.members) {
1152
+ if (m.settled) continue;
1153
+ closeAt = Math.min(closeAt, t + m.request.deadline.remaining() - floorOf(m) - e * (2 * k + 1));
1154
+ k++;
1155
+ }
1156
+ if (closeAt <= t) {
1157
+ closeWindow(w);
1158
+ return;
1159
+ }
1160
+ if (closeAt >= w.closeAt) return;
1161
+ w.closeAt = closeAt;
1162
+ timers.clearTimeout(w.timer);
1163
+ w.timer = timers.setTimeout(() => closeWindow(w), closeAt - t);
1164
+ }
1165
+
1166
+ /**
1167
+ * W7 (QA-2.2-17 a, QA-2.2-18): when no request is planning and no batch is running, nothing
1168
+ * can join an open window and the slot is free, so every open window closes now. A lone request
1169
+ * therefore never waits; requests that arrive while a batch runs gather in the next window.
1170
+ */
1171
+ function closeIdle(): void {
1172
+ if (!idleClose || planning > 0 || running.size > 0) return;
1173
+ for (const w of [...windows.values()]) closeWindow(w);
1174
+ }
1175
+
1176
+ function join(runtime: BatchRuntime, request: TestsPassRequest, spec: ScopedSpec): Promise<TestsPassRun> {
1177
+ const key = batchKey(spec, platform);
1178
+ return new Promise<TestsPassRun>((resolve) => {
1179
+ const member: Member = {
1180
+ request,
1181
+ runtime,
1182
+ spec,
1183
+ failureRecheck: runtime.failureRecheck,
1184
+ currentTree: runtime.currentTree,
1185
+ recheckMinRemainingMs: runtime.recheckMinRemainingMs,
1186
+ seq: arrivals++,
1187
+ phase: "window",
1188
+ settled: false,
1189
+ window: undefined,
1190
+ batch: undefined,
1191
+ scoped: undefined,
1192
+ ready: undefined,
1193
+ recheckBoundMs: 0,
1194
+ resolve,
1195
+ onAbort: () => onAbort(member),
1196
+ };
1197
+ let w = windows.get(key);
1198
+ if (w === undefined) {
1199
+ // W1: the close time is fixed now, with the opener's window length.
1200
+ const opened: BatchWindow = { key, runtime, closeAt: now() + runtime.batchWindowMs, members: [], timer: undefined, closed: false };
1201
+ opened.timer = timers.setTimeout(() => closeWindow(opened), runtime.batchWindowMs);
1202
+ windows.set(key, opened);
1203
+ w = opened;
1204
+ }
1205
+ member.window = w;
1206
+ w.members.push(member);
1207
+ pending++;
1208
+ request.deadline.signal.addEventListener("abort", member.onAbort, { once: true });
1209
+ // W2 (size), W3 (the members' reserves) and W7 (nothing else in flight).
1210
+ if (w.members.length >= maxBatchSize) closeWindow(w);
1211
+ else fitWindow(w);
1212
+ closeIdle();
1213
+ });
1214
+ }
1215
+
1216
+ /** W2, W4: close, leave the key map before anything asynchronous, and start the batch. */
1217
+ function closeWindow(w: BatchWindow): void {
1218
+ if (w.closed) return;
1219
+ w.closed = true;
1220
+ timers.clearTimeout(w.timer);
1221
+ if (windows.get(w.key) === w) windows.delete(w.key);
1222
+ const members = w.members.filter((m) => !m.settled);
1223
+ if (members.length === 0) return;
1224
+ startBatch(w.key, w.runtime, members);
1225
+ }
1226
+
1227
+ /** A batch over `members` (W4), or a member's batch of one (B5.1, B5.6). */
1228
+ function startBatch(key: string, runtime: BatchRuntime, members: readonly Member[]): void {
1229
+ const b: Batch = {
1230
+ key,
1231
+ runtime,
1232
+ members,
1233
+ deadline: createBatchDeadline(members.map((m) => m.request.deadline)),
1234
+ group: undefined,
1235
+ scope: undefined,
1236
+ closing: undefined,
1237
+ settledAt: undefined,
1238
+ unionIds: [],
1239
+ reproduced: new Set(),
1240
+ final: false,
1241
+ rechecked: new Map(),
1242
+ run: undefined,
1243
+ };
1244
+ for (const m of members) {
1245
+ m.window = undefined;
1246
+ m.batch = b;
1247
+ // B5.1: a batch of one runs the member's own spec at once.
1248
+ m.phase = members.length === 1 ? "own-wait" : "run";
1249
+ }
1250
+ running.add(b);
1251
+ b.run = runBatch(b);
1252
+ }
1253
+
1254
+ // -- the batch (B5) --------------------------------------------------------------------------
1255
+
1256
+ async function runBatch(b: Batch): Promise<void> {
1257
+ try {
1258
+ await runSteps(b);
1259
+ } catch (e) {
1260
+ // B-G5: fail closed for every member the failure affects.
1261
+ warn("verify batch: internal failure", { error: message(e) });
1262
+ for (const m of b.members) if (m.batch === b) settle(m, errorRun(`verification batch failed: ${message(e)}`));
1263
+ } finally {
1264
+ // A member handed to a batch of its own (B5.6) is that batch's to settle.
1265
+ for (const m of b.members) if (m.batch === b) settle(m, errorRun("verification batch ended without an outcome"));
1266
+ running.delete(b);
1267
+ b.group?.dispose();
1268
+ b.deadline.dispose();
1269
+ void closeScope(b);
1270
+ // W7: this batch no longer keeps the next windows waiting.
1271
+ closeIdle();
1272
+ }
1273
+ }
1274
+
1275
+ async function runSteps(b: Batch): Promise<void> {
1276
+ const first = b.members[0];
1277
+ let unionSpec: ScopedSpec | undefined;
1278
+ if (b.members.length === 1) {
1279
+ queueOwn([first]);
1280
+ } else {
1281
+ // Step 2a (QA-2.2-17 c, QA-2.2-23): the batch pools only when every member's budget covers
1282
+ // the batched schedule. Otherwise every member runs alone (step 6), with its own scope.
1283
+ if (!poolFits(b)) {
1284
+ dissolve(b, "the members' budgets cannot cover a batched run");
1285
+ return;
1286
+ }
1287
+ // Step 2, bounded by the pooled schedule (QA-2.2-25): planning is not measured, so the check
1288
+ // repeats once it is done.
1289
+ const planned = await planUnion(b, live(b), untilPoolShort(b));
1290
+ if (b.deadline.signal.aborted) return;
1291
+ if (typeof planned === "string") {
1292
+ dissolve(b, planned);
1293
+ return;
1294
+ }
1295
+ if (!poolFits(b)) {
1296
+ dissolve(b, "union planning left a member short of the batched schedule");
1297
+ return;
1298
+ }
1299
+ unionSpec = planned;
1300
+ }
1301
+ // Everyone is gone, or the coordinator was disposed: open nothing.
1302
+ if (b.deadline.signal.aborted) return;
1303
+
1304
+ // Step 3. Its first execute is the union under D, or a batch of one's own run under its own
1305
+ // deadline: the hold is never taken under another member's deadline (QA-2.2-23).
1306
+ const scope = b.runtime.openScope({ cwd: first.request.cwd, command: first.request.command });
1307
+ b.scope = scope;
1308
+ if (unionSpec !== undefined && scope.hold !== undefined) {
1309
+ // QA-2.2-25: the slot wait is the other unmeasured part of the batched schedule. The hold is
1310
+ // taken first, and waits only while the pooled schedule still fits; after that the members
1311
+ // run alone, and each still has what its split schedule needs (W3).
1312
+ const held = await scope.hold(untilPoolShort(b));
1313
+ if (b.deadline.signal.aborted) return;
1314
+ if (!held || !poolFits(b)) {
1315
+ void closeScope(b);
1316
+ dissolve(b, held ? "the slot wait left a member short of the batched schedule" : "the slot was not free in time for a batched run");
1317
+ return;
1318
+ }
1319
+ }
1320
+
1321
+ // Step 4.
1322
+ if (unionSpec !== undefined) {
1323
+ counters.unionRuns++;
1324
+ const union = await execute(b.key, scope, unionSpec, b.deadline);
1325
+ switch (union.kind) {
1326
+ case "ran":
1327
+ attribute(b, union);
1328
+ break;
1329
+ case "slot-busy":
1330
+ case "aborted":
1331
+ for (const m of live(b)) settle(m, { scoped: union, recheck: undefined });
1332
+ return;
1333
+ default:
1334
+ queueOwn(live(b));
1335
+ }
1336
+ }
1337
+
1338
+ // Steps 5, 7 and 8 (QA-2.2-3).
1339
+ await drain(b, scope);
1340
+ }
1341
+
1342
+ /**
1343
+ * B5.5 (QA-2.2-3): one queue under the hold, one command at a time, earliest deadline first. A
1344
+ * member's recheck runs as soon as its outcome is final, before the own runs of members with
1345
+ * more time left; nothing waits for a step it does not need.
1346
+ */
1347
+ async function drain(b: Batch, scope: BatchScope): Promise<void> {
1348
+ for (;;) {
1349
+ advance(b);
1350
+ const next = live(b)
1351
+ .filter((m) => m.phase === "own-wait" || m.phase === "recheck-wait")
1352
+ .sort(byDeadline)[0];
1353
+ if (next === undefined) return;
1354
+ if (next.phase === "own-wait") await runOwn(b, scope, next);
1355
+ else await recheckGroup(b, scope, next);
1356
+ }
1357
+ }
1358
+
1359
+ function queueOwn(members: readonly Member[]): void {
1360
+ for (const m of members) m.phase = "own-wait";
1361
+ }
1362
+
1363
+ /**
1364
+ * Step 6 (QA-2.2-23): the batch splits. Every live member runs alone as a batch of one (B5.1),
1365
+ * with its own gate's runtime: its own scope, whose hold it takes under its own deadline, its own
1366
+ * run and its own recheck. That is its direct path, so no member's slot wait, run or recheck
1367
+ * depends on another member's budget. The batches start in arrival order, the order in which the
1368
+ * members' direct hooks would have queued for the slot. This batch opened no scope, so no hold
1369
+ * is shared or nested; each batch of one holds at most one, as its direct hook would.
1370
+ */
1371
+ function dissolve(b: Batch, cause: string): void {
1372
+ counters.splits++;
1373
+ warn("verify batch: split into own runs", { members: b.members.length, cause });
1374
+ for (const m of live(b).sort((x, y) => x.seq - y.seq)) startBatch(b.key, m.runtime, [m]);
1375
+ }
1376
+
1377
+ /**
1378
+ * B5.2a (QA-2.2-17 c, QA-2.2-25). How long the batch can still go on before some member's budget
1379
+ * no longer covers the worst case of the batched schedule ahead of its recheck: the union run,
1380
+ * every member's own run (mode B; a member can be held until the last of them, B5.7) and one
1381
+ * recheck for each member ahead of it in deadline order. Each own run and recheck is estimated
1382
+ * at e, the key's last measured duration. The union of n members is priced at n x e: it runs
1383
+ * each of the members' related test files once, where their own runs run each at least once,
1384
+ * so it is never priced as one member's run (QA-2.2-25). Before the first measurement e is 0
1385
+ * and only the floor counts (W3). Negative: the members no longer fit.
1386
+ */
1387
+ function poolSlack(b: Batch): number {
1388
+ const e = estimate(b.key);
1389
+ const order = live(b).sort(byDeadline);
1390
+ const n = order.length;
1391
+ let slack = Number.POSITIVE_INFINITY;
1392
+ order.forEach((m, i) => {
1393
+ slack = Math.min(slack, m.request.deadline.remaining() - floorOf(m) - e * (2 * n + i));
1394
+ });
1395
+ return slack;
1396
+ }
1397
+
1398
+ function poolFits(b: Batch): boolean {
1399
+ return poolSlack(b) >= 0;
1400
+ }
1401
+
1402
+ /**
1403
+ * QA-2.2-25: D, cut off where the pooled schedule stops fitting (poolSlack runs out). It has no
1404
+ * timer: remaining() and bound() end there, and its signal is D's. Union planning and the
1405
+ * union's slot wait run under it, so each ends while a split still fits every member (W3's
1406
+ * split schedule is shorter than the pooled one by at least e).
1407
+ */
1408
+ function untilPoolShort(b: Batch): Deadline {
1409
+ const end = now() + Math.max(0, poolSlack(b));
1410
+ const remaining = () => Math.max(0, Math.min(b.deadline.remaining(), end - now()));
1411
+ return { budgetMs: b.deadline.budgetMs, remaining, bound: (ownBudgetMs) => Math.min(ownBudgetMs, remaining()), signal: b.deadline.signal };
1412
+ }
1413
+
1414
+ /** B6 and the step-2 consistency checks over the members. Returns the union spec, or the cause of a split. */
1415
+ async function planUnion(b: Batch, pooled: readonly Member[], deadline: Deadline): Promise<ScopedSpec | string> {
1416
+ const changes: BatchMemberChanges[] = [];
1417
+ for (const m of pooled) {
1418
+ const changedFiles = m.request.changedFiles;
1419
+ if (changedFiles === "unavailable") return "a member's change set is unavailable";
1420
+ changes.push({ cwd: m.request.cwd, changedFiles });
1421
+ }
1422
+ const first = pooled[0];
1423
+ let plan: ScopingPlan;
1424
+ try {
1425
+ plan = await b.runtime.plan(
1426
+ { command: first.request.command, cwd: first.request.cwd, changedFiles: unionChangedFiles(changes, platform) },
1427
+ deadline,
1428
+ );
1429
+ } catch (e) {
1430
+ return `union planning failed: ${message(e)}`;
1431
+ }
1432
+ if ("noAffected" in plan) return "the union plan found nothing to run";
1433
+ if ("unverifiable" in plan) return `the union cannot be scoped (${plan.code})`;
1434
+ if (batchKey(plan, platform) !== b.key) return "the union plan runs a different command";
1435
+ const want = new Set(pooled.flatMap((m) => m.spec.inputs.map((f) => fold(f, platform))));
1436
+ const got = new Set(plan.inputs.map((f) => fold(f, platform)));
1437
+ if (want.size !== got.size || [...want].some((k) => !got.has(k))) return "the union plan's inputs differ from the members' inputs";
1438
+ return plan;
1439
+ }
1440
+
1441
+ /**
1442
+ * B7 for every member after a "ran" union, with the union's per-file counts (P1). A member
1443
+ * marked own-run queues for its own spec (B5.5: mode B, or a confirmation run); a derived member
1444
+ * holds its outcome until it is final (B5.7). QA-2.2-3 (c): static attribution is exact, so the
1445
+ * ids derived for a member that already left still count as reproduced.
1446
+ */
1447
+ function attribute(b: Batch, union: RanOutcome): void {
1448
+ const n = b.members.length;
1449
+ b.unionIds = taintable(union);
1450
+ for (const m of b.members) {
1451
+ const a = attributeUnion(union.result, union.result.testsByFile, m.spec, platform);
1452
+ if (a.kind === "own-run") {
1453
+ if (!m.settled) m.phase = "own-wait";
1454
+ continue;
1455
+ }
1456
+ for (const id of a.result.failingIds) b.reproduced.add(id);
1457
+ if (m.settled) continue;
1458
+ // B7.4: the member's own spec, its plan notes and the batch note.
1459
+ m.scoped = { kind: "ran", result: a.result, exitCode: a.exitCode, spec: m.spec, notes: [...m.spec.notes, `batched: 1 run for ${n} requests`] };
1460
+ m.phase = "held";
1461
+ }
1462
+ }
1463
+
1464
+ /**
1465
+ * B7.5: the union failing ids the taint compares with the members' outcomes. A complete union
1466
+ * keeps every id (QA-2.2-11): an id no member's derivation reproduces must taint, whatever its
1467
+ * key. Only an INCOMPLETE pytest union leaves out an id that names none of its inputs: that is a
1468
+ * classname readResult could not map (runner.ts I step 3: unmapped or ambiguous), whose raw form
1469
+ * no own run can reproduce, and every member of an incomplete union runs its own spec verbatim
1470
+ * (7.1), so none of them is judged on the union's result.
1471
+ */
1472
+ function taintable(union: RanOutcome): readonly string[] {
1473
+ const spec = union.spec;
1474
+ if (union.result.complete || spec === undefined || !spec.inputsAreTests) return union.result.failingIds;
1475
+ const keys = new Set(spec.inputs.map((f) => fold(fileKeyOf(spec.cwd, f, platform), platform)));
1476
+ return union.result.failingIds.filter((id) => keys.has(fold(fileKeyOfId(id), platform)));
1477
+ }
1478
+
1479
+ /** B7.5: the union failing ids that no finished own run or static derivation reproduces yet. */
1480
+ function outstanding(b: Batch): string[] {
1481
+ return b.unionIds.filter((id) => !b.reproduced.has(id));
1482
+ }
1483
+
1484
+ /**
1485
+ * B5.7 and B5.8 (QA-2.2-3). The batch is final once every union failing id is reproduced, or once
1486
+ * no own run is left (then the flaky taint is applied, once). Every held member of a final batch
1487
+ * is then released: settled, or queued for its recheck.
1488
+ */
1489
+ function advance(b: Batch): void {
1490
+ if (!b.final) {
1491
+ const open = outstanding(b);
1492
+ if (open.length > 0) {
1493
+ if (b.members.some((m) => !m.settled && (m.phase === "own-wait" || m.phase === "own-run"))) return;
1494
+ taint(b, open);
1495
+ }
1496
+ b.final = true;
1497
+ }
1498
+ for (const m of live(b)) if (m.phase === "held") release(b, m);
1499
+ }
1500
+
1501
+ /**
1502
+ * B7.5 (B-G2): union failures that no member's final outcome reproduces make every member's
1503
+ * "ran" result incomplete, so none of them can pass on the strength of the batch.
1504
+ */
1505
+ function taint(b: Batch, unreproduced: readonly string[]): void {
1506
+ counters.taints++;
1507
+ warn("verify batch: a batched run failure was not reproduced by any request's own run", { ids: unreproduced });
1508
+ for (const m of live(b)) {
1509
+ const s = m.scoped;
1510
+ if (s?.kind === "ran") m.scoped = { ...s, result: taintUnreproduced(s.result, unreproduced) };
1511
+ }
1512
+ }
1513
+
1514
+ /** B5.8: a final outcome settles unless it needs a recheck that nothing in the batch answers yet. */
1515
+ function release(b: Batch, m: Member): void {
1516
+ const scoped = m.scoped;
1517
+ if (scoped === undefined || !needsRecheck(scoped)) {
1518
+ settle(m, scoped === undefined ? errorRun("verification batch produced no outcome") : { scoped, recheck: undefined });
1519
+ return;
1520
+ }
1521
+ const decision = referenceDecision(m);
1522
+ if ("decided" in decision) {
1523
+ settle(m, { scoped, recheck: decision.decided });
1524
+ return;
1525
+ }
1526
+ const key = referenceKey(decision.reference);
1527
+ const reused = reuse(b, key, scoped, m);
1528
+ if (reused !== undefined) {
1529
+ settle(m, { scoped, recheck: reused });
1530
+ return;
1531
+ }
1532
+ m.ready = { scoped, reference: decision.reference, key };
1533
+ m.phase = "recheck-wait";
1534
+ }
1535
+
1536
+ /**
1537
+ * B9 (QA-2.2-3): a member whose deadline ends once its outcome is known gets that outcome, never
1538
+ * a bare abort. While a union failure is still unexplained the outcome is made incomplete with
1539
+ * those ids (never a pass), and a recheck it needs becomes its reference decision, else
1540
+ * skipped-deadline, as alone below the threshold.
1541
+ */
1542
+ function settleLate(b: Batch, m: Member): void {
1543
+ const s = m.scoped;
1544
+ if (s === undefined) {
1545
+ settle(m, abortedRun(BATCH_REASONS.attribution));
1546
+ return;
1547
+ }
1548
+ const open = b.final ? [] : outstanding(b);
1549
+ const scoped = s.kind === "ran" && open.length > 0 ? { ...s, result: taintUnreproduced(s.result, open) } : s;
1550
+ settle(m, { scoped, recheck: needsRecheck(scoped) ? lateRecheck(m) : undefined });
1551
+ }
1552
+
1553
+ /** B5.5: the member's own spec under its own deadline; the outcome is its scoped outcome, verbatim. */
1554
+ async function runOwn(b: Batch, scope: BatchScope, m: Member): Promise<void> {
1555
+ m.phase = "own-run";
1556
+ counters.ownRuns++;
1557
+ const link = linkDeadline(m.request.deadline, b.deadline.signal);
1558
+ const out = await execute(b.key, scope, m.spec, link.deadline);
1559
+ link.unlink();
1560
+ // B7.5: a finished run is evidence even when its member has already left.
1561
+ if (out.kind === "ran") for (const id of out.result.failingIds) b.reproduced.add(id);
1562
+ if (m.settled) return;
1563
+ m.scoped = out;
1564
+ if (out.kind !== "ran") settle(m, { scoped: out, recheck: undefined });
1565
+ // Its deadline ended during its own run: it waits for nothing more, as alone (B-G4).
1566
+ else if (m.request.deadline.signal.aborted) settleLate(b, m);
1567
+ else m.phase = "held";
1568
+ }
1569
+
1570
+ // -- rechecks (B8) ---------------------------------------------------------------------------
1571
+
1572
+ /** B8.1: the no-spawn decisions of 2.1-T4, or the captured reference to recheck at. */
1573
+ function referenceDecision(m: Member): { readonly decided: RecheckOutcome } | { readonly reference: DispatchReference } {
1574
+ const state = m.request.reference;
1575
+ // QA-2.2-2: 2.1's direct hook, `ref.kind === "disabled" || !failureRecheck` -> disabled.
1576
+ if (!m.failureRecheck) return { decided: { kind: "disabled" } };
1577
+ switch (state.kind) {
1578
+ case "disabled":
1579
+ return { decided: { kind: "disabled" } };
1580
+ case "none":
1581
+ return { decided: { kind: "unusable", cause: "no-reference", reason: state.reason } };
1582
+ case "captured":
1583
+ return { reference: state.reference };
1584
+ }
1585
+ }
1586
+
1587
+ /** The recheck of a member whose deadline already ended: its reference decision, else skipped-deadline. */
1588
+ function lateRecheck(m: Member): RecheckOutcome {
1589
+ const decision = referenceDecision(m);
1590
+ return "decided" in decision ? decision.decided : { kind: "skipped-deadline", remainingMs: m.request.deadline.remaining() };
1591
+ }
1592
+
1593
+ /** B8.3: below the threshold a member gets skipped-deadline and nothing is spawned for it. */
1594
+ function skippedForDeadline(b: Batch, m: Member, scoped: RanOutcome): boolean {
1595
+ const remainingMs = m.request.deadline.remaining();
1596
+ if (remainingMs >= b.runtime.recheckMinRemainingMs) return false;
1597
+ settle(m, { scoped, recheck: { kind: "skipped-deadline", remainingMs } });
1598
+ return true;
1599
+ }
1600
+
1601
+ /**
1602
+ * B8.6: an outcome recorded for later members at the same reference. Only outcomes that do not
1603
+ * depend on the deadline or on a transient failure of the run that produced them are kept.
1604
+ */
1605
+ function remember(b: Batch, key: string, outcome: RecheckOutcome): void {
1606
+ const kept =
1607
+ outcome.kind === "exact" ||
1608
+ outcome.kind === "approximate" ||
1609
+ (outcome.kind === "unusable" && REUSABLE_CAUSES.has(outcome.cause));
1610
+ if (!kept) return;
1611
+ const list = b.rechecked.get(key) ?? [];
1612
+ list.push(outcome);
1613
+ b.rechecked.set(key, list);
1614
+ }
1615
+
1616
+ /** B8.6: the member's outcome derived from a recheck already run at its reference, if one covers its files. */
1617
+ function reuse(b: Batch, key: string, scoped: RanOutcome, m: Member): RecheckOutcome | undefined {
1618
+ for (const done of b.rechecked.get(key) ?? []) {
1619
+ const counts = done.kind === "exact" ? done.result?.testsByFile : undefined;
1620
+ const derived = deriveSharedRecheck(done, counts, scoped.result.failingFiles, m.spec.cwd, platform);
1621
+ if (derived !== "split") return derived;
1622
+ }
1623
+ return undefined;
1624
+ }
1625
+
1626
+ /**
1627
+ * B8.3-8.5 for the member the queue picked: it rechecks together with every member ready at
1628
+ * this moment at the same reference (its group, earliest deadline first).
1629
+ */
1630
+ async function recheckGroup(b: Batch, scope: BatchScope, lead: Member): Promise<void> {
1631
+ const key = lead.ready?.key;
1632
+ const group: { readonly m: Member; readonly ready: Ready }[] = [];
1633
+ for (const m of live(b).sort(byDeadline)) {
1634
+ const ready = m.ready;
1635
+ if (m.phase !== "recheck-wait" || ready === undefined || ready.key !== key) continue;
1636
+ // B8.3: a member below the threshold leaves its group, as it would alone.
1637
+ if (!skippedForDeadline(b, m, ready.scoped)) group.push({ m, ready });
1638
+ }
1639
+ if (group.length === 0) return;
1640
+ // B8.4.
1641
+ if (group.length === 1) {
1642
+ await recheckOne(b, scope, group[0].m, group[0].ready);
1643
+ return;
1644
+ }
1645
+ // B8.5: one recheck over the union of the group's failing files, bounded by Rg.
1646
+ const seen = new Set<string>();
1647
+ const files: string[] = [];
1648
+ for (const { ready } of group) {
1649
+ for (const f of ready.scoped.result.failingFiles) {
1650
+ const k = fold(f, platform);
1651
+ if (seen.has(k)) continue;
1652
+ seen.add(k);
1653
+ files.push(f);
1654
+ }
1655
+ }
1656
+ const first = group[0];
1657
+ const rg = createBatchDeadline(group.map((c) => c.m.request.deadline));
1658
+ b.group = rg;
1659
+ for (const { m } of group) {
1660
+ m.phase = "recheck";
1661
+ m.recheckBoundMs = m.request.deadline.remaining();
1662
+ }
1663
+ counters.rechecks++;
1664
+ const shared = await recheck(scope, first.m, first.ready.reference, files, rg);
1665
+ b.group = undefined;
1666
+ rg.dispose();
1667
+ remember(b, first.ready.key, shared);
1668
+ const counts = shared.kind === "exact" ? shared.result?.testsByFile : undefined;
1669
+ const split: { readonly m: Member; readonly ready: Ready }[] = [];
1670
+ for (const c of group) {
1671
+ if (c.m.settled) continue;
1672
+ const derived = deriveSharedRecheck(shared, counts, c.ready.scoped.result.failingFiles, c.m.spec.cwd, platform);
1673
+ if (derived === "split") split.push(c);
1674
+ else settle(c.m, { scoped: c.ready.scoped, recheck: derived });
1675
+ }
1676
+ if (split.length === 0) return;
1677
+ warn("verify batch: a shared recheck split into own rechecks", { members: split.length, shared: shared.kind });
1678
+ for (const c of split.sort((x, y) => byDeadline(x.m, y.m))) await recheckOne(b, scope, c.m, c.ready);
1679
+ }
1680
+
1681
+ /** B8.4: the direct path, under the member's own deadline. */
1682
+ async function recheckOne(b: Batch, scope: BatchScope, m: Member, ready: Ready): Promise<void> {
1683
+ if (m.settled || skippedForDeadline(b, m, ready.scoped)) return;
1684
+ m.phase = "recheck";
1685
+ m.recheckBoundMs = m.request.deadline.remaining();
1686
+ counters.rechecks++;
1687
+ const link = linkDeadline(m.request.deadline, b.deadline.signal);
1688
+ const out = await recheck(scope, m, ready.reference, ready.scoped.result.failingFiles, link.deadline);
1689
+ link.unlink();
1690
+ remember(b, ready.key, out);
1691
+ settle(m, { scoped: ready.scoped, recheck: out });
1692
+ }
1693
+
1694
+ // -- seams (B-G5: a throwing seam becomes a fail-closed outcome) ------------------------------
1695
+
1696
+ /**
1697
+ * A run under the batch's hold. A run that ran, or ran out of time, measures the key's estimate
1698
+ * (QA-2.2-17). The first run of a scope includes its slot wait, which only overstates it.
1699
+ */
1700
+ async function execute(key: string, scope: BatchScope, spec: ScopedSpec, deadline: Deadline): Promise<ScopedOutcome> {
1701
+ const started = now();
1702
+ let out: ScopedOutcome;
1703
+ try {
1704
+ out = await scope.execute(spec, deadline);
1705
+ } catch (e) {
1706
+ return { kind: "error", reason: `scoped run failed: ${message(e)}` };
1707
+ }
1708
+ if (out.kind === "ran" || out.kind === "timed-out") noteDuration(key, now() - started);
1709
+ return out;
1710
+ }
1711
+
1712
+ async function recheck(
1713
+ scope: BatchScope,
1714
+ m: Member,
1715
+ reference: DispatchReference,
1716
+ files: readonly string[],
1717
+ deadline: Deadline,
1718
+ ): Promise<RecheckOutcome> {
1719
+ try {
1720
+ return await scope.rechecker(m.request.command, m.request.cwd, m.currentTree)(reference, files, deadline);
1721
+ } catch (e) {
1722
+ return { kind: "unusable", cause: "error", reason: `recheck failed: ${message(e)}` };
1723
+ }
1724
+ }
1725
+
1726
+ /** B5.9: close once; requesters never wait for it, dispose() does. */
1727
+ function closeScope(b: Batch): Promise<void> {
1728
+ if (b.closing === undefined) {
1729
+ const scope = b.scope;
1730
+ const p =
1731
+ scope === undefined
1732
+ ? Promise.resolve()
1733
+ : Promise.resolve()
1734
+ .then(() => scope.close())
1735
+ .catch((e: unknown) => warn("verify batch: scope close failed", { error: message(e) }));
1736
+ b.closing = p;
1737
+ closing.add(p);
1738
+ void p.then(() => closing.delete(p));
1739
+ }
1740
+ return b.closing;
1741
+ }
1742
+
1743
+ /**
1744
+ * B11 (QA-2.2-4, QA-2.2-19): stops tracking a batch whose seam did not return after its tree was
1745
+ * killed, and asks its scope to close. 2.1's scope closes only once its in-flight seams have
1746
+ * returned, so the slot stays held until the hung seam exits: nothing else runs beside it. This
1747
+ * is only reached after BATCH_STALE_GRACE_MS, and it is logged.
1748
+ */
1749
+ function evict(b: Batch): void {
1750
+ running.delete(b);
1751
+ b.group?.dispose();
1752
+ b.deadline.dispose();
1753
+ warn("verify batch: evicted a batch whose seam never returned; its scope closes, and its slot is released, once the seam exits", {
1754
+ key: b.key,
1755
+ members: b.members.length,
1756
+ });
1757
+ void closeScope(b);
1758
+ // W7: a hung batch no longer keeps the next windows waiting.
1759
+ closeIdle();
1760
+ }
1761
+
1762
+ // -- arrival (B2) ----------------------------------------------------------------------------
1763
+
1764
+ async function submit(runtime: BatchRuntime, request: TestsPassRequest): Promise<TestsPassRun> {
1765
+ if (disposed) return abortedRun(BATCH_REASONS.disposed);
1766
+ if (request.testScope === "full" || !(runtime.batchWindowMs > 0)) return await runtime.direct(request);
1767
+ // QA-2.2-9: planning comes first, as in 2.1's direct hook, so an exhausted deadline still gets
1768
+ // the planning outcome (NoAffected, S6) the direct path gives, and aborted only for a spec.
1769
+ // W7: a request in planning may join an open window, so it keeps the windows open.
1770
+ planning++;
1771
+ let plan: ScopingPlan;
1772
+ try {
1773
+ plan = await runtime.plan({ command: request.command, cwd: request.cwd, changedFiles: request.changedFiles }, request.deadline);
1774
+ } catch (e) {
1775
+ planning--;
1776
+ closeIdle();
1777
+ return errorRun(`scoped run planning failed: ${message(e)}`);
1778
+ }
1779
+ planning--;
1780
+ if ("noAffected" in plan) {
1781
+ closeIdle();
1782
+ return { scoped: { kind: "no-affected", note: plan.note }, recheck: undefined };
1783
+ }
1784
+ if ("unverifiable" in plan) {
1785
+ closeIdle();
1786
+ return { scoped: { kind: "unverifiable", code: plan.code, reason: plan.reason }, recheck: undefined };
1787
+ }
1788
+ if (disposed) return abortedRun(BATCH_REASONS.disposed);
1789
+ if (request.deadline.signal.aborted) {
1790
+ closeIdle();
1791
+ return abortedRun(BATCH_REASONS.beforeRun);
1792
+ }
1793
+ return join(runtime, request, plan);
1794
+ }
1795
+
1796
+ return {
1797
+ hook(runtime: BatchRuntime): TestsPassHook {
1798
+ return async (request) => {
1799
+ try {
1800
+ return await submit(runtime, request);
1801
+ } catch (e) {
1802
+ return errorRun(`verification coordinator failed: ${message(e)}`);
1803
+ }
1804
+ };
1805
+ },
1806
+
1807
+ sweep(): number {
1808
+ let evicted = 0;
1809
+ for (const [key, w] of windows) {
1810
+ if (w.members.some((m) => !m.settled)) continue;
1811
+ w.closed = true;
1812
+ timers.clearTimeout(w.timer);
1813
+ windows.delete(key);
1814
+ evicted++;
1815
+ warn("verify batch: evicted a window with no live member", { key });
1816
+ }
1817
+ const t = now();
1818
+ for (const b of running) {
1819
+ // D aborted when its last member settled, which killed the running tree. A seam that has
1820
+ // still not returned a grace period later is hung (QA-2.2-4).
1821
+ if (b.settledAt === undefined || t - b.settledAt <= BATCH_STALE_GRACE_MS) continue;
1822
+ evict(b);
1823
+ evicted++;
1824
+ }
1825
+ return evicted;
1826
+ },
1827
+
1828
+ stats(): BatchStats {
1829
+ return { openWindows: windows.size, runningBatches: running.size, pendingRequests: pending, ...counters };
1830
+ },
1831
+
1832
+ async dispose(): Promise<void> {
1833
+ if (!disposed) {
1834
+ disposed = true;
1835
+ for (const w of windows.values()) {
1836
+ w.closed = true;
1837
+ timers.clearTimeout(w.timer);
1838
+ for (const m of [...w.members]) settle(m, abortedRun(BATCH_REASONS.disposed));
1839
+ }
1840
+ windows.clear();
1841
+ for (const b of running) {
1842
+ for (const m of b.members) settle(m, abortedRun(BATCH_REASONS.disposed));
1843
+ // B11.4: kill the running trees. The scope is NOT closed here: runBatch closes it once
1844
+ // its seam has returned, that is once the killed tree has exited (QA-2.2-4).
1845
+ b.group?.dispose();
1846
+ b.deadline.dispose();
1847
+ }
1848
+ }
1849
+ // B11.5 and B11.6 (QA-2.2-19): one grace of BATCH_STALE_GRACE_MS bounds both waits, for
1850
+ // the in-flight seams and then for the scope closes. A seam still running after it is hung:
1851
+ // its batch is evicted and logged. A close still pending after it waits for such a seam
1852
+ // (2.1's close awaits its in-flight executes), so dispose stops waiting and logs it; that
1853
+ // slot is released when the seam exits.
1854
+ if (running.size === 0 && closing.size === 0) return;
1855
+ let handle: unknown;
1856
+ const grace = new Promise<"grace">((resolve) => {
1857
+ handle = timers.setTimeout(() => resolve("grace"), BATCH_STALE_GRACE_MS);
1858
+ });
1859
+ try {
1860
+ const inflight = [...running].map((b) => b.run);
1861
+ if (inflight.length > 0) {
1862
+ await Promise.race([Promise.all(inflight), grace]);
1863
+ for (const b of running) evict(b);
1864
+ }
1865
+ const closes = [...closing];
1866
+ if (closes.length > 0 && (await Promise.race([Promise.all(closes).then(() => "closed" as const), grace])) === "grace") {
1867
+ warn("verify batch: dispose stopped waiting for scope closes; each slot is released once its seam exits", { closes: closing.size });
1868
+ }
1869
+ } finally {
1870
+ timers.clearTimeout(handle);
1871
+ }
1872
+ },
1873
+ };
1874
+ }
1875
+
1876
+ // ---------------------------------------------------------------------------------------------
1877
+ // Pure helpers (exported for table tests)
1878
+ // ---------------------------------------------------------------------------------------------
1879
+
1880
+ function pathApi(platform: NodeJS.Platform): typeof posix {
1881
+ return platform === "win32" ? win32 : posix;
1882
+ }
1883
+
1884
+ /** Path-key folding: case-insensitive on win32 (B3, B6). */
1885
+ function fold(p: string, platform: NodeJS.Platform): string {
1886
+ return platform === "win32" ? p.toLowerCase() : p;
1887
+ }
1888
+
1889
+ /** Code-unit order, independent of the locale. */
1890
+ function byCodeUnit(a: string, b: string): number {
1891
+ return a < b ? -1 : a > b ? 1 : 0;
1892
+ }
1893
+
1894
+ /** B3: key-sorted JSON of a spec's env. */
1895
+ export function envSignature(env: Readonly<Record<string, string>>): string {
1896
+ return JSON.stringify(
1897
+ Object.keys(env)
1898
+ .sort(byCodeUnit)
1899
+ .map((k) => [k, env[k]]),
1900
+ );
1901
+ }
1902
+
1903
+ /** B3: spec.args without the elements equal to an input, with spec.reportPath replaced by "<report>". */
1904
+ export function argvTemplate(spec: ScopedSpec): readonly string[] {
1905
+ const inputs = new Set(spec.inputs);
1906
+ const report = spec.reportPath;
1907
+ return spec.args.filter((a) => !inputs.has(a)).map((a) => (report === "" ? a : a.split(report).join("<report>")));
1908
+ }
1909
+
1910
+ /** B3: [gitRoot, runner, entry, file, cwd, envSignature, argvTemplate] as JSON, with paths case-folded on win32. */
1911
+ export function batchKey(spec: ScopedSpec, platform: NodeJS.Platform): string {
1912
+ return JSON.stringify([
1913
+ fold(spec.gitRoot, platform),
1914
+ spec.runner,
1915
+ fold(spec.entry, platform),
1916
+ fold(spec.file, platform),
1917
+ fold(spec.cwd, platform),
1918
+ envSignature(spec.env),
1919
+ argvTemplate(spec),
1920
+ ]);
1921
+ }
1922
+
1923
+ /** B8.2: root, commit, and the sorted untracked, tracked and captureReasons entries; capturedAt is excluded. */
1924
+ export function referenceKey(reference: DispatchReference): string {
1925
+ const entries = (m: ReadonlyMap<string, string>) => [...m.entries()].sort((a, b) => byCodeUnit(a[0], b[0]) || byCodeUnit(a[1], b[1]));
1926
+ const reasons = reference.captureReasons.map((r) => JSON.stringify([r.cause, r.path])).sort(byCodeUnit);
1927
+ return JSON.stringify([reference.root, reference.commit, entries(reference.untracked), entries(reference.tracked), reasons]);
1928
+ }
1929
+
1930
+ /** One member's change set, as unionChangedFiles reads it. */
1931
+ export interface BatchMemberChanges {
1932
+ /** The request's check cwd: relative ChangedPath paths resolve against it. */
1933
+ readonly cwd: string;
1934
+ readonly changedFiles: readonly ChangedPath[];
1935
+ }
1936
+
1937
+ /**
1938
+ * B6: every member's entries, with path and previousPath made absolute against the member's cwd,
1939
+ * deduplicated by the platform key of (path, previousPath) in first-seen order.
1940
+ */
1941
+ export function unionChangedFiles(members: readonly BatchMemberChanges[], platform: NodeJS.Platform): ChangedPath[] {
1942
+ const P = pathApi(platform);
1943
+ const seen = new Set<string>();
1944
+ const out: ChangedPath[] = [];
1945
+ for (const m of members) {
1946
+ for (const c of m.changedFiles) {
1947
+ const path = P.resolve(m.cwd, c.path);
1948
+ const previousPath = c.previousPath === undefined ? undefined : P.resolve(m.cwd, c.previousPath);
1949
+ const key = JSON.stringify([fold(path, platform), previousPath === undefined ? null : fold(previousPath, platform)]);
1950
+ if (seen.has(key)) continue;
1951
+ seen.add(key);
1952
+ out.push({
1953
+ path,
1954
+ ...(c.status !== undefined ? { status: c.status } : {}),
1955
+ ...(previousPath !== undefined ? { previousPath } : {}),
1956
+ });
1957
+ }
1958
+ }
1959
+ return out;
1960
+ }
1961
+
1962
+ /** runner.ts JS_TEST_RE: the G.8 test-file suffix rule. */
1963
+ const JS_TEST_RE = /\.(test|spec)\.[cm]?[jt]sx?$/;
1964
+
1965
+ /** runner.ts isJsTestPath (G.8): a .test/.spec file or a file under __tests__. Either separator. */
1966
+ function isJsTestPath(p: string): boolean {
1967
+ const segs = p.split(/[\\/]/);
1968
+ return JS_TEST_RE.test(segs[segs.length - 1] ?? "") || segs.includes("__tests__");
1969
+ }
1970
+
1971
+ /**
1972
+ * B7.2: true when readResult's zero-test guard (runner.ts I step 2a) could fire for this spec alone:
1973
+ * lexicalPaths, inputsAreTests, or a JS test file among its inputs (runner.ts G.8 rule).
1974
+ */
1975
+ export function isGuardSensitive(spec: ScopedSpec, platform: NodeJS.Platform): boolean {
1976
+ // The G.8 rule reads both separators and is case-sensitive on every platform, as in runner.ts.
1977
+ void platform;
1978
+ return spec.lexicalPaths === true || spec.inputsAreTests || spec.inputs.some(isJsTestPath);
1979
+ }
1980
+
1981
+ /** The id-space file key: the path of `absolutePath` relative to `cwd`, with "/" separators (runner.ts I). */
1982
+ export function fileKeyOf(cwd: string, absolutePath: string, platform: NodeJS.Platform): string {
1983
+ return pathApi(platform).relative(cwd, absolutePath).replace(/\\/g, "/");
1984
+ }
1985
+
1986
+ /** The sum of `counts` over `keys`, matched with the platform's folding. */
1987
+ function countOver(counts: TestCounts, keys: Iterable<string>, platform: NodeJS.Platform): number {
1988
+ const folded = new Map<string, number>();
1989
+ for (const [k, n] of Object.entries(counts)) folded.set(fold(k, platform), (folded.get(fold(k, platform)) ?? 0) + n);
1990
+ let n = 0;
1991
+ for (const k of new Set([...keys].map((x) => fold(x, platform)))) n += folded.get(k) ?? 0;
1992
+ return n;
1993
+ }
1994
+
1995
+ function greenResult(total: number | undefined): RunResult {
1996
+ return { failingIds: [], failingFiles: [], collectionError: false, total, complete: true, source: "report" };
1997
+ }
1998
+
1999
+ /** Per-file test counts of one run (P1): id-space file key -> the number of tests listed. */
2000
+ export type TestCounts = Readonly<Record<string, number>>;
2001
+
2002
+ /** Why a member runs its own spec (B7). */
2003
+ export type OwnRunCause =
2004
+ /** 7.1: the union's result is incomplete, has a collection error, or comes from text. */
2005
+ | "not-comparable"
2006
+ /** 7.2b/7.3a: the member's own run could have tripped the zero-test guard, and counts cannot tell. */
2007
+ | "zero-test-ambiguous"
2008
+ /** 7.3b: a failing vitest/jest union. */
2009
+ | "mode-b";
2010
+
2011
+ /** attributeUnion's decision for one member. */
2012
+ export type UnionAttribution =
2013
+ | { readonly kind: "derived"; readonly result: RunResult; readonly exitCode: number }
2014
+ | { readonly kind: "own-run"; readonly cause: OwnRunCause };
2015
+
2016
+ /**
2017
+ * B7.1-7.3 for one member, given the union run's result, its per-file counts (P1; undefined
2018
+ * without them) and the member's own spec. Pure.
2019
+ */
2020
+ export function attributeUnion(
2021
+ union: RunResult,
2022
+ counts: TestCounts | undefined,
2023
+ member: ScopedSpec,
2024
+ platform: NodeJS.Platform,
2025
+ ): UnionAttribution {
2026
+ // 7.1
2027
+ if (!union.complete || union.collectionError || union.source !== "report") return { kind: "own-run", cause: "not-comparable" };
2028
+ const inputKeys = member.inputs.map((f) => fileKeyOf(member.cwd, f, platform));
2029
+
2030
+ // 7.2b for pytest (and 7.3a when none of the union's failures is the member's): its own run is
2031
+ // green with n tests, or trips the zero-test guard with n = 0.
2032
+ const staticGreen = (): UnionAttribution => {
2033
+ if (counts === undefined) return { kind: "own-run", cause: "zero-test-ambiguous" };
2034
+ const n = countOver(counts, inputKeys, platform);
2035
+ if (n > 0) return { kind: "derived", result: greenResult(n), exitCode: 0 };
2036
+ return {
2037
+ kind: "derived",
2038
+ result: { ...greenResult(0), complete: false, note: `${member.runner} ran no tests although a test file was passed` },
2039
+ exitCode: member.runner === "pytest" ? 5 : 0,
2040
+ };
2041
+ };
2042
+
2043
+ if (union.failingIds.length === 0) {
2044
+ // 7.2a
2045
+ if (!isGuardSensitive(member, platform)) return { kind: "derived", result: greenResult(union.total), exitCode: 0 };
2046
+ // 7.2b
2047
+ if (member.inputsAreTests) return staticGreen();
2048
+ if (counts === undefined) return { kind: "own-run", cause: "zero-test-ambiguous" };
2049
+ const n = countOver(
2050
+ counts,
2051
+ member.inputs.flatMap((f, i) => (isJsTestPath(f) ? [inputKeys[i]] : [])),
2052
+ platform,
2053
+ );
2054
+ return n > 0 ? { kind: "derived", result: greenResult(n), exitCode: 0 } : { kind: "own-run", cause: "zero-test-ambiguous" };
2055
+ }
2056
+
2057
+ // 7.3b
2058
+ if (!member.inputsAreTests) return { kind: "own-run", cause: "mode-b" };
2059
+ // 7.3a: static attribution by input file key.
2060
+ const own = new Set(inputKeys.map((k) => fold(k, platform)));
2061
+ const ids = union.failingIds.filter((id) => own.has(fold(fileKeyOfId(id), platform)));
2062
+ if (ids.length === 0) return staticGreen();
2063
+ const files = union.failingFiles.filter((f) => own.has(fold(fileKeyOf(member.cwd, f, platform), platform)));
2064
+ const total = counts === undefined ? union.total : countOver(counts, inputKeys, platform);
2065
+ return {
2066
+ kind: "derived",
2067
+ result: { failingIds: ids, failingFiles: files, collectionError: false, total, complete: true, source: "report" },
2068
+ exitCode: 1,
2069
+ };
2070
+ }
2071
+
2072
+ /**
2073
+ * B7.5: the member's result with complete = false and the note "batched run failure not
2074
+ * reproduced by any request's own run: <ids>". Its failing ids and files are kept.
2075
+ */
2076
+ export function taintUnreproduced(result: RunResult, unreproduced: readonly string[]): RunResult {
2077
+ if (unreproduced.length === 0) return result;
2078
+ return {
2079
+ ...result,
2080
+ complete: false,
2081
+ note: `batched run failure not reproduced by any request's own run: ${[...new Set(unreproduced)].sort(byCodeUnit).join(", ")}`,
2082
+ };
2083
+ }
2084
+
2085
+ /** B8.5: unusable causes that describe the reference, the same for every member of its group. */
2086
+ const REFERENCE_LEVEL_CAUSES: ReadonlySet<string> = new Set([
2087
+ "no-reference",
2088
+ "materialize-failed",
2089
+ "reference-vanished",
2090
+ "unreproduced-inputs",
2091
+ "runner-unsupported",
2092
+ "error",
2093
+ ]);
2094
+
2095
+ /**
2096
+ * B8.6: unusable causes a later member at the same reference may reuse. "materialize-failed" is
2097
+ * left out (an aborted materialize reports it, so it can be the deadline of the member that ran
2098
+ * it), and so is "error" (a transient executor failure).
2099
+ */
2100
+ const REUSABLE_CAUSES: ReadonlySet<string> = new Set(["reference-vanished", "unreproduced-inputs", "runner-unsupported"]);
2101
+
2102
+ /**
2103
+ * B8.5: one member's RecheckOutcome, derived from a recheck shared by its reference group, or
2104
+ * "split" when only the member's own recheck can answer. `failingFiles` are the member's absolute
2105
+ * live paths and `cwd` its spec.cwd (the id key space).
2106
+ */
2107
+ export function deriveSharedRecheck(
2108
+ shared: RecheckOutcome,
2109
+ counts: TestCounts | undefined,
2110
+ failingFiles: readonly string[],
2111
+ cwd: string,
2112
+ platform: NodeJS.Platform,
2113
+ ): RecheckOutcome | "split" {
2114
+ switch (shared.kind) {
2115
+ case "approximate":
2116
+ case "disabled":
2117
+ case "timed-out":
2118
+ case "skipped-deadline":
2119
+ return shared;
2120
+ case "unusable":
2121
+ return REFERENCE_LEVEL_CAUSES.has(shared.cause) ? shared : "split";
2122
+ case "exact":
2123
+ break;
2124
+ }
2125
+ const mine = new Set(failingFiles.map((f) => fold(fileKeyOf(cwd, f, platform), platform)));
2126
+ const ranFiles = shared.ranFiles.filter((k) => mine.has(fold(k, platform)));
2127
+ const absentFiles = shared.absentFiles.filter((k) => mine.has(fold(k, platform)));
2128
+ // Every file of the member must be accounted for, and ran files need a result: otherwise only
2129
+ // the member's own recheck can answer.
2130
+ const covered = new Set([...ranFiles, ...absentFiles].map((k) => fold(k, platform)));
2131
+ if ([...mine].some((k) => !covered.has(k))) return "split";
2132
+ if (ranFiles.length === 0) return { kind: "exact", result: undefined, ranFiles, absentFiles, notes: shared.notes };
2133
+ const full = shared.result;
2134
+ if (full === undefined) return "split";
2135
+
2136
+ const ranSet = new Set(ranFiles.map((k) => fold(k, platform)));
2137
+ const failingIds = full.failingIds.filter((id) => ranSet.has(fold(fileKeyOfId(id), platform)));
2138
+ // The rerun's failingFiles are absolute paths in the reference worktree, whose cwd this module
2139
+ // does not know: each is keyed by the longest shared ran-file key it ends with.
2140
+ const allKeys = [...new Set(shared.ranFiles.map((k) => fold(k, platform)))].sort((a, b) => b.length - a.length);
2141
+ const keyOfRerunFile = (f: string): string | undefined => {
2142
+ const slashed = fold(f.replace(/\\/g, "/"), platform);
2143
+ return allKeys.find((k) => slashed === k || slashed.endsWith(`/${k}`));
2144
+ };
2145
+ const failingFilesAtRef = full.failingFiles.filter((f) => {
2146
+ const k = keyOfRerunFile(f);
2147
+ return k !== undefined && ranSet.has(k);
2148
+ });
2149
+
2150
+ let total: number | undefined;
2151
+ if (counts !== undefined) {
2152
+ total = countOver(counts, ranFiles, platform);
2153
+ if (total === 0) {
2154
+ return { kind: "unusable", cause: "incomplete", reason: "rerun ran no tests although every input is a test file" };
2155
+ }
2156
+ } else {
2157
+ if (failingIds.length === 0) return "split";
2158
+ total = full.total;
2159
+ }
2160
+ return {
2161
+ kind: "exact",
2162
+ result: { failingIds, failingFiles: failingFilesAtRef, collectionError: false, total, complete: true, source: "report" },
2163
+ ranFiles,
2164
+ absentFiles,
2165
+ notes: shared.notes,
2166
+ };
2167
+ }
2168
+
2169
+ /** B9: the deadline of a batch or of a recheck group, over the members still attached. */
2170
+ export interface BatchDeadline extends Deadline {
2171
+ /** Detaches a settled member: it no longer counts toward remaining() or the all-aborted rule. */
2172
+ release(member: Deadline): void;
2173
+ /** Aborts the signal if it has not aborted yet, and removes every listener. Idempotent. */
2174
+ dispose(): void;
2175
+ }
2176
+
2177
+ /** B9. It has no timer of its own: it aborts when every attached member has aborted, or at dispose. */
2178
+ export function createBatchDeadline(members: readonly Deadline[]): BatchDeadline {
2179
+ const controller = new AbortController();
2180
+ const attached = new Map<Deadline, () => void>();
2181
+ const budgetMs = members.reduce((m, d) => Math.max(m, d.budgetMs), 0);
2182
+
2183
+ const detachAll = () => {
2184
+ for (const [d, listener] of attached) d.signal.removeEventListener("abort", listener);
2185
+ attached.clear();
2186
+ };
2187
+ const abort = () => {
2188
+ detachAll();
2189
+ if (!controller.signal.aborted) controller.abort();
2190
+ };
2191
+ const check = () => {
2192
+ for (const d of attached.keys()) if (!d.signal.aborted) return;
2193
+ abort();
2194
+ };
2195
+
2196
+ for (const d of members) {
2197
+ if (attached.has(d)) continue;
2198
+ const listener = () => check();
2199
+ attached.set(d, listener);
2200
+ d.signal.addEventListener("abort", listener, { once: true });
2201
+ }
2202
+ check();
2203
+
2204
+ const remaining = () => {
2205
+ if (controller.signal.aborted) return 0;
2206
+ let r = 0;
2207
+ for (const d of attached.keys()) r = Math.max(r, d.remaining());
2208
+ return r;
2209
+ };
2210
+
2211
+ return {
2212
+ budgetMs,
2213
+ remaining,
2214
+ bound: (ownBudgetMs: number) => Math.min(ownBudgetMs, remaining()),
2215
+ signal: controller.signal,
2216
+ release(member: Deadline) {
2217
+ const listener = attached.get(member);
2218
+ if (listener === undefined) return;
2219
+ member.signal.removeEventListener("abort", listener);
2220
+ attached.delete(member);
2221
+ check();
2222
+ },
2223
+ dispose: abort,
2224
+ };
2225
+ }
2226
+