refactor(eager-closure): tolerate a pure split in the no-growth rule (#2469)

Merged
TH
2mo ago
+1552-491

Closes #2469. Resolves ADR 0027.

Design note: the chosen rule

Of the four candidates, this implements candidate 4 (structure ∧ weight) as the minimal slice: NO-GROWTH tolerates module-count growth for exactly one shape — a pure split — decided from the two closure graphs and the merge-base tree, with nothing hand-entered. Growth is tolerated only when all three facts hold:

  1. Containment — the head closure still evaluates every module the merge-base closure did (renames canonicalized through renamedSince), so the growth is purely additive.
  2. Added-module novelty — every module the head closure evaluates that the base closure did not is absent from the merge-base tree at its rename-canonicalized path (so a moved-in pre-existing module fails at the base path the merge-base still has) and is not a verbatim transplant of a deleted source: movedFromDeletedSource brands an added module as pre-existing code when it shares ≥2 identical normalized top-level statements with one source deleted since the merge-base. Without this fact, shrinkage elsewhere in the closure would fund a new eager edge (the maintainer's counterexample); the probe is textual and deliberately conservative — a rewritten transplant evades it, which the weight fact then has to catch if it is heavier, and ADR 0027 states exactly this boundary.
  3. Flat weight — the closure's total top-level-statement count does not grow. topLevelStatementCount excludes wiring (import, export … from, source-less export { foo }), so re-homing declarations is invisible to it while module-scope execution is not.

Any one or two alone are refutable, and the planted tests pin each refutation: containment without novelty accepts pulling a pre-existing module in at flat weight (the maintainer's offset-smuggle case is a planted red→green test here); novelty without containment accepts dropping a merge-base module; weight without the other two accepts unrelated shrinkage paying for a smuggled edge.

Why not the other candidates:

  • Candidate 1 (weight alone) is refuted by the planted drop test: a swap can hold the statement total flat while making the closure evaluate different modules. Statements were chosen over bytes because formatting/comment churn moves bytes; statements track module-scope evaluation work — the thing actually preserved.
  • Candidate 2 (structure alone) is refuted by the planted smuggle test: a "new" module can carry a new heavy edge (the #2423 reviewer's own caveat).
  • Candidate 3 (APPROVED_GROWTH rows) is an allowlist on the one invariant deliberately given no approval path — AGENTS.md forbids adding one to obtain a pass — and it costs a hand-edited row plus retirement per split. Under the chosen rule an ordinary extraction costs zero configuration edits: no row, baseline, or number; the merge-base comparison recomputes everything.

Scope discipline per the umbrella (#3276) constraint: no inference framework, no source-equivalence machinery — three facts over the two closure graphs plus one git cat-file batch for deleted sources, in one small rule module. The hard ADR-0019 checks (façade exactness; no platform implementation before binding) are untouched, so the tolerance relaxes the count proxy only, never the loading property. A tolerated split still needs containment, so it cannot add an eager edge under a façade that drops anything.

Changes

  • scripts/__tests__/closure-growth-rule.ts (new): the rule — ClosureGrowthEvidence, closureGrowthEvidence, classifyGrowth, movedFromDeletedSource.
  • src/__tests__/eager-import-closure.fixtures.ts: topLevelStatementCount / topLevelStatementWeightsOf and statement-text extraction, parsed once per file content and memoized per tree alongside the edges (the base tree pays only for changed files).
  • scripts/__tests__/committed-source-tree.ts: deletedSourcesSince (a -M-less diff, so rewritten moves still list their sources) and committed-blob contents feeding the novelty probe.
  • scripts/__tests__/eager-closure-budgets.ts: applies the rule; the aggregation now fires only where the per-entry rule fails, so a tolerated split can never turn one green lane into two red aggregate failures (#2471 invariant kept).
  • scripts/__tests__/closure-growth-rule.test.ts (new, mirrors the source per testing.md): planted in both directions —
    • pure split passes: a real git repo, hub commit → working-tree split of two of three declarations; count 1→3, weight 3→3, all three facts hold → tolerated.
    • smuggled heavy edge fails: the split's part calls scan() at module scope into a new module → weight 3→4, refused.
    • pre-existing-heavy smuggle with weight offset fails (the maintainer's counterexample): split fixture + import './pre-existing-heavy.ts' in one part, weight offset by merging two hub declarations → refused on novelty; red on the two-fact draft by construction.
    • plus a flat-weight drop (not-a-split), rename canonicalization both directions, the deleted-source transplant test (a second file carrying a deleted source's statements is refused despite passing exists), and the weight function's own accept/refuse pair incl. the export { a } row.
  • docs/adr/0027: Proposed → Accepted with the decision, the refuted alternatives (including the two-fact first draft and its refutation), and the maintenance-cost answer; the guarantee sentence states the gate's actual check, including the probe's textual conservatism; 0028's measurement step updated to the tolerance's actual semantics; README row updated.

First-consumer proof (the #2423 extraction)

runner-cache-metadata.ts (621 lines) splits into runner-phase-budget.ts + runner-toolchain-probe.ts, exactly the shape the #2423 review asked for. Measured on this head via the gate's own evidence function — all seven entries #2469 names keep containment and novelty at flat weight:

entrycountweightverdict
app-lifecycle-facade117→1191952→1952PASS
app-resolution-facade59→611103→1103PASS
doctor-facade98→1001596→1596PASS
perf-facade36→36603→603PASS
physical-device-facade43→45779→779PASS
runner-operations-facade97→991587→1587PASS
runner/index.ts13→15399→399PASS

The NO-GROWTH lane in eager-closure-budgets.test.ts runs these comparisons on the real tree, so the extraction is gated by the rule, not argued past it — with zero approval rows (the rule has none). ADR 0027's measured descriptor-root split (+11, statement-neutral) is likewise unblocked; the branch that holds it needs no gate change beyond this one.

Gates

pnpm check:affected --run on the pushed head 3c6885bc1 (final round): all runnable checks passed — 470 test files / 4,363 tests, apple-runner lane, layering (all R rules), fallow audit (baseline-relative to origin/main, no new findings), gate manifest, xctest-selection (0 unreachable), typecheck, build, format, lint. (Evidence at each earlier reviewed head was identical; logs under the PR's review-round notes.) Fallow caught one real over-broad re-export from the extraction (runner-cache.ts briefly exported createRunnerPhaseBudget, which before the split reached consumers only via runner-xctestrun.ts); fixed at the owning declaration in 5e96a8785, no baseline moved. The split mirrored the test-file ratchet: the rule module and its test are their own files rather than a >1,000-line growth of the gate test.

Review rounds

Round 1 (Cubic @ 5e96a87, fixed in bdf8876ce):

  • Walker bug: topLevelStatementCount counted a source-less export { foo } as module-scope work — false weight on the re-export half of a split's wiring. Fixed at the owning predicate; planted row added, mutation-verified (revert → exactly that row fails).
  • ADR 0027 / rule header overclaim: "refuses new eager work" replaced with the actual guarantee, with the statement-replacement residue named.
  • ADR 0028 mismatch: step 3 now states classifyGrowth's real conditions instead of a paraphrase.
  • Toolchain cache-key staleness on xcode-select --switch: pre-existing (#3109 shape), moved byte-identically. Behavior changes cannot ride a split commit; filed as #3300 with the planted-test sketch.

Round 2 (maintainer review @ bdf8876, fixed in b1cc79e88 + efb0176ad):

  • The offset-smuggle hole: the two-fact rule let unrelated shrinkage fund a new eager edge to a pre-existing module. Fixed as prescribed — the addedModulesAreNew novelty fact — with the maintainer's exact counterexample planted as a failing-direction test.
  • Novelty tightened past the literal prescription (also in #2469): a rename's head is checked at its base path, so a pre-existing external module renamed into the closure fails novelty too, not just a same-name pull-in.
  • Rewritten moves (-M defeat) (Cubic round-2 P2): git's similarity pairing can miss a rewritten move, so the new path would pass exists. Fixed with deletedSourcesSince (no -M) + movedFromDeletedSource (≥2 shared normalized statements = move signal; one is coincidence), planted test included.
  • Weight-scoping question ("compare weight only across changed/added files?") answered on the PR as an issue comment: scoped weight is weaker (offsets in changed files still fund growth) and harsher on honest splits; the novelty fact is what closes the funding channel.

Round 3 (Cubic @ efb0176, fixed in 0749922d9):

  • Cost comment process count: the gate's header promised four merge-base git processes; the novelty fact adds a fifth — the -M-less delete diff (a rewritten move evades similarity pairing, so its deletions need their own listing; their contents come from the base tree's existing cat-file batch). Comment updated with the full enumeration.
  • ADR 0027 deleted-source claim: "carrying no deleted source's statements" stated the guarantee absolutely; the gate checks the conservative textual movedFromDeletedSource probe. The ADR and the rule header now state what is verified — "no verbatim transplant of a deleted source," not "no repurposed logic" — and what bounds the residue.

Round 4 (maintainer approval @ 0749922, non-blocking docstring fix in e407ad338):

  • deletedSourcesSince docstring: claimed the diff runs "WITHOUT -M" so paired renames stay visible — backwards. Plain git diff pairs renames by default and --diff-filter=D drops the paired ones; the list covers only deletions pairing did NOT absorb, and paired renames are answered by renamedSince. The corrected docstring also records the companion constraint: --no-renames would put a re-homed hub into the deleted set and refuse the very splits the tolerance exists for (asymmetry verified in a scratch repo). Same claim fixed at its two siblings: the rule's deletedSourceTexts field doc and the gate's cost-comment enumeration.

Round 5 (Cubic @ e407ad3, fixed in df95c943a):

  • Probe-completeness claim in deletedSourcesSince: "such a move stays non-novel" was unqualified where the implementing comment and ADR 0027 are precise. The docstring now states the probe's rule and limits — two-or-more statements with ONE deleted source is the move signal, one is tolerated as coincidence, a statement-by-statement rewrite evades a textual match — and positions the probe as the reinforcement while containment is the structural refusal.

Round 6 (maintainer re-review @ df95c94, fixed in 3c6885bc1):

  • Ambient-config dependency: the deleted-source probe leaned on git's DEFAULT rename pairing while its comment called that pairing load-bearing — a diff.renames=false gitconfig would list every re-homed split hub as a deleted source and refuse honest splits. The argv now requests pairing explicitly (--find-renames), verified under -c diff.renames=false in a scratch repo: the old argv leaks the hub, the shipped one lists nothing. Docstrings and the gate's cost comment state that pairing is requested, not defaulted.