diff --git a/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts b/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts index 6beadc3a7..0e31cf518 100644 --- a/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts +++ b/gitnexus-shared/src/scope-resolution/finalize-algorithm.ts @@ -392,7 +392,13 @@ function makeEdgeDrafts( // and resolved-dynamic imports are terminal at the file level — no // `targetDefId` needed since they materialize no `BindingRef`. Pre- // finalize them here so the fixpoint loop skips them entirely. - const targetFiles = Array.isArray(targetFile) ? targetFile : [targetFile]; + // Annotated rather than inferred: `isArray`'s `arg is any[]` predicate widens + // the true branch to a MUTABLE array, and a resolver may hand back a cached, + // frozen candidate list (Kotlin's `dirChildren` buckets do). Only `.map` is + // wanted here, so pinning `readonly` makes an in-place `.sort()`/`.push()` — + // which would reorder that resolver's index for the rest of the run — a + // compile error rather than a runtime TypeError. + const targetFiles: readonly string[] = Array.isArray(targetFile) ? targetFile : [targetFile]; const isFileLevelTerminal = parsed.kind === 'side-effect' || parsed.kind === 'dynamic-resolved'; return targetFiles.map((tf) => { const base: ImportEdge = { diff --git a/gitnexus/bench/import-target/baselines.json b/gitnexus/bench/import-target/baselines.json index c5b57cc66..1a158f5d8 100644 --- a/gitnexus/bench/import-target/baselines.json +++ b/gitnexus/bench/import-target/baselines.json @@ -1,18 +1,18 @@ { - "_what": "Baselines for bench/import-target/measure.mjs \u2014 EVERY import-target resolver registered in SCOPE_RESOLVERS, on one shared corpus, plus csharp a second time WITH csproj configs. One entry per registered language and one more for the csproj arm, no registered language ungated \u2014 and that is ASSERTED rather than asserted-in-a-comment, which is also why no roster of language names is kept in this prose to go stale: measure.mjs derives its language list from a LANG_REGISTRY table and a --check inventory arm reconciles that table against SCOPE_RESOLVERS in both directions. A C/C++ #include is an import site for this purpose and is gated like every other registered language. csharp and csharp_csproj resolve the IDENTICAL file corpus (buildFiles aliases the two) and differ in exactly one thing: whether csharpConfigs is supplied. Without that second arm the csproj namespace-directory index ships unmeasured, because every C# import in the no-csproj arm returns before reaching it. C and C++ follow that same precedent for a different context \u2014 their HEADERS arrive through resolutionConfig rather than through allFilePaths, and augmentedFilePaths unions the two once per pass, so the corpus is split at newPass rather than pre-merged. The first nine were added as their own O(imports x files) scans were indexed away (#2877/#2878/#2879/#2880, #2872, #2901, #2902, #2908) and this is the forward guard on each; the other eight were ungated until now, and PR #2911 \u2014 JavaScript reaching suffixResolve with no index at all, 25972 us per import at 8000 files \u2014 is what that costs.", - "_fingerprint_note": "Per-language sha256 over every distinct fromFile|target -> resolved target. A change here is a BEHAVIOUR change: the resolver returned a different target set, and IMPORTS/CALLS edges moved. Explain it, never re-baseline to make CI green. For the languages these PRs changed, the pre-change implementations produce these same values on this corpus at both 400 and 1600 files \u2014 that is what makes the index hoist a performance change. The tie-break-level proof lives in test/unit/scope-resolution/import-target-index-parity.test.ts (verbatim copies of the pre-change code, diffed) for Kotlin in test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts, and for the four resolvers added there in test/unit/scope-resolution/{php,java,cobol}-import-target-parity.test.ts and test/unit/import-resolvers/csharp-csproj-parity.test.ts, and for JavaScript in test/unit/scope-resolution/javascript-import-target-parity.test.ts (a differential over 211200 old-vs-new pairs, PR #2911). The eight languages added last have no per-language parity harness against a pre-change implementation and do NOT need one: nothing about their resolution changed, so there is no before to diff against. Their fingerprints are pure forward guards, minted from the current implementations, and their adapter-boundary index reuse is covered for every registered language at once by test/unit/scope-resolution/import-target-index-reuse.contract.test.ts. NOTE for csharp_csproj: on this corpus the #2902 indexed leg (step 3 of resolveCSharpImportInternal) is reached by 2221 of the 3200 small-arm imports but answers null for every one of them \u2014 the 979 that resolve do so at step 2 \u2014 so this fingerprint pins that legs cost and its null answers, while its positive tie-breaks (first-occurrence, unanchored substring, iteration order) are pinned by csharp-csproj-parity.test.ts.", - "_shape_note": "files/imports/resolved/distinct_outcomes AND the fingerprint are asserted exactly, per scale. A fingerprint alone cannot tell a legitimate resolution change from a corpus quietly shrunk below the size at which the timing arms can see anything; conversely the counts alone cannot see a defect confined to one arm, because the arms differ only in path padding and directory layout and both of those are count-neutral by design. Two cross-arm assertions close the remaining hole: the deep and collide arms must resolve exactly what small resolves (they are the same workload), and each of their fingerprints must DIFFER from small's (they are not the same corpus). Without the second, setting DEEP_PAD to 0 \u2014 which deletes the entire depth arm \u2014 moves no asserted number and prints PASS; the same is true of a collideDir that forwards to uniqueDir. THE HEAP ARM IS ASSERTED THE SAME WAY, by the same loop, and was not before: files_small, files_large, path_segments and probe decide WHAT it measures, and every one of them was reported and compared to nothing. Swapping HEAP_PROBE_TARGET.csharp_csproj for a target matching no CSPROJ_CONFIGS rootNamespace skips the whole config loop, so the getFilesInDir and getInsensitive legs never run and the arm the header calls the witness that the read pattern IS the footprint quietly becomes a two-map arm \u2014 73703384 -> 59921216 B, ratio 1.017 -> 1.011, ceiling and floor both still passing and --check still exiting 0. Setting HEAP_SMALL equal to HEAP_LARGE is the same hole from the other side: ratio goes to ~1.0 by construction and bytes_large never moves. bytes_small and bytes_large are deliberately NOT asserted for equality \u2014 heap_ceiling_bytes and the heap_reading_bytes floor bound them with ~50% either way, because heapUsed accounting moves across platforms and Node majors and an exact byte assertion would be a re-baseline per runner. THE CONTEXT ARM IS ASSERTED THE SAME WAY, by the same loop, and more strictly than either: target, with_context and without_context are exact strings with no tolerance at all, because the arm resolves one import over a three-file corpus and has no measurement noise to tolerate. A separate check requires the last two to DIFFER, for the same reason deep.fingerprint must differ from small.fingerprint \u2014 a probe on which both call shapes agree asserts one number twice. Both halves run through resolveOne, so what the arm gates is this bench threading run.ts's fifth argument, not the resolvers' behaviour.", - "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT \u2014 the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) and Kotlin suffixByStem emit one entry per component, so they legitimately sit above 1.0 while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x \u2014 and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION \u2014 this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number \u2014 measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 \u2014 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 \u2014 no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all \u2014 harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it \u2014 same corpus, same getWorkspaceFileIndex, three maps instead of one \u2014 it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release \u2014 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths — 37% of what this arm used to read was empty array slots — the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE \u2014 do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% \u2014 identical to the byte \u2014 on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way \u2014 true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs \u2014 tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost — 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in import-resolvers/python.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` — the package probe's recursion re-ran the whole tail on identical inputs — and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 \u2014 its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 \u2014 python 1.097, javascript 1.083, typescript 1.053, vue 1.079 \u2014 and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) \u2014 the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 \u2014 a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter \u2014 if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK \u2014 ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s \u2014 see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another \u2014 i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) \u2014 its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms \u2014 which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL \u2014 the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP: small_ms 27.762 -> 35.125 (+26.5%) and collide_ms 29.407 -> 36.182 (+23.0%), which is filesByDirectory plus, on every import that resolves, a candidate gather over the resolved file's directory and a localDefs filter; the ms ceilings keep PHP's own 4.21x and 4.26x multipliers (117 -> 148, 125 -> 154). depth_ratio 1.144 -> 1.283 and the 1.9 budget is UNCHANGED, which makes it 1.48x measured rather than 1.66x: directoryAliases emits one entry per path segment, so filesByDirectory is O(files x depth) and the depth arm is the only one that can see it \u2014 that budget got TIGHTER relative to its measurement, not looser, and 1.48x sits inside the 1.37-1.75x band the other sixteen carry. Its heap reading rises 37576816 -> 49574008 (+31.9%) for the same structure, and the reading is the MEMO rather than the workspace it indexes: newPass allocates the ParsedFile objects before retainedPassBytes takes its baseline sample, so they sit outside the delta. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later \u2014 which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch \u2014 the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x \u2014 far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 \u2014 both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles \u2014 see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", - "_triage": "Every ratio and ms ceiling here is a TIMING signal \u2014 re-run on an idle machine before investigating; runner contention dominates. depth_ratio is the noisiest of them by a wide margin (it divides two sub-3 ms numbers, and Dart's are sub-1 ms): if exactly one arm fails and it is that one, suspect the machine first. N is 15 for every language whose cheapest arm is under 5 ms, rather than this bench's original 5, specifically to hold that arm's peak-to-peak swing under 1.26x \u2014 see _arms_note for the measured distributions and for why the six languages that drop to 7-8 are the ones where cell size makes it safe \u2014 so a depth_ratio failure that REPRODUCES is a real signal, not noise. Each language's chosen N is printed as `reps`; read it before blaming the estimator. The fingerprint, shape and heap arms are the opposite: deterministic (over 4 runs the heap arm's widest spread was 0.11% on python and 0.00% on java, javascript and c), a re-run never changes them, and they must never be wished away. TWO heap failures mean the arm STOPPED MEASURING rather than that memory grew, and both are deterministic: a heap floor failure says the probe no longer forces the index it used to (this is how four arms read 0 B when buildSuffixIndex went lazy, and 0 B passes every ceiling), and a `heap probe ... resolved` throw says a probe target that must MISS now hits, so the reading is a materialized answer and the legs past it were never reached. A heap BOUND failure is deterministic in the same way and means one specific thing: a language excluded from the budgeted tier has grown a structure, or started asking its index a question it did not ask when the exclusion was recorded \u2014 never a timing signal, never a re-run, and never fixed by raising the bound without saying what grew. The context arm is deterministic too, and a failure there means one specific thing rather than a range of them: run.ts's fifth argument is not reaching that resolver from this bench, or the leg behind it stopped running. Never a timing signal, never a re-run.", - "_floor": "Measured against the pre-change implementations on THIS corpus at 150/600 files: go 3.36, csharp 4.10, dart 3.32, ruby 3.87. The issues report 4.00 / 3.43 / 4.05 on their own corpora; those are DIFFERENT numbers from different repositories and are not reproduced here \u2014 what they and these share is that both independently land in the quadratic band, well clear of the ~1.0 a linear result gives. Note also that this floor was taken at 150/600 while the gate runs at 400/1600, so it is a lower bound on what the pre-change code would score today. Kotlin's own bench measured its pre-index floor at 3.737. The four resolvers added later were NOT re-floored on this corpus, and the reason is that they do not need to be: every one of their pre-change legs walked the whole file set per import (PHP one findIndex per path part per extension, Java one scan per stripped prefix, COBOL two full scans per COPY, C# csproj one normalizedFileList pass per import per matching config), so their scaling_ratio is ~4 by construction rather than by measurement. Their per-import costs were measured on their own issue corpora instead: PHP 96.40 ms -> 0.036 ms, Java 8.05 ms -> 0.62 ms, COBOL 3879 us -> 10.5 us, C# csproj 1103 us -> 7.6 us. The 1.8 budget sits well above the linear result and well below every one of those. The eight languages added last were NOT floored either, and for a different reason again: they are not fixes, so there is no pre-change implementation to floor against. Their scaling budgets are the global linear 1.8 and the point of the arms is to hold the current numbers (measured 1.01-1.13) rather than to separate a fix from a break. The one exception is javascript, which IS a fix and does have a floor: 6448.9 us per import at 2000 files and 25972.6 us at 8000 \u2014 4.12x the per-import cost for 4x the files, i.e. O(imports x files) \u2014 against 28.5 / 27.4 us with the index PR #2911 gave it, and 25.0 / 27.0 us for TypeScript over the identical corpus.", + "_what": "Baselines for bench/import-target/measure.mjs — EVERY import-target resolver registered in SCOPE_RESOLVERS, on one shared corpus, plus csharp a second time WITH csproj configs. One entry per registered language and one more for the csproj arm, no registered language ungated — and that is ASSERTED rather than asserted-in-a-comment, which is also why no roster of language names is kept in this prose to go stale: measure.mjs derives its language list from a LANG_REGISTRY table and a --check inventory arm reconciles that table against SCOPE_RESOLVERS in both directions. A C/C++ #include is an import site for this purpose and is gated like every other registered language. csharp and csharp_csproj resolve the IDENTICAL file corpus (buildFiles aliases the two) and differ in exactly one thing: whether csharpConfigs is supplied. Without that second arm the csproj namespace-directory index ships unmeasured, because every C# import in the no-csproj arm returns before reaching it. C and C++ follow that same precedent for a different context — their HEADERS arrive through resolutionConfig rather than through allFilePaths, and augmentedFilePaths unions the two once per pass, so the corpus is split at newPass rather than pre-merged. The first nine were added as their own O(imports x files) scans were indexed away (#2877/#2878/#2879/#2880, #2872, #2901, #2902, #2908) and this is the forward guard on each; the other eight were ungated until now, and PR #2911 — JavaScript reaching suffixResolve with no index at all, 25972 us per import at 8000 files — is what that costs.", + "_fingerprint_note": "Per-language sha256 over every distinct fromFile|target -> resolved target. A change here is a BEHAVIOUR change: the resolver returned a different target set, and IMPORTS/CALLS edges moved. Explain it, never re-baseline to make CI green. For the languages these PRs changed, the pre-change implementations produce these same values on this corpus at both 400 and 1600 files — that is what makes the index hoist a performance change. The tie-break-level proof lives in test/unit/scope-resolution/import-target-index-parity.test.ts (verbatim copies of the pre-change code, diffed) for Kotlin in test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts, and for the four resolvers added there in test/unit/scope-resolution/{php,java,cobol}-import-target-parity.test.ts and test/unit/import-resolvers/csharp-csproj-parity.test.ts, and for JavaScript in test/unit/scope-resolution/javascript-import-target-parity.test.ts (a differential over 211200 old-vs-new pairs, PR #2911). The eight languages added last have no per-language parity harness against a pre-change implementation and do NOT need one: nothing about their resolution changed, so there is no before to diff against. Their fingerprints are pure forward guards, minted from the current implementations, and their adapter-boundary index reuse is covered for every registered language at once by test/unit/scope-resolution/import-target-index-reuse.contract.test.ts. NOTE for csharp_csproj: on this corpus the #2902 indexed leg (step 3 of resolveCSharpImportInternal) is reached by 2221 of the 3200 small-arm imports but answers null for every one of them — the 979 that resolve do so at step 2 — so this fingerprint pins that legs cost and its null answers, while its positive tie-breaks (unanchored substring, iteration order) are pinned by csharp-csproj-parity.test.ts. NOTE for kotlin, go, csharp and java: twenty fingerprints across these four languages were re-baselined in #2881, the one deliberate behaviour change any language in this file has had. It landed in two steps and the second is the reason the first is not a special case: Kotlin first, then the shared package-dir-index (go, java, csharp) and the csproj namespace index once the same rule was found live there. `getKotlinFileIndex` no longer requires a file's package directory to be the FIRST occurrence of that name in its own path, so the unique arm's `d % 7` nested slice (`mod{d}/src/main/kotlin/com/example/pkg{d}/inner/pkg{d}`) now belongs to package `pkg{d}` and its wildcard imports resolve: resolved 1100 -> 1153 small and deep, 4456 -> 4681 large. The collide arm needed a CORPUS edit alongside it, not just a new number — its `d % 7` slice deliberately imported `com.example.vendor{d}`, a package that exists nowhere, purely to mirror the unique arm's nested-slice MISS, so leaving it would have left collide at 1100 against small's 1153 and broken the same-workload invariant the arm is built on (that assertion is what caught it). It now uses the same `com.example.models.*` spelling as the rest of the arm, which is why its distinct_outcomes fell (2775 -> 2744, 11087 -> 10961): one shared target instead of one per d. The record-level evidence for the resolver change — 235 of 19968 records moved, 54 null -> resolved, 0 buckets losing a member — is in bench/kotlin-import-target/baselines.json `_provenance`. The kotlin heap_reading_bytes and heap_ceiling_bytes moved with it, together as `_heap_reading_note` requires: 48073096 -> 48200224 bytes_large (+127128, +0.264%), ceiling still exactly 1.5x. Small, and it is worth saying WHY it is small rather than reading the number as evidence that the change is cheap. `dirChildren` grows by one entry per component-suffix the old rule used to skip, and this arm can only see part of that: the heap corpus is built with HEAP_PAD 8, which prefixes every path with `d0/…/d7/`, so no path can begin with a suffix of its own directory and the leading-segment half of the old rule is structurally invisible here. What moves the reading is the `d % 7` nested slice alone. Read +0.264% as this arm's ceiling on the effect, not as the effect. GO NEEDED A CORPUS EDIT TO BE GATED AT ALL. Its nested slice was `src/pkg{d}/internal/pkg{d}`, repeating only the LAST segment, while a Go query addresses the whole package path `src/pkg{d}` — so the directory never even ended with the query and the first-occurrence rule was never reached. Every go arm sat unchanged through the resolver fix. `uniqueDir`/`collideDir` now repeat the shape at the granularity Go actually queries (`src/pkg{d}/internal/src/pkg{d}`, `svc{d}/internal/sub/svc{d}/internal`), which is what moved go from 979 to 1153 resolved and bumped `languages.go.heap.path_segments` 13 -> 14. The general lesson: a corpus that carries a shape the QUERY cannot express does not gate that shape. CSHARP AND JAVA HIT THE SAME COLLIDE-ARM TRAP AS KOTLIN. Both collide arms sent their `d % 7` slice to a namespace that exists nowhere (`App.Src{d}.Vendor`, `com.svc{d}.vendor`) purely to MIRROR the unique arm's nested-slice miss; once that miss became a hit, collide sat at 979/1100 against small's 1153 and the same-workload assertion failed. Both now use the same spelling as the rest of their arm. HEAP: no reading here moved for the resolver change. An earlier revision of this branch re-recorded `csharp_csproj` 73703384 -> 73116520 as a -0.79% effect of the step-2 filter; review measured base and branch three times each and got the same 73.10e6 on BOTH sides — the recorded 73703384 was simply not reproducible on this box, and re-recording it would have dropped that language's derived floor by 0.8% for no reason belonging to this change. Reverted. Everything else sat within +/-0.03%. Note that `_heap_reading_note`'s claim that these readings 'reproduce to the byte across processes on one box' did NOT hold on the box this was measured on: go, dart, ruby, python, php and cpp all wandered by a few hundred to a few thousand bytes between processes with no code change touching them. Treat sub-0.05% movement as jitter, not signal. HEAP, kotlin, second movement: 48200224 -> 42802456 (-11.20%), re-recorded with its ceiling. `getKotlinFileIndex` now compacts each `dirChildren` bucket as it freezes it. `addChild` mints a bucket as `[raw]` and pushes the rest, and V8 grows a backing store by `old + old/2 + 16`, so the second child takes a 1-slot store to 17: 61144 buckets, 52.9% of their slots empty, 88 B each. Same fix and same accounting as the python `byBasename` sentence above. Note what this means for the gate: a memory WIN of this size passes every arm — it is under the ceiling and over the 0.5x floor — so it is recorded because the convention says a reading and its ceiling move together, not because anything went red. kotlin now reads 40.82 MiB. The prose in measure.mjs calling it '45.85 MiB, the second-largest reading in this file' is corrected with it — and was already wrong on the ranking before this change, since csharp_csproj (69.73) and php (47.28) both read higher; kotlin was third. A measurement written into prose is not re-taken, which is the finding `_heap_bound_note` records about this very file. One further corpus edit, made in review and MEASURED rather than assumed: kotlin's collide layout repeated only the `models` leaf (`…/com/example/models/inner/models`) while a Kotlin query addresses the whole dotted path, so a full revert of the Kotlin guards left both collide fingerprints UNMOVED — the arm was blind to the rule it was re-baselined for. Deepening it to `…/models/inner/com/example/models` makes the revert move both, and those two fingerprints are the only ones that changed for it. The same deepening was applied to the java and kotlin UNIQUE arms and REVERTED: it moved ten more fingerprints, grew java's heap reading 43%, and bought nothing — progressive stripping lands those queries on the same file with or without the rule, so the control still failed only on go.", + "_shape_note": "files/imports/resolved/distinct_outcomes AND the fingerprint are asserted exactly, per scale. A fingerprint alone cannot tell a legitimate resolution change from a corpus quietly shrunk below the size at which the timing arms can see anything; conversely the counts alone cannot see a defect confined to one arm, because the arms differ only in path padding and directory layout and both of those are count-neutral by design. Two cross-arm assertions close the remaining hole: the deep and collide arms must resolve exactly what small resolves (they are the same workload), and each of their fingerprints must DIFFER from small's (they are not the same corpus). Without the second, setting DEEP_PAD to 0 — which deletes the entire depth arm — moves no asserted number and prints PASS; the same is true of a collideDir that forwards to uniqueDir. THE HEAP ARM IS ASSERTED THE SAME WAY, by the same loop, and was not before: files_small, files_large, path_segments and probe decide WHAT it measures, and every one of them was reported and compared to nothing. Swapping HEAP_PROBE_TARGET.csharp_csproj for a target matching no CSPROJ_CONFIGS rootNamespace skips the whole config loop, so the getFilesInDir and getInsensitive legs never run and the arm the header calls the witness that the read pattern IS the footprint quietly becomes a two-map arm — 73703384 -> 59921216 B, ratio 1.017 -> 1.011, ceiling and floor both still passing and --check still exiting 0. Setting HEAP_SMALL equal to HEAP_LARGE is the same hole from the other side: ratio goes to ~1.0 by construction and bytes_large never moves. bytes_small and bytes_large are deliberately NOT asserted for equality — heap_ceiling_bytes and the heap_reading_bytes floor bound them with ~50% either way, because heapUsed accounting moves across platforms and Node majors and an exact byte assertion would be a re-baseline per runner. THE CONTEXT ARM IS ASSERTED THE SAME WAY, by the same loop, and more strictly than either: target, with_context and without_context are exact strings with no tolerance at all, because the arm resolves one import over a three-file corpus and has no measurement noise to tolerate. A separate check requires the last two to DIFFER, for the same reason deep.fingerprint must differ from small.fingerprint — a probe on which both call shapes agree asserts one number twice. Both halves run through resolveOne, so what the arm gates is this bench threading run.ts's fifth argument, not the resolvers' behaviour.", + "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT — the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) and Kotlin suffixByStem emit one entry per component, so they legitimately sit above 1.0 while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x — and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION — this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number — measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 — 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 — no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all — harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it — same corpus, same getWorkspaceFileIndex, three maps instead of one — it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release — 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths — 37% of what this arm used to read was empty array slots — the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE — do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% — identical to the byte — on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way — true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs — tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost — 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in import-resolvers/python.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` — the package probe's recursion re-ran the whole tail on identical inputs — and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 — its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 — python 1.097, javascript 1.083, typescript 1.053, vue 1.079 — and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) — the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 — a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter — if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK — ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s — see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another — i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) — its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms — which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL — the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP: small_ms 27.762 -> 35.125 (+26.5%) and collide_ms 29.407 -> 36.182 (+23.0%), which is filesByDirectory plus, on every import that resolves, a candidate gather over the resolved file's directory and a localDefs filter; the ms ceilings keep PHP's own 4.21x and 4.26x multipliers (117 -> 148, 125 -> 154). depth_ratio 1.144 -> 1.283 and the 1.9 budget is UNCHANGED, which makes it 1.48x measured rather than 1.66x: directoryAliases emits one entry per path segment, so filesByDirectory is O(files x depth) and the depth arm is the only one that can see it — that budget got TIGHTER relative to its measurement, not looser, and 1.48x sits inside the 1.37-1.75x band the other sixteen carry. Its heap reading rises 37576816 -> 49574008 (+31.9%) for the same structure, and the reading is the MEMO rather than the workspace it indexes: newPass allocates the ParsedFile objects before retainedPassBytes takes its baseline sample, so they sit outside the delta. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later — which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch — the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x — far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 — both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles — see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", + "_triage": "Every ratio and ms ceiling here is a TIMING signal — re-run on an idle machine before investigating; runner contention dominates. depth_ratio is the noisiest of them by a wide margin (it divides two sub-3 ms numbers, and Dart's are sub-1 ms): if exactly one arm fails and it is that one, suspect the machine first. N is 15 for every language whose cheapest arm is under 5 ms, rather than this bench's original 5, specifically to hold that arm's peak-to-peak swing under 1.26x — see _arms_note for the measured distributions and for why the six languages that drop to 7-8 are the ones where cell size makes it safe — so a depth_ratio failure that REPRODUCES is a real signal, not noise. Each language's chosen N is printed as `reps`; read it before blaming the estimator. The fingerprint, shape and heap arms are the opposite: deterministic (over 4 runs the heap arm's widest spread was 0.11% on python and 0.00% on java, javascript and c), a re-run never changes them, and they must never be wished away. TWO heap failures mean the arm STOPPED MEASURING rather than that memory grew, and both are deterministic: a heap floor failure says the probe no longer forces the index it used to (this is how four arms read 0 B when buildSuffixIndex went lazy, and 0 B passes every ceiling), and a `heap probe ... resolved` throw says a probe target that must MISS now hits, so the reading is a materialized answer and the legs past it were never reached. A heap BOUND failure is deterministic in the same way and means one specific thing: a language excluded from the budgeted tier has grown a structure, or started asking its index a question it did not ask when the exclusion was recorded — never a timing signal, never a re-run, and never fixed by raising the bound without saying what grew. The context arm is deterministic too, and a failure there means one specific thing rather than a range of them: run.ts's fifth argument is not reaching that resolver from this bench, or the leg behind it stopped running. Never a timing signal, never a re-run. TIGHTENED IN #2881, because the measurements they bound got faster and a budget left alone while its reading falls is a gate loosening without anyone deciding to. Each new value holds the headroom the old one expressed over the old reading, computed from `_measured` on both sides: kotlin depth 3.4 -> 2.8 (reading 2.219 -> 1.813), go depth 1.6 -> 1.4 (1.169 -> 0.999), csharp depth 2.2 -> 2.0 (1.438 -> 1.279), java depth 2.2 -> 2.1 (1.402 -> 1.354), kotlin collide_scaling 1.8 -> 1.65 (1.179 -> 1.081), go collide_scaling 5.5 -> 5.1 (3.763 -> 3.465). The ABSOLUTE ms ceilings were deliberately NOT tightened by the same reasoning: they carry runner-contention headroom rather than measurement headroom, and a ratio is runner-speed-invariant where a millisecond is not.", + "_floor": "Measured against the pre-change implementations on THIS corpus at 150/600 files: go 3.36, csharp 4.10, dart 3.32, ruby 3.87. The issues report 4.00 / 3.43 / 4.05 on their own corpora; those are DIFFERENT numbers from different repositories and are not reproduced here — what they and these share is that both independently land in the quadratic band, well clear of the ~1.0 a linear result gives. Note also that this floor was taken at 150/600 while the gate runs at 400/1600, so it is a lower bound on what the pre-change code would score today. Kotlin's own bench measured its pre-index floor at 3.737. The four resolvers added later were NOT re-floored on this corpus, and the reason is that they do not need to be: every one of their pre-change legs walked the whole file set per import (PHP one findIndex per path part per extension, Java one scan per stripped prefix, COBOL two full scans per COPY, C# csproj one normalizedFileList pass per import per matching config), so their scaling_ratio is ~4 by construction rather than by measurement. Their per-import costs were measured on their own issue corpora instead: PHP 96.40 ms -> 0.036 ms, Java 8.05 ms -> 0.62 ms, COBOL 3879 us -> 10.5 us, C# csproj 1103 us -> 7.6 us. The 1.8 budget sits well above the linear result and well below every one of those. The eight languages added last were NOT floored either, and for a different reason again: they are not fixes, so there is no pre-change implementation to floor against. Their scaling budgets are the global linear 1.8 and the point of the arms is to hold the current numbers (measured 1.01-1.13) rather than to separate a fix from a break. The one exception is javascript, which IS a fix and does have a floor: 6448.9 us per import at 2000 files and 25972.6 us at 8000 — 4.12x the per-import cost for 4x the files, i.e. O(imports x files) — against 28.5 / 27.4 us with the index PR #2911 gave it, and 25.0 / 27.0 us for TypeScript over the identical corpus.", "scaling_budget": 1.8, "collide_scaling_budget": { - "go": 5.5, + "go": 5.1, "csharp": 3.4, "csharp_csproj": 1.8, "dart": 3.3, "ruby": 1.8, - "kotlin": 1.8, + "kotlin": 1.65, "php": 1.8, "java": 3.4, "cobol": 1.8, @@ -26,14 +26,14 @@ "cpp": 4 }, "depth_budget": { - "go": 1.6, - "csharp": 2.2, + "go": 1.4, + "csharp": 2.0, "csharp_csproj": 2.3, "dart": 1.6, "ruby": 2.2, - "kotlin": 3.4, + "kotlin": 2.8, "php": 1.9, - "java": 2.2, + "java": 2.1, "cobol": 1.6, "swift": 2.3, "rust": 2.1, @@ -85,7 +85,7 @@ "heap_ceiling_bytes": { "vue": 43326024, "typescript": 40117944, - "kotlin": 72109644, + "kotlin": 46000000, "go": 4497696, "dart": 11751300, "cpp": 15035016, @@ -98,11 +98,12 @@ "javascript": 40200000, "c": 15000000 }, - "_heap_reading_note": "The measured bytes_large each heap_ceiling_bytes entry above is 1.5x, recorded so the FLOOR can be derived from the reading instead of from the ceiling. It used to be 0.33 x the ceiling, described as 'half the measured size' — which held only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. 0.5 x the reading is the same effective floor to within 0.8% for all eight and says what it means. These are NOT asserted for equality: they reproduce to the byte across processes on one box, but a Node major or a different platform moves heapUsed accounting, and the ceiling/floor pair is what tolerates that (+50%/-50%). Re-baseline a ceiling and re-baseline the reading with it — they are two views of one measurement.", + "_heap_reading_note": "The measured bytes_large each heap_ceiling_bytes entry above is 1.5x — every entry except kotlin's, which is 1.0747x for a stated reason (see _heap_compaction_gate). Recorded so the FLOOR can be derived from the reading instead of from the ceiling. It used to be 0.33 x the ceiling, described as 'half the measured size' — which held only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. 0.5 x the reading is the same effective floor to within 0.8% for all eight and says what it means — and it is what let kotlin's ceiling be tightened to 1.0747x without moving kotlin's floor by a byte, which is exactly the independence this key was introduced for. These are NOT asserted for equality: they reproduce to the byte across processes on one box, but a Node major or a different platform moves heapUsed accounting, and the ceiling/floor pair is what tolerates that (+50%/-50%, and +7.5%/-50% for kotlin). Re-baseline a ceiling and re-baseline the reading with it — they are two views of one measurement.", + "_heap_compaction_gate": "WHY KOTLIN'S CEILING IS TIGHT AND EVERY OTHER ONE IS 1.5x. It is the only ceiling in this file that gates a size REDUCTION being preserved rather than a footprint not growing: #2881 compacts getKotlinFileIndex's dirChildren buckets (`bucket.slice()` before the freeze), and until this entry existed nothing anywhere could see that compaction disappear. MEASURED, not assumed — head against a copy of languages/kotlin/import-target.ts with the slice deleted and Object.freeze kept, one process, the same corpus this arm builds: bytes_large 42805256 -> 48184784 (+12.57%), bytes_small 10676432 -> 12020736 (+12.6%), byte-identical over three runs. NOTHING ELSE MOVES for that mutation. Every arm of bench/kotlin-import-target is output-identical (its fingerprint, cases and non_null cannot see an array's spare capacity); test/unit/scope-resolution/kotlin/kotlin-index-internals.test.ts stays green and says so in its own header, because a JS array's backing-store capacity has no reflective surface; heap ratio is 1.002 either way, since both scales grow together and a ratio divides the growth out; and at the old ceiling of 64203684 the heap arm passed with 25% to spare. DIRECTION MATTERS: compaction RECLAIMS, so losing it makes the reading GROW. The gate is therefore the CEILING. A floor cannot see this mutation in any sizing, and kotlin's floor stays the file-wide 0.5 x reading. WHERE THE 5.4 MB COMES FROM, so the number can be re-derived rather than trusted: the heap corpus is 32000 files over 4000 directories, 8 files each, and a directory contributes one dirChildren key per component-suffix of its path (~15.3 keys at HEAP_PAD 8), so ~61000 buckets of length 8. On this repo's Node a bucket minted as [raw] and pushed to 8 sits in a 19-slot backing store — the capacity steps kotlin-index-internals.test.ts records — leaving 11 slots, 88 B, of retained slack per bucket. 61000 x 88 B is ~5.4 MB, which is the delta. HOW 46000000 WAS CHOSEN: reading 42802456, plus 7.5% is 46012640, rounded down to 46000000 (1.0747x). PROVEN both ways through the real gate, not argued: a full `--check` over a copy of measure.mjs whose only difference is the kotlin import, pointed at a resolver with the slice deleted, reads 48203376 B (45.97 MiB) and fails on THIS ARM ALONE — every fingerprint, every corpus count, every timing ratio and the heap ratio all stay green, which is the claim 'nothing else moves' turned into a run. That is 4.8% clear above the ceiling. Both margins are three orders of magnitude larger than the measurement's own spread (peak-to-peak 1.0001 over three runs of the isolated arm, 1.0004 over the five runs _heap_bound_note records). The 7.5% is also an order of magnitude above the widest cross-run movement any heap arm in this file shows on this box: kotlin itself reads 42802456 B in a full `--check`, byte-identical to the recorded value, and the noisiest reading here — csharp_csproj, the one prior sessions found unreproducible — moves 0.78% between runs. A LOADED RUNNER DOES NOT MOVE THIS NUMBER and the tolerance is not for one: this is a forced-GC heapUsed delta over structures held alive across the window (see HEAP_RETAINED), so scheduler contention has no term in it. What can move it is heapUsed ACCOUNTING — a Node major, a heap above the pointer-compression cage, a 32-bit platform. TRIAGE, and it is what makes the tight ceiling safe to run: that class of change moves EVERY reading in the run, so compare kotlin against the other 13 budgeted readings in the SAME run before touching this key. kotlin alone over its ceiling with the rest of the file at its recorded values is a lost compaction; everything moving together is a runner change and a whole-file re-baseline. WHAT IT DOES NOT CATCH: any regression under 7.5%, and a compaction that still runs while something else in the index grows to fill the headroom.", "heap_reading_bytes": { "vue": 28884016, "typescript": 26745296, - "kotlin": 48073096, + "kotlin": 42802456, "go": 2998464, "dart": 7834200, "cpp": 10023344, @@ -115,7 +116,7 @@ "javascript": 26745296, "c": 10018816 }, - "_heap_bound_note": "THE SECOND HEAP TIER. Every registered language is measured now; heap_bound_bytes gates the nine that are not BUDGETED above, and it gates them with one comparison and no floor. A ceiling says 'this index is not too big'. A bound says something narrower and it is the thing that was missing: 'the exclusion still holds' — this language has not grown an index since it was left out. measure.mjs's MEMORY section states the re-entry condition (if a language ever diverges in what it ASKS its index, it earns a budgeted arm) and until now nothing watched for the divergence; HEAP_LANGS was a hand-maintained list of eight whose two neighbours, LANG_REGISTRY and CONTEXT_LANGS, are both reconciled against a derived predicate in both directions. HEAP_BOUNDED is derived too — it is LANGS minus HEAP_BUDGETED — so the two tiers partition the languages and a new one cannot land outside both. WHAT RE-MEASURING FOUND, five runs each, maximum quoted, peak-to-peak in brackets. go 2998464 B [1.0021], dart 7834200 B [1.0006] and kotlin 48073096 B [1.0004] HAD NO STATED REASON AT ALL: the old prose opened 'SIX of the seventeen are deliberately NOT in HEAP_LANGS' against a list of eight of seventeen, and these three were the three nobody counted. All three retain a real per-pass structure (go's PackageDirIndex, dart's basename buckets, kotlin's suffixByStem cascade) and kotlin's 45.85 MiB is the second-largest reading in this file, above ruby's 39.12 and java's 33.34, both of which carry a full budget. swift 3449216 B [1.0024] and cobol 2320456 B [1.0000] were excluded as 'below the measurement's own noise floor' on readings of 0.29 MB and 0 B at 32000 files; they now read 3.29 MB and 2.21 MB, growing with the corpus (969120 B and 536264 B at 8000). Those old numbers were not wrong when taken — the ARM changed under them, when #2903's follow-up made every probe resolve a real import and when measureHeap began flattening its corpus — which is the whole finding: a measurement written into prose is not re-taken, and this file had already gone stale against itself, quoting javascript at 46208832 B four paragraphs after quoting it at 25.51 MiB. rust is the one exclusion that survived unchanged: 16 B at 8000 files and 16 B at 32000, identical in all five runs. typescript 26745296 B, vue 28884016 B and cpp 10023344 B are duplicates of a builder AND of a read pattern: typescript is byte-identical to javascript's 26745296 in four runs of five, cpp is +0.05% of c's 10018816, vue is +8.0% of javascript. HOW THE BOUNDS WERE CHOSEN. Eight of the nine take 1.5x their measured maximum, rounded up to the next 100000 B: go 4500000 (1.501x), dart 11800000 (1.506x), kotlin 72200000 (1.502x), cobol 3500000 (1.508x), swift 5200000 (1.508x), typescript 40200000 (1.503x), vue 43400000 (1.503x), cpp 15100000 (1.507x). 1.5x is NOT copied from the ceilings out of habit — it is the same number for a stated reason, and the reason is not noise: measured peak-to-peak on this box is at most 1.0024, so noise alone would justify 1.05x. What a bound has to survive is a RUNNER change, since heapUsed accounting moves across platforms and Node majors, and this file already fixes that allowance at 50% for exactly this measurement on exactly this arm. Using a second allowance for the same uncertainty on the same number would be two conventions, not more rigour. At 1.5x the bound catches what the re-entry condition is about — a language growing an index, which costs +85% for one more suffix map and +100% for a duplicate — and it does NOT catch a duplicate diverging by 8%. That limit is real and is stated rather than hidden: the tight form is a same-process ratio against the arm each duplicate is a duplicate OF, which is the only form immune to the drift the absolute bound has to tolerate. RUST TAKES AN ABSOLUTE BOUND INSTEAD, 1048576 B (1 MiB), because 1.5 x 16 B is 24 B and would fail on the first byte of anything — a multiplier on a reading that is already nothing is a gate that flakes rather than a gate that bites. 1 MiB is ~65000x the reading and still 2.2x below the smallest real index measured here (cobol's 2.32 MB at the same file count), so it separates 'builds nothing' from 'builds something' with room on both sides. NO FLOOR ON ANY OF THE NINE, and the reason differs by language rather than being uniform. For rust a floor would be a floor on noise. For the other eight the readings are stable enough to floor today, and for kotlin and dart — larger than budgeted arms — a floor would be worth having, since a lazily-built map going quiet is exactly how the four budgeted arms once read 0 B. Adding one is a PROMOTION to the budgeted tier, with a ceiling and a recorded reading beside it, not a line here: a floor whose companion ceiling does not exist asserts 'still measuring' against a number nothing else bounds. Recommended next, in order: kotlin, then dart, then go.", + "_heap_bound_note": "THE SECOND HEAP TIER. Every registered language is measured now; heap_bound_bytes gates the nine that are not BUDGETED above, and it gates them with one comparison and no floor. A ceiling says 'this index is not too big'. A bound says something narrower and it is the thing that was missing: 'the exclusion still holds' — this language has not grown an index since it was left out. measure.mjs's MEMORY section states the re-entry condition (if a language ever diverges in what it ASKS its index, it earns a budgeted arm) and until now nothing watched for the divergence; HEAP_LANGS was a hand-maintained list of eight whose two neighbours, LANG_REGISTRY and CONTEXT_LANGS, are both reconciled against a derived predicate in both directions. HEAP_BOUNDED is derived too — it is LANGS minus HEAP_BUDGETED — so the two tiers partition the languages and a new one cannot land outside both. WHAT RE-MEASURING FOUND, five runs each, maximum quoted, peak-to-peak in brackets. go 2998464 B [1.0021], dart 7834200 B [1.0006] and kotlin 42802456 B [1.0004] HAD NO STATED REASON AT ALL: the old prose opened 'SIX of the seventeen are deliberately NOT in HEAP_LANGS' against a list of eight of seventeen, and these three were the three nobody counted. All three retain a real per-pass structure (go's PackageDirIndex, dart's basename buckets, kotlin's suffixByStem cascade) and kotlin's 40.82 MiB is above ruby's 39.12 and java's 33.34, both of which carry a full budget. (It read 45.85 MiB when this was written, described here as 'the second-largest reading in this file' — it was third even then, behind csharp_csproj and php; #2881 later compacted its dirChildren buckets and took 11% off it. Same staleness this paragraph exists to document.) swift 3449216 B [1.0024] and cobol 2320456 B [1.0000] were excluded as 'below the measurement's own noise floor' on readings of 0.29 MB and 0 B at 32000 files; they now read 3.29 MB and 2.21 MB, growing with the corpus (969120 B and 536264 B at 8000). Those old numbers were not wrong when taken — the ARM changed under them, when #2903's follow-up made every probe resolve a real import and when measureHeap began flattening its corpus — which is the whole finding: a measurement written into prose is not re-taken, and this file had already gone stale against itself, quoting javascript at 46208832 B four paragraphs after quoting it at 25.51 MiB. rust is the one exclusion that survived unchanged: 16 B at 8000 files and 16 B at 32000, identical in all five runs. typescript 26745296 B, vue 28884016 B and cpp 10023344 B are duplicates of a builder AND of a read pattern: typescript is byte-identical to javascript's 26745296 in four runs of five, cpp is +0.05% of c's 10018816, vue is +8.0% of javascript. HOW THE BOUNDS WERE CHOSEN. Each takes 1.5x its measured maximum, rounded up to the next 100000 B: cobol 3500000 (1.508x), swift 5200000 (1.508x). (This sentence used to list eight, including go, dart, kotlin, typescript, vue and cpp. Those six were promoted to the budgeted tier and their bounds deleted; the numbers stayed here, unread by any gate, and #2881 dutifully updated kotlin's to 64300000 before anyone noticed heap_bound_bytes holds only cobol, swift and rust. A number nothing asserts is a number that rots — the finding this paragraph is otherwise about.) 1.5x is NOT copied from the ceilings out of habit — it is the same number for a stated reason, and the reason is not noise: measured peak-to-peak on this box is at most 1.0024, so noise alone would justify 1.05x. What a bound has to survive is a RUNNER change, since heapUsed accounting moves across platforms and Node majors, and this file already fixes that allowance at 50% for exactly this measurement on exactly this arm. Using a second allowance for the same uncertainty on the same number would be two conventions, not more rigour. At 1.5x the bound catches what the re-entry condition is about — a language growing an index, which costs +85% for one more suffix map and +100% for a duplicate — and it does NOT catch a duplicate diverging by 8%. That limit is real and is stated rather than hidden: the tight form is a same-process ratio against the arm each duplicate is a duplicate OF, which is the only form immune to the drift the absolute bound has to tolerate. RUST TAKES AN ABSOLUTE BOUND INSTEAD, 1048576 B (1 MiB), because 1.5 x 16 B is 24 B and would fail on the first byte of anything — a multiplier on a reading that is already nothing is a gate that flakes rather than a gate that bites. 1 MiB is ~65000x the reading and still 2.2x below the smallest real index measured here (cobol's 2.32 MB at the same file count), so it separates 'builds nothing' from 'builds something' with room on both sides. NO FLOOR ON ANY OF THE NINE, and the reason differs by language rather than being uniform. For rust a floor would be a floor on noise. For the other eight the readings are stable enough to floor today, and for kotlin and dart — larger than budgeted arms — a floor would be worth having, since a lazily-built map going quiet is exactly how the four budgeted arms once read 0 B. Adding one is a PROMOTION to the budgeted tier, with a ceiling and a recorded reading beside it, not a line here: a floor whose companion ceiling does not exist asserts 'still measuring' against a number nothing else bounds. Recommended next, in order: kotlin, then dart, then go.", "heap_bound_bytes": { "cobol": 3500000, "swift": 5200000, @@ -128,90 +129,90 @@ "small": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2913, - "fingerprint": "c96c4a0adce69f7c0e40fa84f6d2920c160e8a76d594803b4c725666fdcb7edf" + "fingerprint": "f2ff032eb7dc4d8f37ecfc9b56d7fc846c5a78cf9a4dfd9f78f4e04588fd0a90" }, "large": { "files": 1600, "imports": 12800, - "resolved": 4064, + "resolved": 4681, "distinct_outcomes": 11709, - "fingerprint": "ec4bb401b3465713ad6dedc4f9aa774e586b319f21d406fd79eaad29f4e98861" + "fingerprint": "19bd34ab249a95fe93843cfb3f5ab84f8215ed0eaccef30ca50298e8dcde1d87" }, "deep": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2913, - "fingerprint": "f1ce3dbe9fa4d03bae9504b644e39cc3c815d99defda70aedcf09fb743575f54" + "fingerprint": "67f8fa6657625080e912e417047320928f23f87ecd7a3f45283ad31684752195" }, "collide": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "6727beda6df2251260ee89718ea7931fa7ff1e59fa9966caf4df95f7186b6257" + "fingerprint": "8d82320278f74c0ebf7ba3e58fd49fde13e9927956f284774cbf39c3b8ca34a8" }, "collide_large": { "files": 1600, "imports": 12800, - "resolved": 4064, + "resolved": 4681, "distinct_outcomes": 11570, - "fingerprint": "6d844763547b5cad54f41cfa0c0d618b098b214cb58654375fe7d74d229bee98" + "fingerprint": "f9c777dc06e32edd30570a5f9316531481941d1f91930e86e2f2bc8dbdf7d6a7" }, - "fingerprint": "ec4bb401b3465713ad6dedc4f9aa774e586b319f21d406fd79eaad29f4e98861", + "fingerprint": "19bd34ab249a95fe93843cfb3f5ab84f8215ed0eaccef30ca50298e8dcde1d87", "heap": { "files_small": 8000, "files_large": 32000, - "path_segments": 13, + "path_segments": 14, "probe": "github.com/org/repo0/pkg/util" }, "_measured": { - "collide_ms": 5.964, - "collide_scaling_ratio": 3.763, - "depth_ratio": 1.169, - "scaling_ratio": 1.045, - "small_ms": 1.6 + "collide_ms": 7.15, + "collide_scaling_ratio": 3.465, + "depth_ratio": 0.999, + "scaling_ratio": 0.985, + "small_ms": 1.475 } }, "csharp": { "small": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2844, - "fingerprint": "cd1d665d997280a3eeb52069f2a8745f85ef91042085498a9ab546ed45faf10b" + "fingerprint": "503dbb3c2fd97d2fa380bc7d77d11706b42878a034a92dbc9a55620f88c53c76" }, "large": { "files": 1600, "imports": 12800, - "resolved": 4064, + "resolved": 4681, "distinct_outcomes": 11440, - "fingerprint": "0b46146f5213fea8c07f1f90305a14da5ce31c865c495180f3f3903ddc6b8117" + "fingerprint": "1145ce5736bfea02dcd948eac9e1d263d67470f661b7bafb30061887745d2bf5" }, "deep": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2844, - "fingerprint": "2baee530615a03ac6342d8d330f8b40e619b46e5de40f688ca8fb8a5f8b35027" + "fingerprint": "36df304d03f1d0e05e4883e69d91b95728468fdc7c7147eaa357c0ad1d022fd6" }, "collide": { "files": 400, "imports": 3200, - "resolved": 979, + "resolved": 1153, "distinct_outcomes": 2844, - "fingerprint": "51d8d08e5195a416a2e7d8e42daf69bf5c5e4882239732dee454bd9c8ecf935e" + "fingerprint": "557c92c82c8960723f0d3ce4bf13f7d661e822d98d9597fe0f5e7c6eaf988f68" }, "collide_large": { "files": 1600, "imports": 12800, - "resolved": 4064, + "resolved": 4681, "distinct_outcomes": 11440, - "fingerprint": "6d3a964bdb4ae4a0c64a1e31023fb736c42643f5aeeef704d8e00c31ae12c3af" + "fingerprint": "dbcab955f88895058613b0fb5b9ac81504c7bdc27344e3eab6a6272a14127796" }, - "fingerprint": "0b46146f5213fea8c07f1f90305a14da5ce31c865c495180f3f3903ddc6b8117", + "fingerprint": "1145ce5736bfea02dcd948eac9e1d263d67470f661b7bafb30061887745d2bf5", "heap": { "files_small": 8000, "files_large": 32000, @@ -219,11 +220,11 @@ "probe": "Ghost0.Deep.Missing" }, "_measured": { - "collide_ms": 4.074, - "collide_scaling_ratio": 2.163, - "depth_ratio": 1.438, - "scaling_ratio": 1.094, - "small_ms": 2.255 + "collide_ms": 5.167, + "collide_scaling_ratio": 2.265, + "depth_ratio": 1.279, + "scaling_ratio": 1.043, + "small_ms": 2.45 } }, "csharp_csproj": { @@ -383,39 +384,39 @@ "small": { "files": 400, "imports": 3200, - "resolved": 1100, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "59c4287225e765d75518a7ae1531487e0270c9a1ce42a3e1821c301f7cfeb3cc" + "fingerprint": "1b3cd628bb069a3388af655c301984635cdc00a5d54b0e0ffd2b12849eb7fe40" }, "large": { "files": 1600, "imports": 12800, - "resolved": 4456, + "resolved": 4681, "distinct_outcomes": 11512, - "fingerprint": "003bb2fe82972c6bb6b4b4e569fb49dfcda2d7c61922d68c65b04398cbbde50b" + "fingerprint": "8763c5ea18a25663deb30b2e065d2fde1b0df7bad5b19e46a9ea0d30d8780995" }, "deep": { "files": 400, "imports": 3200, - "resolved": 1100, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "e541c9daee39c271ccc08b045f5330a98efba8b8dd4ded233e39e174f50d3785" + "fingerprint": "b71c0f96506a5775f2a92e035c203a085bb211f93bc45be4183ebefc87ba412f" }, "collide": { "files": 400, "imports": 3200, - "resolved": 1100, - "distinct_outcomes": 2775, - "fingerprint": "1e855115befc9a7e972bc3990816c366c9ac1ccb1aa3e50d237ccb76e9a8f99a" + "resolved": 1153, + "distinct_outcomes": 2744, + "fingerprint": "d3453a77f76e4cc59d3479af80d05b358abe9c1277a6aa92611d0f20cac80eea" }, "collide_large": { "files": 1600, "imports": 12800, - "resolved": 4456, - "distinct_outcomes": 11087, - "fingerprint": "d867aaa39e47ba55df1853c4eaca741977e946a16ad3d99f35c698abe7241ac7" + "resolved": 4681, + "distinct_outcomes": 10961, + "fingerprint": "335eaaa54b2663caee5587b66d96d0669106e5a10e4d70ae2ee67443d939890e" }, - "fingerprint": "003bb2fe82972c6bb6b4b4e569fb49dfcda2d7c61922d68c65b04398cbbde50b", + "fingerprint": "8763c5ea18a25663deb30b2e065d2fde1b0df7bad5b19e46a9ea0d30d8780995", "heap": { "files_small": 8000, "files_large": 32000, @@ -423,11 +424,11 @@ "probe": "com.ghost0.deep.Missing" }, "_measured": { - "collide_ms": 2.611, - "collide_scaling_ratio": 1.179, - "depth_ratio": 2.219, - "scaling_ratio": 1.169, - "small_ms": 2.799 + "collide_ms": 2.448, + "collide_scaling_ratio": 1.081, + "depth_ratio": 1.813, + "scaling_ratio": 1.097, + "small_ms": 2.62 } }, "php": { @@ -490,39 +491,39 @@ "small": { "files": 400, "imports": 3200, - "resolved": 1100, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "a5e3b2e63b6c06dc1ae3655193c96801f038f9a69d448e399e1865d9f2601844" + "fingerprint": "c66d780f4b5549e0a9596ed30eb9035dca8e8168e90371124d1cbad968205569" }, "large": { "files": 1600, "imports": 12800, - "resolved": 4456, + "resolved": 4681, "distinct_outcomes": 11512, - "fingerprint": "7ffdd453170ef36aa66c3de73f45d6ffa0588850b16111a4078f10f41782ee18" + "fingerprint": "354cc4de030ce581982eae15d7f6c95ba8ed14b7a14a2e0e9c3b06f90efb1eee" }, "deep": { "files": 400, "imports": 3200, - "resolved": 1100, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "9c1589a04dfe8c70fa5aff57ebb5742eb8999b8979a8baae701da3ef993114ec" + "fingerprint": "de26edd2268593f35120801c8f96799786ff01976dc84f9c342e7426be0afa9a" }, "collide": { "files": 400, "imports": 3200, - "resolved": 1100, + "resolved": 1153, "distinct_outcomes": 2868, - "fingerprint": "8a08bb2d5919e9739388c0c514ae0162f6a18c10577d1b7c5bad54e2320efea5" + "fingerprint": "260aa5fa381b853e2cb92548a5bbb684f4afe6ba513d419e2fb2bd178f00c293" }, "collide_large": { "files": 1600, "imports": 12800, - "resolved": 4456, + "resolved": 4681, "distinct_outcomes": 11512, - "fingerprint": "3286317a7e5c2ae70b1c001690980f61633566a30672e949caebcbb065e8c80f" + "fingerprint": "a8bcf5e432dcedf82c7b23c533311b051b00a68cbbd8bb4e816fd1c8ae055f33" }, - "fingerprint": "7ffdd453170ef36aa66c3de73f45d6ffa0588850b16111a4078f10f41782ee18", + "fingerprint": "354cc4de030ce581982eae15d7f6c95ba8ed14b7a14a2e0e9c3b06f90efb1eee", "heap": { "files_small": 8000, "files_large": 32000, @@ -530,11 +531,11 @@ "probe": "com.google.common.vendor0.Missing" }, "_measured": { - "collide_ms": 5.434, - "collide_scaling_ratio": 2.365, - "depth_ratio": 1.402, - "scaling_ratio": 1.16, - "small_ms": 3.18 + "collide_ms": 5.34, + "collide_scaling_ratio": 2.508, + "depth_ratio": 1.354, + "scaling_ratio": 1.147, + "small_ms": 3.317 } }, "cobol": { @@ -1002,5 +1003,5 @@ } } }, - "_blind_spot": "MEASURED, so nobody has to rediscover it: a full workspace scan reintroduced on 1-in-32 imports passes EVERY arm here \u2014 dart scored 1.458 scaling and 1.736 ms against the 1.8 budget and 4 ms ceiling of an earlier revision. At 1-in-8 the scaling arm catches it (2.414). The gate that NARROWS this is not a timing gate at all: test/unit/scope-resolution/import-target-index-parity.test.ts counts iterations of the file-set Set and reads 14 instead of 1 for that same 1-in-32 mutation, deterministically and for all five languages. It does NOT close it. The counter watches the Set, and the resolvers no longer read the Set \u2014 they read materialized copies of the same file list: WorkspaceFileIndex.normalized and .all (C#, Ruby), Dart's byBasename buckets, and PackageDirIndex.filesByDir (Go, C#). A 1-in-32 scan over any of those three touches the Set zero extra times, so it passes the parity test AND passes --check. Closing it would take an iteration counter on the materialized arrays themselves. Read the two gates together; tightening these ceilings toward the noise floor to chase that case would only buy flaky CI. CONFIRMED THE HARD WAY by PR #2911: JavaScript resolution was scanning ImportPassCache.normalizedFileList on every import \u2014 a materialized array, not the Set \u2014 at 25972 us per import at 8000 files, and no instrument on the #2901-#2909 branch could see it. It took a differential parity test over 211200 old-vs-new pairs to find. The arms added here would have caught THAT one on absolute ms (85 ms budget against a 20 ms arm; the unindexed resolver costs ~83000 ms on the same corpus), which is the argument for gating every registered language rather than only the ones a PR happens to touch. THE SECOND BLIND SPOT IS CLOSED, and this records what closing it changed. This harness used to call the inner resolvers with the NO-CONTEXT shape: run.ts calls provider.resolveImportTarget with five arguments, the fifth being { parsedFiles, parsedImport }, and resolveOne supplied three. resolveOne now makes the production call, newPass mints the ParsedFile[] FIRST and derives the path set from it exactly as run.ts does, and both legs behind the argument run on every import of their arms \u2014 PHP's named/alias function-or-const leg over filesByDirectory(context.parsedFiles), whose memo defeated measures 197.0 us -> 9976.2 us per import (50.6x), and Python's from-import submodule-precedence branch, the only spelling that reads context.parsedFiles at all. Fifteen of the seventeen arms cannot observe a context (their hooks declare three or four parameters) and are handed none, so their numbers did not move; which two CAN is now reconciled against SCOPE_RESOLVERS' hook arity rather than asserted in prose. NOTHING ELSE IN THIS FILE COULD HAVE GATED IT, which is why the context arm exists: on this corpus the leg AGREES with the cascade for every import, so all ten of PHP's and Python's fingerprints, their resolved counts and their distinct_outcomes are unchanged; a dropped context makes the timing arms FASTER and no arm here has a lower bound on ms; and the heap floor (0.5 x 49573840 = 24.8 MB) still passes the 37576816 B a no-context PHP pass reads. The arm is one import per language resolved through resolveOne twice, with and without the pass's parsedFiles, whose two answers must DIFFER and must both match what is recorded. WHAT REMAINS UNMEASURED, narrowed rather than deleted: Python's parsedFileByPath memo is exercised by the five timing arms and cannot be reached by the heap arm at all, because retainedPassBytes requires a probe that MISSES while every path that builds that memo returns a non-null packageTarget \u2014 so no ceiling bounds that Map (one pointer per parsed file, O(files), no depth term) and the contract test's count gate is what holds it to one build per pass. PHP's leg is measured with NO composer.json, so namespaceDirectories only ever returns the directory of an already-resolved file and the PSR-4 mapping branch stays unreached, exactly as csharp cannot reach the csproj leg; closing that is a second PHP arm on the csharp_csproj precedent, not a parameter. And the const tail of PHP's leg is a different ANSWER at the same cost \u2014 it runs the identical candidate gather and localDefs filter and diverges in the last two lines \u2014 so it is gated by count in test/unit/scope-resolution/import-target-index-reuse.contract.test.ts, which stays the gate to read alongside this file." + "_blind_spot": "MEASURED, so nobody has to rediscover it: a full workspace scan reintroduced on 1-in-32 imports passes EVERY arm here — dart scored 1.458 scaling and 1.736 ms against the 1.8 budget and 4 ms ceiling of an earlier revision. At 1-in-8 the scaling arm catches it (2.414). The gate that NARROWS this is not a timing gate at all: test/unit/scope-resolution/import-target-index-parity.test.ts counts iterations of the file-set Set and reads 14 instead of 1 for that same 1-in-32 mutation, deterministically and for all five languages. It does NOT close it. The counter watches the Set, and the resolvers no longer read the Set — they read materialized copies of the same file list: WorkspaceFileIndex.normalized and .all (C#, Ruby), Dart's byBasename buckets, and PackageDirIndex.filesByDir (Go, C#). A 1-in-32 scan over any of those three touches the Set zero extra times, so it passes the parity test AND passes --check. Closing it would take an iteration counter on the materialized arrays themselves. Read the two gates together; tightening these ceilings toward the noise floor to chase that case would only buy flaky CI. CONFIRMED THE HARD WAY by PR #2911: JavaScript resolution was scanning ImportPassCache.normalizedFileList on every import — a materialized array, not the Set — at 25972 us per import at 8000 files, and no instrument on the #2901-#2909 branch could see it. It took a differential parity test over 211200 old-vs-new pairs to find. The arms added here would have caught THAT one on absolute ms (85 ms budget against a 20 ms arm; the unindexed resolver costs ~83000 ms on the same corpus), which is the argument for gating every registered language rather than only the ones a PR happens to touch. THE SECOND BLIND SPOT IS CLOSED, and this records what closing it changed. This harness used to call the inner resolvers with the NO-CONTEXT shape: run.ts calls provider.resolveImportTarget with five arguments, the fifth being { parsedFiles, parsedImport }, and resolveOne supplied three. resolveOne now makes the production call, newPass mints the ParsedFile[] FIRST and derives the path set from it exactly as run.ts does, and both legs behind the argument run on every import of their arms — PHP's named/alias function-or-const leg over filesByDirectory(context.parsedFiles), whose memo defeated measures 197.0 us -> 9976.2 us per import (50.6x), and Python's from-import submodule-precedence branch, the only spelling that reads context.parsedFiles at all. Fifteen of the seventeen arms cannot observe a context (their hooks declare three or four parameters) and are handed none, so their numbers did not move; which two CAN is now reconciled against SCOPE_RESOLVERS' hook arity rather than asserted in prose. NOTHING ELSE IN THIS FILE COULD HAVE GATED IT, which is why the context arm exists: on this corpus the leg AGREES with the cascade for every import, so all ten of PHP's and Python's fingerprints, their resolved counts and their distinct_outcomes are unchanged; a dropped context makes the timing arms FASTER and no arm here has a lower bound on ms; and the heap floor (0.5 x 49573840 = 24.8 MB) still passes the 37576816 B a no-context PHP pass reads. The arm is one import per language resolved through resolveOne twice, with and without the pass's parsedFiles, whose two answers must DIFFER and must both match what is recorded. WHAT REMAINS UNMEASURED, narrowed rather than deleted: Python's parsedFileByPath memo is exercised by the five timing arms and cannot be reached by the heap arm at all, because retainedPassBytes requires a probe that MISSES while every path that builds that memo returns a non-null packageTarget — so no ceiling bounds that Map (one pointer per parsed file, O(files), no depth term) and the contract test's count gate is what holds it to one build per pass. PHP's leg is measured with NO composer.json, so namespaceDirectories only ever returns the directory of an already-resolved file and the PSR-4 mapping branch stays unreached, exactly as csharp cannot reach the csproj leg; closing that is a second PHP arm on the csharp_csproj precedent, not a parameter. And the const tail of PHP's leg is a different ANSWER at the same cost — it runs the identical candidate gather and localDefs filter and diverges in the last two lines — so it is gated by count in test/unit/scope-resolution/import-target-index-reuse.contract.test.ts, which stays the gate to read alongside this file." } diff --git a/gitnexus/bench/import-target/measure.mjs b/gitnexus/bench/import-target/measure.mjs index 6e914f840..c4318d558 100644 --- a/gitnexus/bench/import-target/measure.mjs +++ b/gitnexus/bench/import-target/measure.mjs @@ -270,9 +270,12 @@ * of eight, so go, dart and kotlin were excluded silently. All three * retain a real per-pass structure: go's `PackageDirIndex` reads * 2 998 464 B, dart's basename buckets 7 834 200 B, and kotlin's - * `suffixByStem` cascade 48 073 096 B (45.85 MiB) — the second-largest - * reading in this file, above ruby's 39.12 and java's 33.34, both of which - * carry a full budget. + * `suffixByStem` cascade 42 802 456 B (40.82 MiB) — above ruby's 39.12 and + * java's 33.34, both of which carry a full budget. (Read 48 073 096 B when + * this paragraph was written and described as "the second-largest reading + * in this file", which it was not even then: csharp_csproj and php both + * read higher. #2881 then compacted kotlin's `dirChildren` buckets and + * took 11% off it.) * 2. TWO OF THE STATED REASONS NO LONGER HOLD. swift was excluded as "below * its own noise floor" on 0.98 MB at 8000 files against 0.29 MB at 32 000; * it now reads 969 120 B and 3 449 216 B, growing the right way. COBOL was @@ -560,9 +563,20 @@ const HEAP_BUDGETED = [ // per-pass structure and each grows LINEARLY with the file count (ratio // 0.996-1.004 against a 1.25 budget over 8000 -> 32000 files), so each can // carry the full ceiling + floor + ratio set rather than a bound alone. - // kotlin's 45.85 MiB is the second-largest reading in this file — larger than - // ruby's and java's, both of which were budgeted from the start — and it had - // no stated exclusion reason at all. + // kotlin's 40.82 MiB is larger than ruby's and java's, both of which were + // budgeted from the start, and it had no stated exclusion reason at all. + // + // Its ceiling is also the one TIGHT ceiling in this file — 1.0747x its + // reading where every other is 1.5x — because it is the only one gating a + // size REDUCTION being preserved rather than a footprint not growing. + // #2881 compacts `dirChildren`'s buckets, and deleting that `slice()` is + // invisible to every other instrument in the repository: output-identical, + // so no fingerprint moves; capacity has no reflective surface, so no unit + // assertion moves; and both heap scales grow together, so `heap_ratio_budget` + // divides it out. It shows up here and nowhere else, at +12.57%. See + // `_heap_compaction_gate` in baselines.json for the measurement, the + // arithmetic behind the 5.4 MB, and how to tell a lost compaction from a + // runner's heapUsed accounting moving under the whole file. 'kotlin', 'dart', 'go', @@ -726,12 +740,33 @@ function unwiredLanguage(where, lang) { * UNIQUE-LEAF layout: one directory name per index, so no two directories share * a last segment and no two files share a basename. Every index bucket holds * exactly one entry. A nested same-name directory in one repo slice is the - * shape whose handling the first-`indexOf` tie-break decides (see - * package-dir-index.ts), and the shape Kotlin's `dirChildren` resolves the same - * way. + * shape the first-`indexOf` tie-break used to reject (see package-dir-index.ts); + * #2881 removed that tie-break from every resolver that had it, so the go, + * csharp, java and kotlin arms all resolve their `d % 7` slice now. + * + * A repeat the query cannot ask about leaves the arm blind, which is why go's + * slice repeats the WHOLE package path: a Go import addresses `src/pkg{d}`, and + * `…/internal/pkg{d}` does not end with that, so the old rule was never even + * reached and every go arm sat still through the fix. Java, C# and Kotlin query + * the whole dotted path FIRST and only fall back to the tail through + * progressive stripping, so their slices — which repeat the last segment only — + * move through that fallback rather than the primary query. The consequence is + * measured and worth knowing: a partial revert that reinstates first-occurrence + * only for multi-segment package paths is caught on the go arm alone. */ function uniqueDir(lang, d, i) { - if (lang === 'go') return d % 7 === 0 ? `src/pkg${d}/internal/pkg${d}` : `src/pkg${d}`; + // Go's nested slice repeats the WHOLE queried path (`src/pkg{d}`), not just + // its last segment. `src/pkg{d}/internal/pkg{d}` repeated only `pkg{d}`, so + // the query `src/pkg{d}` failed on "the directory ends with the package path" + // and never reached the first-occurrence rule at all — Go's arms did not move + // when #2881 removed that rule, which would have shipped a widened bucket + // with no bench coverage while C# and Java were re-baselined for it. + if (lang === 'go') return d % 7 === 0 ? `src/pkg${d}/internal/src/pkg${d}` : `src/pkg${d}`; + // Leaf-only repeat, deliberately: this layout is shared with the + // `csharp_csproj` arm, whose configs mint `dirPrefix` against `src/Ns{d}`, so + // deepening it to the full `App/Ns{d}` query path resolves that arm to ZERO + // and breaks its same-workload invariant. C# therefore exercises the removed + // rule through progressive stripping rather than through its primary query. if (lang === 'csharp') return d % 7 === 0 ? `src/Ns${d}/Sub/Ns${d}` : `src/Ns${d}`; if (lang === 'dart') return d % 3 === 0 ? `lib/feature${d}` : `pkg/feature${d}`; if (lang === 'kotlin') { @@ -782,14 +817,52 @@ function uniqueDir(lang, d, i) { */ function collideDir(lang, d, i) { if (lang === 'go') { - if (d % 7 === 0) return `svc${d}/internal/sub/internal`; + // `…/sub/internal` repeats only the last segment, which the ends-with test + // answers on its own; `…/internal/sub/svc{d}/internal` is the shape the + // removed first-occurrence rule used to reject (see `uniqueDir`). + if (d % 7 === 0) return `svc${d}/internal/sub/svc${d}/internal`; return d % 5 === 1 ? `svc${d}/internal/shared` : `svc${d}/internal`; } + // Leaf-only repeat here too, and unlike the kotlin arm below that is not a + // blind spot — measured, base against head over this exact corpus. C#'s match + // test is an unanchored ends-with and its cascade strips leading segments, so + // `App.Src{d}.Models` reaches `Models` after two strips and finds + // `Src{d}/Models/Inner/Models`, whose FIRST `/Models/` is not its last: the + // removed first-occurrence rule rejected it and the current one takes it. The + // `csharp` collide fingerprint therefore moves across #2881 (03c9afe33276 + // head, 89d0a054b617 base) with the resolved count unchanged at 1153 — the + // arm sees the change, it just sees it as different ANSWERS rather than more + // of them. Deepening the slice to `Src{d}/Models/Inner/Src{d}/Models` only + // moves which strip level finds it; both layouts move base -> head, so it + // buys nothing here. + // + // And it costs, because the `csharp_csproj` constraint binds this arm too — + // differently from the way it binds `uniqueDir`. There, deepening resolves + // that arm to ZERO. Here it resolves MORE: `Lib` has `projectDir: ''`, so its + // `dirPrefix` is `Src{d}/Models`, which is not a segment suffix of + // `…/Inner/Models` and is one of `…/Inner/Src{d}/Models`. Measured, the + // csproj arm's collide `resolved` goes 979 -> 1153 against its `small` 979, + // which is the same-workload invariant `--check` asserts. (Worth recording + // while it is measured: with the shipped layout BOTH csproj arms are blind to + // #2881 — unique and collide fingerprints identical base and head — because + // `getFilesInDir` is keyed on segment-aligned directory SUFFIXES and neither + // nested slice is one. Closing that is the deepening plus a mirrored miss for + // the csproj arm's `d % 7` slice, i.e. a corpus redesign and four + // re-baselines, not this edit.) if (lang === 'csharp') return d % 7 === 0 ? `Src${d}/Models/Inner/Models` : `Src${d}/Models`; if (lang === 'dart') return `pkg${d}/lib/src`; if (lang === 'kotlin') { return d % 7 === 0 - ? `mod${d}/src/main/kotlin/com/example/models/inner/models` + ? // Repeats the WHOLE queried path (`com.example.models`), not just the + // `models` leaf. With a leaf-only repeat this arm was structurally + // blind to the #2881 rule: a full revert of the Kotlin guards left both + // collide fingerprints unmoved, because `com/example/models` is not a + // suffix of `…/models/inner/models` and the query never reached the + // rule. Deepening it is the only corpus edit in this file that buys + // coverage — the same deepening applied to the java and kotlin UNIQUE + // arms was measured and reverted, because progressive stripping lands + // those queries on the same file either way. + `mod${d}/src/main/kotlin/com/example/models/inner/com/example/models` : `mod${d}/src/main/kotlin/com/example/models`; } if (lang === 'php') return `svc${d}/src/Models`; @@ -1203,11 +1276,13 @@ function collideTarget(lang, { local, r, d, j, dirs }) { } if (lang === 'csharp') { return local - ? // `Vendor` has no directory anywhere, mirroring the unique arm's - // nested-same-name slice, which also resolves to nothing. - d % 7 === 0 - ? `App.Src${d}.Vendor` - : `App.Src${d}.Models` + ? // This used to send the `d % 7` slice to `App.Src{d}.Vendor`, a + // namespace with no directory anywhere, to mirror the unique arm's + // nested-same-name slice, which also resolved to nothing. #2881 made + // that slice resolve, so the mirror has to as well — otherwise this arm + // stops resolving as many imports as `small`, which is the invariant + // that makes the two timings comparable and is asserted below. + `App.Src${d}.Models` : (r >>> 3) % 2 === 0 ? ['System', 'System.Threading.Tasks', 'System.Collections.Generic'][(r >>> 4) % 3] : `Ghost${(r >>> 4) % 97}.Deep.Missing`; @@ -1246,13 +1321,18 @@ function collideTarget(lang, { local, r, d, j, dirs }) { `package:ext${(r >>> 4) % 97}/other/mod${(r >>> 4) % 8}.dart`; } if (lang === 'kotlin') { - // Same wildcard share as the unique arm; `vendor${d}` is the collide - // layout's spelling of a package that exists nowhere. + // Same wildcard share as the unique arm. This used to send the `d % 7` + // nested slice to `com.example.vendor${d}`, a package that exists nowhere, + // to mirror the unique arm's nested slice — which missed, because + // `dirChildren` required the parent to be the FIRST occurrence of its own + // name and `…/com/example/pkg${d}/inner/pkg${d}` therefore did not belong to + // `pkg${d}`. #2881 removed that rule, so the unique arm's nested wildcards + // resolve and the mirror has to as well, or this arm stops resolving as + // many imports as `small` — which is the invariant that makes the two + // timings comparable, and it is asserted below. return local ? (r >>> 3) % 3 === 0 - ? d % 7 === 0 - ? `com.example.vendor${d}.*` - : `com.example.models.*` + ? `com.example.models.*` : `com.example.models.File${j}` : (r >>> 3) % 2 === 0 ? ['java.util.List', 'kotlin.collections.Map', 'kotlinx.coroutines.flow.Flow'][ @@ -1282,13 +1362,13 @@ function collideTarget(lang, { local, r, d, j, dirs }) { // every directory now ends in, so `firstFileDirectlyInPkgDir` walks the // whole `model` bucket twice — at the direct match and again after the // first strip — before the third strip finds `model` on its own. That walk - // is the non-constant term this arm exists to measure. `vendor` buckets to - // nothing, mirroring the unique arm's nested slice, which also misses. + // is the non-constant term this arm exists to measure. The `d % 7` slice + // used to import `com.svc{d}.vendor`, which buckets to nothing, mirroring + // the unique arm's nested slice — which missed until #2881 and resolves + // now, so the mirror follows it or the same-workload invariant below breaks. return local ? (r >>> 3) % 3 === 0 - ? d % 7 === 0 - ? `com.svc${d}.vendor.*` - : `com.svc${d}.model.*` + ? `com.svc${d}.model.*` : `com.example.model.File${j}` : (r >>> 3) % 2 === 0 ? ['java.util.List', 'java.io.IOException', 'java.util.concurrent.ConcurrentHashMap'][ @@ -1820,8 +1900,9 @@ const HEAP_PROBE_TARGET = { javascript: 'vendor0/lib/missing', python: 'vendor0.deep.missing', c: 'vendor0/missing.h', - // The nine below are the BOUNDED tier — see `HEAP_BOUNDED`. Same rule as the - // eight above: a spelling `uniqueTarget` already mints for that language, and + // The entries below cover the BOUNDED tier — see `HEAP_BOUNDED`, which + // derives to cobol, swift and rust; the rest were promoted. Same rule as the + // budgeted ones above: a spelling `uniqueTarget` already mints for that language, and // one that MISSES, so the reading is the index and the cascade runs to the // end. Chosen from the miss family that reaches furthest into each cascade: // - `go` takes the GOPATH fallback, one `filesDirectlyInPkgDir` per path @@ -2578,9 +2659,12 @@ for (const lang of HEAP_BUDGETED) { * TIER TWO, the bounded arms: ONE comparison, and what it is a comparison FOR. * * `heap_bound_bytes` is the "exclusion still holds" bound. It does not claim - * these nine indexes are small enough, which is what a ceiling claims about a + * these indexes are small enough, which is what a ceiling claims about a * budgeted one; it claims each is still the SIZE the decision to leave it out - * was taken on. The re-entry condition the MEMORY section states — "if any of + * was taken on. `HEAP_BOUNDED` derives to THREE today — cobol, swift, rust. + * The prose below still counts nine because six were promoted to tier one + * after it was written; read the counts as history, and `HEAP_BOUNDED` itself + * as the answer. The re-entry condition the MEMORY section states — "if any of * the four ever diverges in what it ASKS, it earns an arm the same way" — is a * claim about growth, and this is the only thing in the file that can see it. * @@ -2588,13 +2672,12 @@ for (const lang of HEAP_BUDGETED) { * because it builds nothing, so any floor at all would be a floor on noise and * `1.5 x 0 B` is 0 — its bound is ABSOLUTE (1 MiB) for the same reason: a * multiplier on 16 B fails on the first byte of anything. The other eight are - * stable enough today to floor (0.24% peak-to-peak at worst over five runs) and - * two of them — kotlin at 45.85 MiB and dart at 7.47 — are larger than budgeted - * arms, so a floor there would be worth having. That is a promotion to tier one, - * with a ceiling and a recorded reading, and it is not this change: a floor - * without them would assert "still measuring" against a number nothing else - * bounds. What this tier is NOT is a weaker version of tier one — it is the - * different question, asked of every language instead of eight. + * stable enough today to floor (0.24% peak-to-peak at worst over five runs). + * The two this paragraph named as floor candidates, kotlin and dart, TOOK that + * promotion: both now carry a ceiling and a recorded reading in tier one, which + * is what the paragraph said the promotion had to be. What this tier is NOT is a + * weaker version of tier one — it is a different question, asked of the + * languages tier one does not ask it of. */ const heapBoundScope = `That leaves the arm bounded by nothing, which is the state all nine of these were in before ` + diff --git a/gitnexus/bench/kotlin-import-target/baselines.json b/gitnexus/bench/kotlin-import-target/baselines.json index 6810c0224..e89eaaec7 100644 --- a/gitnexus/bench/kotlin-import-target/baselines.json +++ b/gitnexus/bench/kotlin-import-target/baselines.json @@ -1,14 +1,15 @@ { "_comment": "Baselines for bench/kotlin-import-target/measure.mjs --check. `fingerprint` is a sha256 over every `fileSet | fromFile | targetRaw -> result` record the correctness corpus resolves, in BOTH file-set iteration orders; it is a CORRECTNESS gate, so drift means Kotlin import resolution started returning a different file set and IMPORTS/CALLS edges moved in every Kotlin repository. Explain it, never re-baseline to make CI green. `cases` and `non_null` are asserted beside it because a shrunken or hollowed corpus produces a perfectly valid fingerprint over a smaller surface — all three are one re-baseline, never separate ones. `scaling_budget`, `depth_budget` and `small_ms_ceiling` are timing gates and carry deliberate headroom for shared CI runners.", - "_provenance": "This fingerprint is the value the PRE-INDEX implementation produces. It was not read off the new code: the same corpus was run against `git show :gitnexus/src/core/ingestion/languages/kotlin/import-target.ts` — the four-tier per-import scan — and against the index that replaced it. Both print ebf1790bf1d42dad483a51f2cbdeb2351e493b9e8236e4eedeef592dd81e2c5c over 20106 cases, 13256 of them non-null. That is what makes the index change a performance change rather than a behaviour change, and it is reproducible: swap the module specifier at the top of measure.mjs for the old file and re-run. The corpus deliberately includes the shapes where the two could have diverged — repeated directory names whose FIRST occurrence is not the parent (`data/src/main/kotlin/com/example/data/Repo.kt` is NOT a child of `data`, because the old scan tested startsWith and then used indexOf), doubly nested same-name directories, an exact match appearing after a suffix match in iteration order, `.kt`/`.kts` stem collisions, backslash paths, repo-root files, wildcard `.*` targets landing on the single-file tier rather than fanning out, and non-Kotlin noise.", - "_gate_controls": "The gate is only worth its baseline if a plausible regression moves it, so each arm was checked against the mutation it exists to catch, with the resolver otherwise untouched. Caught, all with the corpus below: capping suffixByStem key depth at 7 (fingerprint a0e6eb98f9…); skipping the dirChildren suffix loop above depth 8 (d53182ebbc…, non_null 13256 -> 12746); capping a dirChildren bucket at 17 entries (ed3ea85c59…). Also caught, with the RESOLVER untouched and only the corpus edited: dropping the competing file from the exact-beats-earlier-suffix case and emptying the repeated-directory negative case (44df5093ee…). All four passed silently before this corpus carried deep paths, packages above 16 files, queries against suffix keys deeper than 7, and the file set inside the hashed record. Re-check them after any corpus edit — a corpus that stops spanning an axis takes the gate with it.", - "fingerprint": "ebf1790bf1d42dad483a51f2cbdeb2351e493b9e8236e4eedeef592dd81e2c5c", + "_provenance": "RE-BASELINED ONCE, DELIBERATELY, IN #2881. The previous value ebf1790bf1d42dad483a51f2cbdeb2351e493b9e8236e4eedeef592dd81e2c5c (13256 non-null) was the PRE-INDEX implementation's, and the index that replaced it in #2872 reproduced it byte for byte — that is what made #2872 a performance change. #2881 changes resolution on purpose: `getKotlinFileIndex` no longer requires the parent directory to be the FIRST occurrence of that name in the path, so a file whose package directory name repeats higher in its own path is now a child of that package (`data/src/main/kotlin/com/example/data/Repo.kt` IS a child of `data`, and `import data.helper` resolves instead of returning null). The drift was not read off the new code and accepted; the corpus was dumped from both implementations and diffed record by record. That census was RE-RUN with a shape classifier after review found its taxonomy — 54 NULL -> resolved, 149 reselections, 32 wider fan-outs — was entirely SHAPE-PRESERVING and so had no bucket for a class this change introduces. Both ends of the re-run are validated against numbers this file already publishes, so the census is provably over the surface they describe: driven over this bench's own corpus, the BASE resolver reproduces ebf1790bf1… at 13256 non_null and the HEAD resolver reproduces d91110bee3… at 13310, across 20106 records of which 19968 are distinct. 235 distinct records moved, classified by SHAPE rather than by null-ness: null -> string 38 and null -> array 16, which together are the first census's '54 NULL -> resolved' and exactly the +54 in non_null; string -> string (a different member of a now-wider bucket) 149; array -> array (the fan-out grew) 32; string -> array 0; and ZERO of every other transition — nothing went string -> null, array -> null or array -> string, and no array shrank or reordered. So the old three buckets reappear inside the shape taxonomy exactly, and its two structural claims hold when checked directly instead of inferred: all 32 growths are order-preserving SUPERSETS of the base answer, no record lost a member, and in all 149 reselections the new answer's parent directory is named by a segment of the import and carries the same directory NAME the base answer's parent did. WHAT THE OLD TAXONOMY HAD NO BUCKET FOR is `string -> array`, and it is the one class here that is not shape-preserving: it is a RESOLVED -> UNRESOLVED transition. Tier 3 (`findKotlinPackageFiles`) runs before tier 4 (`findByProgressivePrefixStrip`), so a bucket the removed guards left empty returned null and let tier 4 answer with a single BOUND file; a now-populated bucket stops tier 4 running at all and hands back a fan-out array that need not contain the imported name at all. Two files reproduce it, in both iteration orders: ['data/src/main/kotlin/com/example/data/Repo.kt', 'common/helper.kt'] with `import data.helper` answers 'common/helper.kt' at base and ['data/src/main/kotlin/com/example/data/Repo.kt'] at head. ITS COUNT OVER THIS CORPUS IS 0, AND THAT IS A FACT ABOUT THE CORPUS RATHER THAN ABOUT THE CLASS. This file's own fuzz generator, run at ten times the repositories (4000, ~198600 distinct records), hits the class 12, 4, 10 and 10 times over four seeds — ~5e-5 per record, an expectation of about ONE over the 19968 records here — so 0 is this corpus being an order of magnitude too small to reach it, not the shape being unreachable. The consequence is worth stating plainly: the fingerprint below is blind to a resolved -> unresolved class this change introduces, by corpus SIZE and not by construction, and no arm in this bench gates it today. Adding a hand-written case for it is a deliberate fingerprint move and a fourth re-baseline of this file; it is worth doing and it is not this change. The corpus itself is untouched, which is why `cases` is unchanged at 20106 — the fingerprint is over the same surface as the value it replaces.", + "_gate_controls": "The gate is only worth its baseline if a plausible regression moves it, so each arm was checked against the mutation it exists to catch, with the resolver otherwise untouched. All values below are against the CURRENT baseline (#2881, guards removed + per-directory key memo + bucket compaction). Caught: skipping the dirChildren component walk above depth 8 (fingerprint 41bb550b76d4…, non_null 13310 -> 12800); capping a dirChildren bucket at 17 entries (a7681945b752…, non_null UNCHANGED — the fingerprint is the only arm that sees it, and note the compaction pass now rewrites those same buckets, so this control was re-run after it); capping suffixByStem key depth at 7 (d24b8a2bd822…, non_null unchanged); and a HALF fix that drops only the `startsWith` guard while keeping the `indexOf` first-occurrence check (836977b83bf0…, non_null 13310 -> 13282), which leaves every mid-path repeat such as `top/data/mid/data/Repo.kt` broken and is the mutation #2881 itself makes plausible. Added with the memo: keying `dirKeys` on the directory's LAST SEGMENT instead of its full path (36a4e9dad313…, non_null 13310 -> 13305) — the memo's whole safety argument is that its key determines the key SET a directory contributes, so a coarser key silently hands one directory another's bucket list, and that is the one way this optimization can move an answer. Also caught, with the RESOLVER untouched and only the corpus edited: dropping the competing file from the exact-beats-earlier-suffix case and emptying the repeated-directory case (44df5093ee…). All of these passed silently before this corpus carried deep paths, packages above 16 files, queries against suffix keys deeper than 7, and the file set inside the hashed record. Re-check them after any corpus edit — a corpus that stops spanning an axis takes the gate with it. NOTE what no fingerprint control here can catch: the memo and the compaction are both invisible to this bench by design (identical output), so no arm in this file gates either one, and the honest version of where they ARE gated is narrower than a claim about comparing the three maps would suggest. The memo's gate is test/unit/scope-resolution/kotlin/kotlin-index-internals.test.ts, which drives the resolver's OBSERVABLE SURFACE rather than the built index — the index is module-private — and reconstructs what it needs from the tiers. It pins: bucket CONTENTS and ORDER, read back from the fan-out tier, which hands out the bucket array itself; that the first-child tier reads position 0 of that SAME array; bucket IDENTITY across two calls on one Set, which is what proves the memo's hit path ran at all, since only a second file in the same directory reaches it; the frozen state of the array actually handed out, on the multi-child path, on the `length === 1` skip path, and once per key of a multi-key directory; that the memo keys on the NORMALIZED directory while storing the raw path; and the one mutation that can move an answer — keying `dirKeys` on the directory's last segment instead of the whole `dir` — which fails three of its arms. KEY INSERTION ORDER is unasserted there BY DESIGN and not by omission: `dirChildren` is only ever read by `.get(key)`, so key order has no consumer, and that file says so. The COMPACTION is unasserted there too and cannot be asserted there at all — a JS array's backing-store capacity has no reflective surface, so deleting `bucket.slice()` and freezing the grown bucket in place leaves every arm in that file green, `Object.isFrozen` included. Its only instrument is the retained-heap arm in bench/import-target, whose kotlin ceiling was tightened to 1.0747x its recorded reading precisely so that the +12.57% the slice reclaims fails `--check`; see `_heap_compaction_gate` in bench/import-target/baselines.json for the measurement and for how to tell that failure apart from a runner's heapUsed accounting moving under the whole file.", + "fingerprint": "d91110bee389891c313811c5b4bae61d909561156e1458d38d487be969f0059c", "cases": 20106, - "non_null": 13256, + "non_null": 13310, "scaling_budget": 1.6, - "depth_budget": 2.4, + "depth_budget": 2.0, "small_ms_ceiling": 40, "_scaling_note": "(t_large/t_small)/(1600/400). ~1.0 is linear. OBSERVED BAND: 0.99-1.04 on a 12-core dev box, small arm ~6 ms. Read that band as a floor, not a spec — independent runs on other hardware during review came out 0.954-1.014, 0.965-1.036 and ~0.95-1.08, so a 1.2 reading is noise and should be re-run, not investigated. IMPORTS_PER_FILE is sized so the small arm lands in the ms rather than the ~2 ms a first revision measured, where timer granularity and JIT warm-up, not scaling, set the number; bench/cpp-qualified-ns documents the same artifact. TRIAGE: every timing arm here is a TIMING signal — RE-RUN IT on an idle machine before investigating; runner contention dominates. The fingerprint arm is the opposite: deterministic, a re-run never changes it, and it must never be wished away. FLOOR CHECK: the pre-index implementation — i.e. exactly the regression this gate exists to catch — measures ratio 3.737 on this corpus (2207.8 ms small, 33003.5 ms large, one cold run) against ~1.0 for the index. Independent review runs measured its floor at 3.905-4.297. Treat the absolute times as an order of magnitude only: the floor arm is one cold run because best-of-seven against a quadratic implementation costs minutes, while the index arm is best-of-seven after two warmups.", - "_depth_note": "deep_ms/shallow_ms at a FIXED file count, paths 24 components against 8. scaling_ratio divides the file count out, so it is scale-invariant and structurally cannot see a cost that grows with path depth instead — and both loops this change added are depth loops (one suffixByStem entry per '/' in a stem, one dirChildren pass per component of dir). OBSERVED BAND: 1.44-1.51 over four unloaded runs. It sits above 1.0 legitimately: 3x the depth is 3x the suffix keys per file, so the build genuinely does more work; what the budget of 2.4 forbids is that growing faster than the depth ratio itself.", - "_ceiling_note": "small_ms_ceiling is an ABSOLUTE bound, because scaling_ratio is a ratio and a constant-factor regression that grows both arms equally passes it. Measured during review: a full workspace scan reintroduced on 1-in-16 imports is caught by the ratio (1.814), but at 1-in-32 it passes at 1.490 while running 2.8x slower in absolute terms. 40 ms against an observed 5.9-6.1 ms leaves ~6x of headroom for a loaded shared runner while still catching that shape." + "_depth_note": "deep_ms/shallow_ms at a FIXED file count, paths 24 components against 8. scaling_ratio divides the file count out, so it is scale-invariant and structurally cannot see a cost that grows with path depth instead — and the two loops the index is built from are depth loops (one suffixByStem entry per '/' in a stem, one dirChildren pass per component of dir). OBSERVED BAND, five runs each on one box: 1.44-1.51 before #2881; 1.27-1.40 after its guard removal, which deleted two string comparisons per component of every dir; 1.20-1.26 after the same issue's per-directory key memo, which turns that whole component walk from once-per-FILE into once-per-DIRECTORY. Both movements are per-depth work, which is why this arm sees them and the file-count arm does not. The BUDGET moved with the band both times — 2.4 -> 2.2 -> 2.0 — holding the ~1.6x headroom over the band's top that 2.4 expressed against the original; left at 2.4 it would quietly have become 1.9x, which is how a gate goes slack without anyone deciding to loosen it. Note what this budget is NOT for: a revert of #2881 scores ~1.5 and passes at any of those numbers, and that is correct — reverting it restores a resolution bug, which is the FINGERPRINT's job to catch, not a timing arm's. It sits above 1.0 legitimately: 3x the depth is 3x the suffix keys per file, so the build genuinely does more work; what the budget forbids is that growing faster than the depth ratio itself.", + "_ceiling_note": "small_ms_ceiling is an ABSOLUTE bound, because scaling_ratio is a ratio and a constant-factor regression that grows both arms equally passes it. Measured during review: a full workspace scan reintroduced on 1-in-16 imports is caught by the ratio (1.814), but at 1-in-32 it passes at 1.490 while running 2.8x slower in absolute terms. 40 ms against an observed 5.9-6.1 ms leaves ~6x of headroom for a loaded shared runner while still catching that shape.", + "_blind_spot": "WHAT THIS BENCH CANNOT SEE, measured rather than guessed. Its scaling corpus gives every module a UNIQUE package leaf (`com/example/mod{N}`), so a `dirChildren` query matches exactly one directory. That makes it blind to any cost that grows with the number of DIRECTORIES sharing a queried segment — the shape a real Kotlin monorepo has, where 200 modules each hold `data`, `ui` and `domain`. Established by building the reuse this file's memo argues against: swapping `dirChildren` for the shared `import-resolvers/package-dir-index.ts` (with its first-occurrence rule off) is OUTPUT-IDENTICAL — same fingerprint, same cases, same non_null, 0 divergences over 107948 answers — and on THIS corpus it costs only 1.37x-1.50x and passes every arm here. On a repeated-leaf corpus the same swap measures 13.5x per first-child query, 409x per fan-out, and 8114x on `import data.*` at 200 matching directories (it merges and SORTS every candidate, per import), for 3.1x-5.7x end to end and a bench-style scaling_ratio of 3.465 against this file's 1.6 budget — i.e. back to the pre-index quadratic floor of 3.737. A change that regresses this resolver to the very shape the bench exists to catch would go GREEN here. The trade it buys is real and also measured: 26.2% less retained memory, 12.18 MiB at 32000 files. If that memory is ever wanted, the shape to build is per-suffix keys -> DIRECTORY lists plus files-per-directory (8.29 MiB against 15.87 measured, single-directory query still one hash lookup) — and the repeated-leaf arm to measure it against already exists one directory over: bench/import-target's kotlin `collide` layout puts `com/example/models` under 200 modules at the 1600-file scale, with `collide_scaling_budget` 1.8 against a measured 1.081. The swap scores 3.465 there. So the gate for this decision is that arm, not a new one here; what this file lacks is only a repeated-leaf arm of its own, which would be duplicated coverage." } diff --git a/gitnexus/bench/kotlin-import-target/measure.mjs b/gitnexus/bench/kotlin-import-target/measure.mjs index a11747153..5d1868910 100644 --- a/gitnexus/bench/kotlin-import-target/measure.mjs +++ b/gitnexus/bench/kotlin-import-target/measure.mjs @@ -60,13 +60,16 @@ * Set-iteration order — "first suffix match wins", and the two stem maps * keeping the FIRST path inserted per key. A single-order corpus scores an * implementation that keeps the LAST match identically. - * 2. **The correctness corpus contains repeated directory names where the - * first occurrence is not the parent** (`data/src/main/kotlin/com/example/ - * data/Repo.kt`). The pre-index scan tested `startsWith` and then used - * `indexOf`, so it only ever considered the FIRST `/dir/`; that file is - * therefore NOT a child of `data`. The index reproduces it deliberately. - * Without these shapes the fingerprint cannot tell the preserved rule from - * the intuitive one. + * 2. **The correctness corpus contains repeated directory names at BOTH the + * leading and the mid-path position** (`data/src/main/kotlin/com/example/ + * data/Repo.kt` and `top/data/mid/data/Repo.kt`). Until #2881 the resolver + * required a file's package directory to be the FIRST occurrence of that + * name in its own path, so neither file was a child of `data`; both are + * now, and that is what the fingerprint pins. Two positions, not one, + * because the old rule was two guards and a half fix that drops only the + * leading-position one still leaves the mid-path shape broken — see + * `_gate_controls` in baselines.json. Without these shapes the fingerprint + * cannot tell the current rule from either predecessor. * 3. **~40% of the scaling corpus's imports are unresolvable.** The old cost * was worst when nothing matched, because only then did all four tiers * run. A corpus where every import hits tier 1 exits after one pass and @@ -141,12 +144,7 @@ function record(files, targetRaw, fromFile = 'App.kt') { if (r !== null) nonNull++; const rendered = r === null ? 'NULL' : Array.isArray(r) ? `[${r.join(',')}]` : r; // The FILE SET is part of the hashed record, not just the query and the - // result — see header property 4. Without it a corpus edit that changes - // which workspace a case runs against, while leaving the result string - // alone, is invisible: dropping the competing file from the - // "exact beats an earlier suffix" case, or emptying the repeated-directory - // negative case, both leave `cases`, `non_null` and the fingerprint - // byte-identical. + // result — see header property 4. lines.push(`${order}\t${list.join('|')}\t${fromFile}\t${targetRaw}\t${rendered}`); } } @@ -187,7 +185,8 @@ record(['win\\pkg\\A.kt', 'win\\pkg\\B.kt'], 'win.pkg.someFunction'); record(['pkg/A.java', 'pkg/A.md', 'pkg/A.kt.txt'], 'pkg.A'); // Kotlin file alongside non-Kotlin noise of the same stem. record(['pkg/A.java', 'pkg/A.kt'], 'pkg.A'); -// Header property 2: repeated directory name, first occurrence is not the parent. +// Header property 2: repeated directory name — a child of the repeated package +// since #2881, at the leading position here and mid-path below. record(['data/src/main/kotlin/com/example/data/Repo.kt'], 'data.something'); record(['data/src/main/kotlin/com/example/data/Repo.kt'], 'data.Repo'); record(['a/c/b/c/File.kt'], 'c.X'); diff --git a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts b/gitnexus/src/core/ingestion/import-resolvers/csharp.ts index 9183fbb24..e8d6fdf7a 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts +++ b/gitnexus/src/core/ingestion/import-resolvers/csharp.ts @@ -25,19 +25,31 @@ import { csharpSuffixFallbackAllowed } from '../csharp-namespace-gate.js'; * normalized directory of a `.cs` file and `dirPrefix` for the query: * * let H = D + '/', P = dirPrefix + '/' - * match ⟺ H.length >= P.length && H.indexOf(P) === H.length - P.length + * match ⟺ H.endsWith(P) * - * Derivation, because both halves are load-bearing: + * Derivation: * - the scan keeps a file only when nothing after the matched occurrence holds * a slash, so the occurrence's trailing '/' must be the file's LAST slash — * i.e. `H` ends with `P`; - * - it uses `indexOf`, the FIRST occurrence, so `a/Models/b/Models/x.cs` does - * NOT answer `Models`: the first `Models/` is found and `b/Models/x.cs` - * still contains a slash. Dropping that half moves edges in every repo that - * nests a directory name inside itself. + * - it used `indexOf`, the FIRST occurrence, so `a/Models/b/Models/x.cs` did + * NOT answer `Models`. That half was removed in #2881: it was an artifact of + * how the pre-index scan was written, not a rule about C# namespaces, and it + * dropped every repository that nests a directory name inside itself. The + * same removal landed in `package-dir-index.ts` and in step 2 below, which + * have to move together — see the note at step 3. * - the needle ends with '/', so every occurrence of it lies wholly inside * `D + '/'` and never reaches into the file name — which is what lets the - * whole test be evaluated on `D` alone. + * whole test be evaluated on `D` alone; + * - and then the '/' cancels. `(D + '/').endsWith(P + '/')` IS `D.endsWith(P)`: + * the appended character only ever matches itself, so it decides nothing and + * the comparison of everything before it is unchanged. The predicate the code + * actually runs is therefore + * + * match ⟺ D.endsWith(dirPrefix) + * + * with no concatenation on either side. Verified rather than argued: over + * every ordered pair of strings up to length 5 over `{a, b, '/'}` including + * the empty string — 132 496 pairs — the two forms disagreed 0 times. * * NOT the same query as `package-dir-index.ts`, and the difference is exactly * one character on each side: that module tests `'/'+D+'/'` against @@ -50,6 +62,11 @@ import { csharpSuffixFallbackAllowed } from '../csharp-namespace-gate.js'; * "cleaned up" into a reuse of `filesDirectlyInPkgDir` — see * `test/unit/import-resolvers/csharp-csproj-parity.test.ts`. * + * That one character is also why the cancellation above empties this predicate + * out but not that one: the decoration is one term per side here (`D + '/'`) and + * two there (`'/' + D + '/'`), and only the TRAILING '/' cancels. Here nothing + * is left to concatenate; there the leading segment anchor has to stay. + * * Candidates are narrowed by the directory's LAST segment, the same * O(directories) bucket `package-dir-index.ts` uses instead of an * O(files × depth) suffix map (#2649). @@ -176,14 +193,32 @@ function* matchingDirPositions( index: CsharpNamespaceDirIndex, dirPrefix: string, ): Generator { - const needle = dirPrefix + '/'; for (const dir of candidateDirs(index, dirPrefix)) { - const haystack = dir + '/'; - // The length guard is not redundant: for a shorter `haystack`, `indexOf` - // returns -1 and `haystack.length - needle.length` can also be -1, which - // would report a bogus match. - if (haystack.length < needle.length) continue; - if (haystack.indexOf(needle) !== haystack.length - needle.length) continue; + // `(dir + '/').endsWith(dirPrefix + '/')` IS `dir.endsWith(dirPrefix)` — the + // appended '/' only ever matches itself, so it decides nothing and BOTH + // concatenations go. Exhaustively verified, not assumed: 0 disagreements + // over every ordered pair of strings up to length 5 over `{a, b, '/'}` + // including '' (132 496 pairs). Measured 64.9 ns -> 18.4 ns per candidate + // (Node 22.18); the `dir + '/'` was paid once per candidate, on every sweep + // of the last-segment keys. + // + // Still deliberately UNANCHORED (no leading '/'), so `src/SubModels` keeps + // answering `Models` — see the derivation above. That is also exactly why + // the reduction empties this predicate out while `package-dir-index.ts` + // keeps its concatenations: one decorating term per side here, two there, + // and only the trailing one cancels. + // + // `endsWith` subsumes the length guard the `indexOf` form needed: a shorter + // `dir` is simply false, where `indexOf` returned -1 and + // `haystack.length - needle.length` could also be -1 and report a bogus + // match. + // + // Do NOT "finish the job" with the two-argument overload. `endsWith(search, + // endPosition)` measured 8.8-11.8 ns against 9.5-14.9 ns for the + // one-argument form across seven call-site shapes (Node 22.18) — a wash — + // and `dir.endsWith(dirPrefix, dir.length)` is character-for-character this + // same test anyway. There is nothing left here to win. + if (!dir.endsWith(dirPrefix)) continue; const positions = index.positionsByDir.get(dir); if (positions !== undefined) yield positions; } @@ -284,15 +319,48 @@ export function resolveCSharpImportInternal( // 2. Try as directory: all .cs files directly inside (namespace import) if (index) { const dirFiles = index.getFilesInDir(dirPrefix, '.cs'); + // `getFilesInDir` already answers "directly inside a directory `D` where + // `D === dirPrefix || D.endsWith('/' + dirPrefix)`" — its keys ARE + // segment-aligned directory suffixes. So for a non-empty `dirPrefix` the + // direct-child re-check this loop used to run cannot reject anything, and + // measurement agrees: zero rejections over 12 008 (prefix, candidate) + // pairs. It rejected before #2881 only because it asked `indexOf` for the + // FIRST `//`, which is the rule that issue removed. + // + // That widening does not stay inside step 2's own bucket. This step + // returns as soon as it pushes anything, so a query it used to answer with + // nothing now also SUPPRESSES step 3, whose unanchored match set is a + // strict superset: over `SubModels/Models/F1.cs` + `SubModels/F3.cs`, + // `using App.Models` answered both through step 3 and now answers only the + // first through step 2. The new answer is the more precise one — a + // directory literally named `Models` beating a character-suffix hit on + // `SubModels` — and it is what this module's step-2-before-step-3 layering + // asks for, so it is kept rather than worked around. Pinned absolutely by + // the parity test, which is differentially blind to it (its frozen legacy + // copy moved in lockstep with this line). + // + // The empty prefix is the exception and keeps a real filter. `getDirMap` + // keys a file under every suffix of its DIRECTORY, so it emits the EMPTY + // one exactly when that directory's last component is empty: a leading '/' + // on a root-level file, or a doubled slash immediately before the file + // name. Probed against `getDirMap`'s own key emission: + // + // src/X.cs -> ['src:.cs'] no empty key + // /X.cs -> [':.cs'] empty key + // a//X.cs -> [':.cs', 'a/:.cs'] empty key + // /a/b/X.cs -> ['b:.cs', 'a/b:.cs', '/a/b:.cs'] no empty key + // + // So the `''` bucket is not "one directory deep" on its own — `a//X.cs` + // sits in it two components down — while step 3 answers that same query + // from `singleSegmentDirs`, which is. Filtering on `D` holding no slash is + // what rejects `a//X.cs` and keeps steps 2 and 3 in agreement. for (const f of dirFiles) { - const normalized = f.replace(/\\/g, '/'); - // Check it's a direct child by finding the dirPrefix and ensuring no deeper slashes - const prefixIdx = normalized.indexOf(dirPrefix + '/'); - if (prefixIdx < 0) continue; - const afterDir = normalized.substring(prefixIdx + dirPrefix.length + 1); - if (!afterDir.includes('/')) { - results.push(f); + if (dirPrefix === '') { + const normalized = f.replace(/\\/g, '/'); + const lastSlash = normalized.lastIndexOf('/'); + if (lastSlash < 0 || normalized.slice(0, lastSlash).includes('/')) continue; } + results.push(f); } if (results.length > 0) return results; } @@ -301,7 +369,7 @@ export function resolveCSharpImportInternal( // // Not redundant with step 2, and not skippable when `index` is present: // `getFilesInDir` is keyed on SEGMENT suffixes of a directory, while this - // leg's predicate is an unanchored substring one, so it additionally + // leg's predicate is an unanchored ends-with one, so it additionally // answers `Models` with `src/SubModels/` and `src/Models` with // `vendor/mysrc/Models/`. It is also the only leg that answers an empty // `dirPrefix` — the `relative = ''` branch above (the import IS the root diff --git a/gitnexus/src/core/ingestion/import-resolvers/go.ts b/gitnexus/src/core/ingestion/import-resolvers/go.ts index f4ac5048a..eb87b0997 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/go.ts +++ b/gitnexus/src/core/ingestion/import-resolvers/go.ts @@ -3,10 +3,23 @@ * * Strategy lives in configs/go.ts. * This file contains the shared helpers used by the strategy. + * + * **Reachability, as of #2929:** nothing in production calls either export + * today. The only path in is `configs/go.ts` → `createImportResolver` → + * the `importResolver` field on Go's `LanguageProvider`, and that field is + * read at exactly two lines — `import-target-adapter.ts:74-75` — whose two + * exports (`buildImportTargetWorkspace`, + * `resolveImportTargetAcrossLanguages`) have no importer anywhere but their + * own unit test. So this is a live-looking but currently unwired leg; the + * tests in `test/unit/import-resolvers/go-package-resolve.test.ts` are the + * only thing watching it. */ import type { GoModuleConfig } from '../language-config.js'; +/** `'/'`, for the parent-directory boundary check in `resolveGoPackage`. */ +const SLASH_CODE = 47; + /** * Extract the package directory suffix from a Go import path. * Returns the suffix string (e.g., "/internal/auth/") or null if invalid. @@ -28,29 +41,39 @@ export function resolveGoPackage( normalizedFileList: readonly string[], allFileList: readonly string[], ): string[] { - if (!importPath.startsWith(goModule.modulePath)) return []; + // Identical to the six lines this used to re-derive; `resolveGoPackageDir` + // returns the '/'-wrapped form and the scan wants the bare path, so unwrap. + const pkgDir = resolveGoPackageDir(importPath, goModule); + if (pkgDir === null) return []; + const relativePkg = pkgDir.slice(1, -1); // "/internal/auth/" → "internal/auth" - // Strip module path to get relative package path - const relativePkg = importPath.slice(goModule.modulePath.length + 1); // e.g., "internal/auth" - if (!relativePkg) return []; - - const pkgSuffix = '/' + relativePkg + '/'; + const pkgLen = relativePkg.length; // >= 1: `resolveGoPackageDir` rejects empty const matches: string[] = []; for (let i = 0; i < normalizedFileList.length; i++) { - // Prepend '/' so paths like "internal/auth/service.go" match suffix "/internal/auth/" - const normalized = '/' + normalizedFileList[i]; - // File must be directly in the package directory (not a subdirectory) - if ( - normalized.includes(pkgSuffix) && - normalized.endsWith('.go') && - !normalized.endsWith('_test.go') - ) { - const afterPkg = normalized.substring(normalized.indexOf(pkgSuffix) + pkgSuffix.length); - if (!afterPkg.includes('/')) { - matches.push(allFileList[i]); - } - } + const normalized = normalizedFileList[i]; + if (!normalized.endsWith('.go') || normalized.endsWith('_test.go')) continue; + // The file's PARENT directory ends with the package path — the same + // predicate `package-dir-index.ts` states. This used to ask `indexOf` for + // the FIRST `//` and then check that nothing after it held a slash, + // which made `a/pkg/b/pkg/x.go` not a member of `pkg` (#2881). + // + // Expressed as "`relativePkg` sits immediately before the last slash, on a + // segment boundary". The boundary is either the start of the path (an + // import matching from index 0, `internal/auth/x.go`) or a `/` — which is + // what the old `'/' + path` cons bought, at the price of a per-file + // concatenation the first `endsWith` forced V8 to flatten (#2929). + // + // Rewriting this as `endsWith(relativePkg, lastSlash)` buys nothing: the + // two-argument overload measured a wash against `startsWith(needle, pos)` + // here (10.28 ns vs 9.82 ns), so it trades the clarity of an explicit start + // index for no gain. A "the 2-arg overload leaves V8's fast path, 20x" + // claim from review did not reproduce on Node 22.18 — its baseline was a + // one-argument call that early-exited on the length precheck. + const start = normalized.lastIndexOf('/') - pkgLen; // < 0 when there is no parent dir + if (start < 0 || !normalized.startsWith(relativePkg, start)) continue; + if (start > 0 && normalized.charCodeAt(start - 1) !== SLASH_CODE) continue; + matches.push(allFileList[i]); } return matches; diff --git a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts b/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts index 371eae9bf..cb7e77ed0 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts +++ b/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts @@ -12,15 +12,51 @@ * * let D = '/' + + '/' * let P = '/' + pkgPath + '/' + * match ⟺ D.endsWith(P) + * + * It used to say one more thing, and #2881 removed it: + * * match ⟺ D.length >= P.length && D.indexOf(P) === D.length - P.length * - * The right-hand side says two things at once, and BOTH are load-bearing: - * 1. `D` ends with `P` — the file's directory ends with `pkgPath`; - * 2. that trailing occurrence is the FIRST one — so `a/pkg/b/pkg/x.go` does - * NOT answer `pkg`, because the original `indexOf` found the earlier `/pkg/` - * and `b/pkg/x.go` still contained a slash. Dropping condition 2 looks like - * a cleanup and moves edges in every repository that nests a directory name - * inside itself (`internal/…/internal`, `Models/…/Models`). + * — i.e. `D` ends with `P` AND that trailing occurrence is the FIRST one, so + * `a/pkg/b/pkg/x.go` did NOT answer `pkg`. The second half was never a rule + * anyone chose. It is what the pre-index per-import scan happened to compute + * (it called `indexOf`, then checked that nothing after the match contained a + * slash), and the index was built to reproduce that scan byte for byte. It + * dropped exactly the repositories that nest a directory name inside itself: + * `internal/…/internal`, `Models/…/Models`, and the reported shape + * `data/src/main/kotlin/com/example/data/Repo.kt`, where `import data.helper` + * resolved to null. Kotlin was fixed first, in its own `dirChildren` + * (`languages/kotlin/import-target.ts`); this index, the C# csproj index and + * the legacy `go.ts` scan followed. + * + * The strongest evidence that the rule was accidental is that a sixth + * implementation of the same question never had it. `import-resolvers/jvm.ts` + * answers "files directly inside a directory ending with " for + * Java and Kotlin wildcard imports, and has used `lastIndexOf` since #488. + * + * That is evidence about how the predicate was WRITTEN, not about live + * behaviour, and the distinction matters enough to spell out. `jvm.ts` is + * reached only through `provider.importResolver`, which `languages/java.ts` and + * `languages/kotlin.ts` do wire — but that field currently has no production + * READER. Its only reader anywhere is `import-target-adapter.ts`, whose own + * docblock says it is "threaded through `finalizeScopeModel`"; nothing threads + * it, and neither that module nor its two exports + * (`buildImportTargetWorkspace`, `resolveImportTargetAcrossLanguages`) is + * referenced outside its own unit test. So `jvm.ts`'s `resolveJvmWildcard` and + * `import-resolvers/go.ts`'s `resolveGoPackage` are dormant, while THIS index, + * `csharp.ts`'s `resolveCSharpImportInternal` and Kotlin's `dirChildren` are + * the ones that run. Whether those two dormant resolvers should be deleted or + * actually wired up is an open question and wants its own issue; it is not + * settled here. + * + * The argument survives that correction intact, because it never needed the + * resolvers to be live: an independent implementation of the same question, + * written without reference to the pre-index scan, reached for `lastIndexOf`. + * The extra clause was never a rule anyone chose. All six spellings now agree. + * + * The length guard the `indexOf` form needed is gone with it: `endsWith` is + * false for a shorter `D` instead of comparing -1 to -1. * * Candidates are narrowed by the directory's LAST segment rather than by * indexing every directory suffix: a suffix map costs O(files × depth) entries, @@ -120,14 +156,40 @@ function* matchingDirs(index: PackageDirIndex, pkgPath: string): Generator.java` suffix key, so the * extension filter is implied on the file/suffix legs and explicit in the * directory index's `accept`. - * 5. The directory-child leg matched on the FIRST `'/' + pathLike + '/'` - * occurrence, so `com/example/com/example/Deep.java` does NOT answer - * `com.example`. `firstFileDirectlyInPkgDir` encodes exactly that rule (see - * the header of `import-resolvers/package-dir-index.ts`). + * 5. The directory-child leg used to match on the FIRST `'/' + pathLike + '/'` + * occurrence, so `com/example/com/example/Deep.java` did NOT answer + * `com.example`. #2881 removed that: the rule came from how the pre-index + * scan was written, not from Java, and it made a package whose name repeats + * higher in the path unresolvable. `firstFileDirectlyInPkgDir` now answers + * plain "the parent directory ends with `pathLike`" (see the header of + * `import-resolvers/package-dir-index.ts`). This leg commits to ONE file + * with no downstream filter, so widening it can change which file an + * already-resolving import binds to, not only turn a null into a hit. + * WHICH file it binds to is decided by nothing in this resolver: it is + * `allFilePaths` iteration order, i.e. the insertion order of the Set built + * from `parsedFiles` in `scope-resolution/pipeline/run.ts`, which for a full + * scan is the canonical sorted path order `filesystem-walker.ts` imposes on + * its unsorted recursive-`glob` result. So the widened set's winner is a + * property of the file list, not of the import — pinned explicitly, in both + * insertion orders, by "pins WHICH of two competing package directories the + * first-child leg takes" in + * `test/unit/scope-resolution/java-import-target-parity.test.ts` (Kotlin's + * twin, which has the same unfiltered first-child leg, is in + * `test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts`). */ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; diff --git a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts index 6f20e5d6f..33de337ee 100644 --- a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts @@ -88,8 +88,10 @@ function findKotlinDirectoryChild(index: KotlinFileIndex, pathLike: string): str if (pathLike === '') return null; const children = index.dirChildren.get(pathLike); // "First" is first in `allFilePaths` iteration order, which the index - // preserves by appending as it walks the set — the same file the scan - // used to return. + // preserves by appending as it walks the set. Since #2881 that can be an + // EARLIER file than the pre-index scan returned, never a later one: the + // guards that fell take members away from no bucket, so a bucket only ever + // gains, and a gained member lands wherever set iteration puts it. return children === undefined ? null : (children[0] ?? null); } @@ -156,22 +158,89 @@ function findByProgressivePrefixStrip(index: KotlinFileIndex, pathLike: string): * The shared `buildSuffixIndex` (`import-resolvers/utils.ts`, used by C#, Ruby, * Vue and TypeScript) is deliberately NOT reused — the same call Python * documents at `python/import-target.ts`. Run side by side against this - * resolver, four probes out of five diverge: + * resolver, three probes out of five diverge: * * - `['deep/util/User.kt', 'util/User.kt']` for `util.User` — it conflates * exact and proper-suffix matches in one map, so the deep path wins where * the scan returned the exact one; * - `['deep/util/User.kt', 'util/User.kts']` for `util.User` — its keys carry * the extension, so a `.kt` SUFFIX beats a `.kts` EXACT; - * - `['data/src/…/data/Repo.kt']` for `data.getRepo` — it indexes every - * directory suffix with no first-occurrence rule, so it fans out where the - * scan returned null; * - `['models/A.kts', 'models/B.kt']` for `models.getThing` — it splits the * package into `:kt` and `:kts` buckets instead of returning both in set * order. * - * Each divergence is an edge that would move in every Kotlin repository, so + * A fourth probe — `['data/src/…/data/Repo.kt']` for `data.getRepo`, where the + * shared index fanned out and this one returned null — stopped diverging in + * #2881, which removed the first-occurrence rule that caused it. The remaining + * three are still edges that would move in every Kotlin repository, so * consolidating the two is a behaviour change, not a cleanup. + * + * `dirChildren` is likewise NOT the shared `import-resolvers/package-dir-index.ts` + * — the consolidation a maintainer will actually propose, since Java routes + * through exactly it (`languages/java/import-target.ts`). Measured, that swap is + * output-identical for 26.2% less retained memory, and costs 8114x on + * `import data.*` at 200 matching directories. `bench/kotlin-import-target` + * CANNOT see that regression — its corpus gives every module a unique package + * leaf — and the arm that can is `bench/import-target`'s kotlin `collide`. See + * `_blind_spot` in `bench/kotlin-import-target/baselines.json`. + * + * `dirChildren`'s bucket rule, and what #2881 removed + * --------------------------------------------------- + * A file is a child of its own directory and of every component-suffix of that + * directory, unguarded. The suffix half used to carry two guards inherited from + * the pre-index per-import scan rather than from anything Kotlin requires (the + * same generation of code put the `indexOf` half into + * `import-resolvers/package-dir-index.ts` and `import-resolvers/csharp.ts`, + * where it was removed under the same issue): `startsWith(s + '/')` skipped the + * bucket outright, and an `indexOf` equality demanded that the parent be the + * FIRST `/s/` in the path. Between them they dropped the bucket whenever the + * package name repeated higher up the tree, so + * `data/src/main/kotlin/com/example/data/Repo.kt` was not a child of `data` + * (leading segment, `startsWith`) and neither was `top/data/mid/data/Repo.kt` + * (mid-path, `indexOf`). `import data.helper` resolved to null in both. Only + * the fan-out tier looked affected — `data.Repo` answers from `suffixByStem`, + * which never had such a guard — which is why the shape looked narrow enough to + * preserve. + * + * Nothing downstream narrows a widened bucket back at the FILE level. The + * `localDefs` filter of #1759 constrains `targetDefId`/`BindingRef` ONLY: the + * finalize pass mints one draft PER CANDIDATE, each keeping its own + * `targetFile` (`gitnexus-shared/src/scope-resolution/finalize-algorithm.ts`), + * and the one File→File filter downstream + * (`scope-resolution/graph-bridge/imports-to-edges.ts`) tests `targetFile` + * against `null` and against the source file, never reads `linkStatus`, and + * emits `IMPORTS` at confidence 1.0. So every extra bucket member becomes an + * unconditional File→File `IMPORTS` edge: one `import data.load` on an + * Android-style layout measured 5 → 6 edges, the added one `unresolved`. That + * is a real cost, paid deliberately — a MISSING bucket is unrecoverable, and + * there is no version of the bucket that is right for one consumer and wrong + * for the other. Narrowing the File→File side, if it is ever wanted, is a + * downstream filter and a separate change. + * + * What moved, over the corpus: of the 235 records the published census counted, + * 149 are a different first child, 32 are a wider fan-out array, and 54 are + * null → resolved — none of which turns a bound answer into an unbound one. + * That taxonomy has no bucket for a fourth outcome class this change + * introduces, and did not count it. Tier 3 + * (`findKotlinPackageFiles`) precedes tier 4 (`findByProgressivePrefixStrip`), + * so a bucket the guards used to leave empty returned null and let tier 4 run; + * a now-populated bucket stops tier 4 from running at all, which turns a + * resolved answer into an unresolved one and a `string` into an array: + * + * ['data/src/main/kotlin/com/example/data/Repo.kt', 'common/helper.kt'] + * with `import data.helper` + * before → 'common/helper.kt' (bound) + * after → ['data/src/main/kotlin/com/example/data/Repo.kt'] (no `helper`) + * + * Over the census corpus that class is ZERO records — and the zero is the + * point, not a reprieve. The shape above is real and reproduces by hand in + * both iteration orders; running `bench/kotlin-import-target`'s own generator + * at 10x (4000 repositories, ~198 600 distinct records) hits it 4-12 times per + * seed, i.e. an expectation of about ONE over this corpus's 19 968. So the + * fingerprint does not gate this class: it is the same blindness the go arm had + * before #2881 widened its corpus — a gate cannot catch a shape its corpus + * cannot express. Adding a case is a deliberate fingerprint move and belongs in + * its own change, with the re-baseline that implies. */ interface KotlinFileIndex { readonly exactByStem: Map; @@ -187,7 +256,44 @@ const getKotlinFileIndex = perFileSet((allFilePaths: ReadonlySet): Kotli const exactByStem = new Map(); const suffixByStem = new Map(); - const dirChildren: MutableDirChildren = new Map(); + const dirChildren = new Map(); + /** + * BUILD-LOCAL: `dir` -> every `dirChildren` key a file in that directory + * contributes to. That list is a pure function of `dir`, and a package + * directory holds many files, so without this the walk below cuts one `slice` + * per component of the SAME directory once per FILE — and every slice after + * the first file's is a freshly allocated string that hashes to a key the map + * already holds and is then dropped. Interning them once per DIRECTORY + * instead of once per FILE is ~21% of the build at 32 000 files. + * + * It cannot move an answer. The array is filled on the first file of a + * directory, in the order the per-file walk produced, and every later file in + * that directory finds those keys already present — so the key set, the Map's + * key insertion order and every bucket's order are what the per-file form + * produced. `kotlin-index-internals.test.ts` pins the part of that a consumer + * can observe, and does it through the resolver's own surface rather than over + * the built maps: bucket CONTENTS and ORDER (from the fan-out tier, which + * hands out the bucket array itself), bucket IDENTITY across calls, and that + * the array handed out is FROZEN. Be precise about the limits, because the + * mutation matrix in that file's header measured them: a MIS-KEYED memo is + * caught, a DELETED one is not — the memo is output-identical by construction, + * so nothing observable can prove it ran. Likewise `Object.isFrozen` catches a + * missing freeze and a compacted-but-never-stored copy, but NOT a deleted + * `slice()`: a JS array's backing-store capacity has no reflective surface, so + * the compaction's only instrument is `heap_ceiling_bytes.kotlin` in + * `bench/import-target/baselines.json` — a CEILING, because compaction + * reclaims, so losing it makes the retained reading grow (+12.57% measured). + * Map key insertion ORDER is + * unasserted BY DESIGN: + * `dirChildren` is only ever read by `.get(key)`, so key order has no + * consumer and pinning it would assert an implementation detail nothing + * depends on. Nothing else watches it either — the correctness fingerprint + * sees this index only through the four tiers, so no fingerprint could catch + * a key-order move. + * + * Dropped with this frame, so it costs nothing retained. + */ + const dirKeys = new Map(); for (const raw of allFilePaths) { const norm = raw.replace(/\\/g, '/'); @@ -206,60 +312,62 @@ const getKotlinFileIndex = perFileSet((allFilePaths: ReadonlySet): Kotli if (!suffixByStem.has(suffix)) suffixByStem.set(suffix, raw); } - const lastSlash = norm.lastIndexOf('/'); + // From `stem`, not `norm`: an extension carries no '/', so the last '/' of + // the two is the same character at the same index, and `stem.slice(0, + // lastSlash)` IS the string `norm.slice(0, norm.lastIndexOf('/'))` was. One + // backwards scan instead of two, over the string this loop already walked. + const lastSlash = stem.lastIndexOf('/'); if (lastSlash < 0) continue; // repo-root file has no package directory - const dir = norm.slice(0, lastSlash); + const dir = stem.slice(0, lastSlash); - // The file's own directory always qualifies: the old scan's `atRoot` branch - // matched `norm.startsWith(dir + '/')` and found no '/' after it. - addChild(dirChildren, dir, raw); - - // A component-suffix of the directory also qualifies — but only under the - // rule the scan actually implemented, which is narrower than "the parent - // directory is named `s`": - // - // - `atRoot` was tested FIRST, so if the path *starts* with `s + '/'` the - // scan used index 0 and the remainder still contained '/', i.e. no - // match — even when a later directory is also named `s`. - // - otherwise it used `indexOf`, the FIRST occurrence of `/s/`. A path - // like `data/src/main/kotlin/com/example/data/Repo.kt` therefore does - // NOT count as a child of `data`: the first `/data/` is not the parent, - // and the scan never looked for a second one. - // - // Preserving that exactly keeps this a pure performance change. It is - // arguably a bug — the file IS a direct child of a `data` directory — but - // fixing it here would silently move edges in every Kotlin repository, - // which belongs in its own change with its own fixtures. - for (let i = 0; i < dir.length; i++) { - if (dir[i] !== '/') continue; - const suffix = dir.slice(i + 1); - if (norm.startsWith(`${suffix}/`)) continue; - if (norm.indexOf(`/${suffix}/`) === dir.length - suffix.length - 1) { - addChild(dirChildren, suffix, raw); + // The keys this file's directory contributes to, unguarded: `dir` itself, + // plus every component-suffix of it. A suffix `s` starts just after a '/', + // so `dir` ends with `/s` by construction and the file IS a direct child of + // a directory named `s`. The absence of a narrowing guard is deliberate — + // see the `dirChildren` section on `KotlinFileIndex` for the two guards + // #2881 dropped and for what the resulting width costs downstream. + let keys = dirKeys.get(dir); + if (keys === undefined) { + keys = [dir]; + for (let i = 0; i < lastSlash; i++) { + if (dir[i] === '/') keys.push(dir.slice(i + 1)); } + dirKeys.set(dir, keys); + } + for (const key of keys) { + const bucket = dirChildren.get(key); + if (bucket === undefined) dirChildren.set(key, [raw]); + else bucket.push(raw); } } + // Buckets are mutable only while this function runs; the index type hands + // them out `readonly` and they are frozen here, before it is cached. // `findKotlinPackageFiles` hands a bucket straight out of the index — the - // same array `findKotlinDirectoryChild` reads `children[0]` from. The - // `readonly string[]` return type does not survive the caller: the finalize - // pass normalizes with `Array.isArray(t) ? t : [t]`, and `isArray`'s - // `arg is any[]` predicate widens the true branch, so `tsc --strict` accepts - // a `.sort()` or `.push()` there. A downstream sort would permanently - // reorder the cached bucket and flip the FIRST-child tier's answer for every - // later import in the run. Freezing makes the contract true at runtime, so a - // future mutation is a loud TypeError instead of a silent edge move. - for (const bucket of dirChildren.values()) Object.freeze(bucket); + // same array `findKotlinDirectoryChild` reads `children[0]` from — so a + // downstream sort would permanently reorder the cached bucket and flip the + // FIRST-child tier's answer for every later import in the run. The finalize + // pass normalizes with `Array.isArray(t) ? t : [t]` and `isArray`'s + // `arg is any[]` predicate widens the true branch; that one call site now + // carries an explicit `readonly string[]` annotation, but the annotation is + // one deletion away and covers only that site. Freezing makes the contract + // true at runtime, so a future mutation is a loud TypeError, not a silent + // edge move. + // + // COMPACTED as they are frozen: buckets grow by `push`, so V8's growth + // overshoot stays retained for the life of the index. `length === 1` never + // grew and is skipped — slicing it saves zero bytes and costs 31% of the + // build on a corpus of single-file packages. The byte accounting lives once, + // in `bench/import-target/baselines.json`. + for (const [key, bucket] of dirChildren) { + if (bucket.length === 1) { + Object.freeze(bucket); + continue; + } + const compacted = bucket.slice(); + Object.freeze(compacted); + dirChildren.set(key, compacted); + } return { exactByStem, suffixByStem, dirChildren }; }); - -function addChild(dirChildren: Map, dir: string, raw: string): void { - const bucket = dirChildren.get(dir); - if (bucket === undefined) dirChildren.set(dir, [raw]); - else bucket.push(raw); -} - -/** Mutable view of the buckets, used only while building — the index exposes - * them as `readonly` and freezes them before it is cached. */ -type MutableDirChildren = Map; diff --git a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts index 3bcc17ef1..d3ed9b42d 100644 --- a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts +++ b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts @@ -12,7 +12,10 @@ * That is wrong, and this file is the proof. Step 2 filters * `index.getFilesInDir(dirPrefix, '.cs')`, whose buckets are keyed on * SEGMENT-aligned directory suffixes; step 3 runs an UNANCHORED - * `normalized.indexOf(dirPrefix + '/')`. Step 3 therefore answers strictly more: + * `normalized.lastIndexOf(dirPrefix + '/')` (`indexOf` before #2881, which is + * the first-occurrence rule that issue removed; the empty-prefix case still + * takes `indexOf` — see `directChildIdx`, which both copies call). Step 3 + * therefore answers strictly more: * * - `dirPrefix = 'ubModels'` matches `src/SubModels/` (character suffix of a * segment, not a segment); @@ -58,6 +61,26 @@ import type { // `SuffixIndex`) are imported from production because this PR does not touch // them; only the function below changed. +/** + * The direct-child probe the frozen copies below run — four call sites, two in + * each copy, that have to move together. + * + * Direct child of a directory ENDING with `dirPrefix` — since #2881, minus + * "…and that occurrence is the FIRST". Empty `dirPrefix` keeps `indexOf`: its + * needle is a bare '/', and step 3 answers that query from the + * one-directory-deep set, which only the first occurrence expresses. + * + * Local to this file on purpose. A parity harness has to stay independent of + * PRODUCTION — that independence is the whole instrument, and importing this + * expression from `csharp.ts` would make the differential compare production + * against itself. But all four copies live inside the harness, so one local + * helper keeps the independence while removing three sites that could silently + * drift apart from each other. + */ +function directChildIdx(normalized: string, dirPrefix: string, dirTrail: string): number { + return dirPrefix === '' ? normalized.indexOf(dirTrail) : normalized.lastIndexOf(dirTrail); +} + function legacyResolveCSharpImportInternal( importPath: string, csharpConfigs: CSharpProjectConfig[], @@ -99,13 +122,17 @@ function legacyResolveCSharpImportInternal( if (suffixResult) return [suffixResult]; } + // Shared by steps 2 and 3 — the same needle, and since #2881 the same + // `indexOf`-only-when-empty rule, so it is declared once rather than + // re-derived per step. + const dirTrail = dirPrefix + '/'; + // 2. Try as directory: all .cs files directly inside (namespace import) if (index) { const dirFiles = index.getFilesInDir(dirPrefix, '.cs'); for (const f of dirFiles) { const normalized = f.replace(/\\/g, '/'); - // Check it's a direct child by finding the dirPrefix and ensuring no deeper slashes - const prefixIdx = normalized.indexOf(dirPrefix + '/'); + const prefixIdx = directChildIdx(normalized, dirPrefix, dirTrail); if (prefixIdx < 0) continue; const afterDir = normalized.substring(prefixIdx + dirPrefix.length + 1); if (!afterDir.includes('/')) { @@ -117,11 +144,10 @@ function legacyResolveCSharpImportInternal( // 3. Linear scan fallback for directory matching if (results.length === 0) { - const dirTrail = dirPrefix + '/'; for (let i = 0; i < normalizedFileList.length; i++) { const normalized = normalizedFileList[i]; if (!normalized.endsWith('.cs')) continue; - const prefixIdx = normalized.indexOf(dirTrail); + const prefixIdx = directChildIdx(normalized, dirPrefix, dirTrail); if (prefixIdx < 0) continue; const afterDir = normalized.substring(prefixIdx + dirTrail.length); if (!afterDir.includes('/')) { @@ -185,11 +211,13 @@ function skipStep3WhenIndexed( if (suffixResult) return [suffixResult]; } + const dirTrail = dirPrefix + '/'; + if (index) { const dirFiles = index.getFilesInDir(dirPrefix, '.cs'); for (const f of dirFiles) { const normalized = f.replace(/\\/g, '/'); - const prefixIdx = normalized.indexOf(dirPrefix + '/'); + const prefixIdx = directChildIdx(normalized, dirPrefix, dirTrail); if (prefixIdx < 0) continue; const afterDir = normalized.substring(prefixIdx + dirPrefix.length + 1); if (!afterDir.includes('/')) { @@ -200,11 +228,10 @@ function skipStep3WhenIndexed( continue; } - const dirTrail = dirPrefix + '/'; for (let i = 0; i < normalizedFileList.length; i++) { const normalized = normalizedFileList[i]; if (!normalized.endsWith('.cs')) continue; - const prefixIdx = normalized.indexOf(dirTrail); + const prefixIdx = directChildIdx(normalized, dirPrefix, dirTrail); if (prefixIdx < 0) continue; const afterDir = normalized.substring(prefixIdx + dirTrail.length); if (!afterDir.includes('/')) { @@ -252,8 +279,10 @@ const RAW_FILES: readonly string[] = [ // Character suffix across a segment boundary: answers `rc/Models`. 'vendor/mysrc/Models/Vendored.cs', 'src/Models/Late.cs', - // `Models` nested inside `Models`: the FIRST `indexOf` occurrence is the - // outer one, whose remainder still holds a slash, so this answers nothing. + // `Models` nested inside `Models`. Answered nothing until #2881, because the + // FIRST `indexOf` occurrence was the outer one and its remainder still held a + // slash; the predicate now asks whether the file's DIRECTORY ends with the + // prefix, which the inner `Models` satisfies. 'nest/Models/inner/Models/Ignored.cs', // Single-segment directory, so it answers the empty `dirPrefix`. 'Models/TopLevel.cs', @@ -483,9 +512,14 @@ describe('C# csproj leg — the answers only step 3 can give (#2902)', () => { ]); }); - it('keeps the FIRST-occurrence tie-break: a directory nested inside a same-named one loses', () => { - // `nest/Models/inner/Models/Ignored.cs` is absent: `indexOf('odels/')` finds - // the outer `Models/`, and `inner/Models/Ignored.cs` still has a slash. + it('a directory nested inside a same-named one now answers too (#2881)', () => { + // `nest/Models/inner/Models/Ignored.cs` used to be absent: `indexOf('odels/')` + // found the OUTER `Models/`, and `inner/Models/Ignored.cs` still had a + // slash. The predicate is now "the file's directory ends with the prefix", + // which the inner `Models` satisfies. Note this arm queries `App.odels` — + // the UNANCHORED half — so it also pins that removing the first-occurrence + // rule did not accidentally anchor the match to a segment boundary: + // `src/SubModels/Widget.cs` is still here. expect(withIndex([{ rootNamespace: 'App', projectDir: '' }], 'App.odels')).toEqual([ 'src/Models/User.cs', 'src/Models/Order.cs', @@ -493,6 +527,7 @@ describe('C# csproj leg — the answers only step 3 can give (#2902)', () => { 'other/Models/Thing.cs', 'vendor/mysrc/Models/Vendored.cs', 'src/Models/Late.cs', + 'nest/Models/inner/Models/Ignored.cs', 'Models/TopLevel.cs', 'win\\Models\\Win.cs', ]); @@ -506,15 +541,19 @@ describe('C# csproj leg — the answers only step 3 can give (#2902)', () => { it('a leading-slash dirPrefix cannot bogus-match a shorter directory', () => { // `dirPrefix = '/Models'` (projectDir used verbatim, since the import IS - // the root namespace): `'Models/'` is SHORTER than `'/Models/'`, and both - // `indexOf` and `haystack.length - needle.length` come out -1 without a - // length guard, so `Models/TopLevel.cs` would join the answer. + // the root namespace): `'Models/'` is SHORTER than `'/Models/'`, so + // `Models/TopLevel.cs` must not join the answer. The `indexOf` form needed + // an explicit length guard for this, because `indexOf` and + // `haystack.length - needle.length` both came out -1; `endsWith` is simply + // false on a shorter haystack, so the property now holds without one, and + // this case is what proves the guard's removal was safe. expect(withIndex([{ rootNamespace: 'App', projectDir: '/Models' }], 'App')).toEqual([ 'src/Models/User.cs', 'src/Models/Order.cs', 'other/Models/Thing.cs', 'vendor/mysrc/Models/Vendored.cs', 'src/Models/Late.cs', + 'nest/Models/inner/Models/Ignored.cs', 'win\\Models\\Win.cs', ]); }); @@ -618,3 +657,101 @@ describe('C# csproj leg — the directory index is built once per file set (#290 ); }); }); + +/** + * ABSOLUTE arms, deliberately not differential. + * + * The harness above is blind to everything in this block. Its frozen legacy copy + * carries the same `dirPrefix === '' ? indexOf : lastIndexOf` rule production + * does (see `directChildIdx`, and the header's note that #2881's edit landed in + * BOTH), so where #2881 moved step 2 the two sides moved together and the + * differential stays green by construction. Only stated expectations can see + * these, so each arm below names the exact line it gates. + */ +describe('C# csproj leg — where step 2 stops and step 3 begins (absolute)', () => { + function corpus(raw: readonly string[]): { paths: ReadonlySet; index: SuffixIndex } { + const all = [...raw]; + const normalized = all.map((f) => f.replace(/\\/g, '/')); + return { paths: new Set(all), index: buildSuffixIndex(normalized, all) }; + } + + const ROOT_NS_ONLY: CSharpProjectConfig[] = [{ rootNamespace: 'App', projectDir: '' }]; + + it("step 2's empty-`dirPrefix` filter rejects a doubled slash, which is NOT one directory deep", () => { + // Gates the five-line `if (dirPrefix === '')` guard in step 2 of + // `resolveCSharpImportInternal`. Delete it and this arm is the only thing in + // the suite that fails. + // + // `getDirMap` keys a file under every suffix of its DIRECTORY, so the empty + // key holds every path whose directory's last component is empty. That is a + // leading '/' on a root-level file (`/Root.cs`, directory ''), but ALSO a + // doubled slash immediately before the file name (`a//Doubled.cs`, directory + // 'a/'). Only the first is one directory deep — the query an empty + // `dirPrefix` is asking, and the one step 3 answers from `singleSegmentDirs` + // — so without the guard step 2 and step 3 disagree. + const { paths, index } = corpus([ + '/Root.cs', + 'a//Doubled.cs', + 'Top.cs', + 'one/Deep.cs', + 'a/b/Deeper.cs', + ]); + // Not vacuous: `a//Doubled.cs` really is in the bucket step 2 filters, so + // this arm fails by ADDING it rather than by finding nothing to reject. + expect(index.getFilesInDir('', '.cs')).toEqual(['/Root.cs', 'a//Doubled.cs']); + expect(resolveCSharpImportInternal('App', ROOT_NS_ONLY, paths, index)).toEqual(['/Root.cs']); + }); + + it('step 2 answering a query it used to miss also PREEMPTS step 3', () => { + // #2881 widened step 2 from "the FIRST `//`" to "the directory + // ENDS with `dirPrefix`". The justification reasons about step 2's own + // bucket and is right there — but step 2 returns as soon as it pushes + // anything, so a query it used to answer with nothing now also suppresses + // step 3, whose unanchored match set is a strict SUPERSET of step 2's. + // + // Pinned in both directions: step 2's answer with an index, and step 3's own + // answer with none. The gap between them is the suppression. + const { paths, index } = corpus([ + 'nest/src/SubModels/F0.cs', + 'SubModels/Models/F1.cs', + 'F2.cs', + 'SubModels/F3.cs', + ]); + // Step 2 alone: `SubModels/Models` is the only SEGMENT-aligned `Models`. + expect(resolveCSharpImportInternal('App.Models', ROOT_NS_ONLY, paths, index)).toEqual([ + 'SubModels/Models/F1.cs', + ]); + // Step 3 alone: every directory whose path merely ENDS with `Models`, which + // is the segment-aligned hit plus both `SubModels` character-suffix ones. + // Before #2881 step 2 rejected here and this was the answer; the widened + // step 2 now returns first, and the narrower, more precise answer above is + // the one that reaches the graph. + expect(resolveCSharpImportInternal('App.Models', ROOT_NS_ONLY, paths, undefined)).toEqual([ + 'nest/src/SubModels/F0.cs', + 'SubModels/Models/F1.cs', + 'SubModels/F3.cs', + ]); + }); + + it('a name that is not a suffix of the PARENT directory stays out of the bucket', () => { + // The negative control for the widened rule, matching the one Kotlin's + // parity test carries. The rule is "the file's parent directory ENDS with + // `dirPrefix`", not "`dirPrefix` appears anywhere in the path" — dropping + // the first-occurrence half must not widen it that far. Both positions the + // old `indexOf` distinguished are covered: leading, and mid-path. + // + // Asserted through both legs, because they run different predicates on + // different indexes and either one alone could widen without the other. + const { paths, index } = corpus([ + 'Models/sub/Leading.cs', + 'top/Models/mid/Middle.cs', + 'Models/Direct.cs', + ]); + expect(resolveCSharpImportInternal('App.Models', ROOT_NS_ONLY, paths, index)).toEqual([ + 'Models/Direct.cs', + ]); + expect(resolveCSharpImportInternal('App.Models', ROOT_NS_ONLY, paths, undefined)).toEqual([ + 'Models/Direct.cs', + ]); + }); +}); diff --git a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts new file mode 100644 index 000000000..2394a44d9 --- /dev/null +++ b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts @@ -0,0 +1,164 @@ +/** + * Coverage for `resolveGoPackage` (`import-resolvers/go.ts`), which had none. + * + * Go resolves package imports through two independent legs. The ScopeResolver + * leg (`languages/go/import-target.ts`) answers from `buildPackageDirIndex`; + * this one is the LanguageProvider leg, wired through `configs/go.ts`, and it + * is still a per-import scan. #2881 changed its membership rule — a directory + * whose name repeats higher in the path is now a member — and review found the + * change reached production with nothing watching it: `bench/import-target`'s + * go arm drives the indexed leg only, and no test called this function. + * + * These cases pin the rule and the two legs' agreement on it, so a revert fails + * here rather than silently moving Go IMPORTS edges in every repository that + * nests a package name inside itself (`internal/…/internal` is the shape Go + * actually produces). + * + * One caveat on "the LanguageProvider leg", recorded in #2929 review: nothing + * in production reads that field today. `configs/go.ts` reaches this function + * through `createImportResolver` → `LanguageProvider.importResolver`, and the + * only readers of `importResolver` are `import-target-adapter.ts:74-75`, whose + * two exports have no importer outside their own unit test. So the leg is wired + * but unreached, and this file is the only thing exercising it. + */ +import { describe, expect, it } from 'vitest'; +import { + resolveGoPackage, + resolveGoPackageDir, +} from '../../../src/core/ingestion/import-resolvers/go.js'; +import type { GoModuleConfig } from '../../../src/core/ingestion/language-config.js'; +import { resolveGoImportTarget } from '../../../src/core/ingestion/languages/go/import-target.js'; + +const MOD: GoModuleConfig = { modulePath: 'example.com/mod' }; + +function resolve(files: readonly string[], importPath: string): string[] { + const normalized = files.map((f) => f.replace(/\\/g, '/')); + return resolveGoPackage(importPath, MOD, normalized, files); +} + +/** The indexed leg, for the agreement arm. */ +function indexed(files: readonly string[], importPath: string): readonly string[] { + const got = resolveGoImportTarget(importPath, 'main.go', new Set(files), MOD); + // `typeof got === 'string'`, not `Array.isArray(got)`: `Array.isArray` narrows + // to `any[]`, which does not subsume `readonly string[]`, so the false branch + // kept the array member and `[got]` did not typecheck (TS2322 under + // `tsconfig.test.json`). Runtime behaviour is identical. + return got === null ? [] : typeof got === 'string' ? [got] : got; +} + +describe('resolveGoPackage', () => { + it('returns every .go file directly inside the package directory', () => { + const files = ['internal/auth/service.go', 'internal/auth/token.go', 'internal/auth/sub/x.go']; + expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ + 'internal/auth/service.go', + 'internal/auth/token.go', + ]); + }); + + it('a package directory nested inside a same-named one IS a member (#2881)', () => { + // The scan asked `indexOf` for the FIRST `/pkg/` and then required nothing + // after it to hold a slash, so this resolved to nothing. Both halves of the + // shape: the repeat leading the path, and the repeat mid-path. + expect(resolve(['pkg/src/go/pkg/repo.go'], 'example.com/mod/pkg')).toEqual([ + 'pkg/src/go/pkg/repo.go', + ]); + expect(resolve(['a/pkg/b/pkg/x.go'], 'example.com/mod/pkg')).toEqual(['a/pkg/b/pkg/x.go']); + expect(resolve(['svc/internal/sub/internal/x.go'], 'example.com/mod/internal')).toEqual([ + 'svc/internal/sub/internal/x.go', + ]); + }); + + it('a repeated name that is not the parent directory is still not a member', () => { + // The rule is "the parent directory ends with the package path", not + // "the package path appears anywhere". + expect(resolve(['a/pkg/b/x.go'], 'example.com/mod/pkg')).toEqual([]); + expect(resolve(['internal/auth/sub/x.go'], 'example.com/mod/internal/auth')).toEqual([]); + }); + + it('multi-segment package paths match on the whole run, not the last segment', () => { + const files = ['a/internal/models/b/internal/models/user.go', 'a/models/other.go']; + expect(resolve(files, 'example.com/mod/internal/models')).toEqual([ + 'a/internal/models/b/internal/models/user.go', + ]); + }); + + it('_test.go files are a different package and never match', () => { + expect( + resolve( + ['internal/auth/service.go', 'internal/auth/service_test.go'], + 'example.com/mod/internal/auth', + ), + ).toEqual(['internal/auth/service.go']); + }); + + it('non-.go files never match, and the RAW path is returned for backslashes', () => { + expect( + resolve(['internal/auth/README.md', 'internal/auth/x.go'], 'example.com/mod/internal/auth'), + ).toEqual(['internal/auth/x.go']); + expect(resolve(['internal\\auth\\x.go'], 'example.com/mod/internal/auth')).toEqual([ + 'internal\\auth\\x.go', + ]); + }); + + it('an import outside the module, or the module root itself, resolves to nothing here', () => { + expect(resolve(['internal/auth/x.go'], 'github.com/other/repo/internal/auth')).toEqual([]); + // The root package is the caller's `findRootPackageFiles` leg, not this one. + expect(resolve(['main.go'], 'example.com/mod')).toEqual([]); + expect(resolveGoPackageDir('example.com/mod', MOD)).toBeNull(); + expect(resolveGoPackageDir('example.com/mod/internal/auth', MOD)).toBe('/internal/auth/'); + }); + + it('vendor/, testdata/ and nested-module directories all merge in (unmodelled)', () => { + // Go excludes all three from a package: `vendor/` is a dependency tree + // resolved against the vendoring module, the go tool ignores `testdata/` + // entirely, and a directory carrying its own `go.mod` is a separate module + // whose packages this module's import paths never name. + // + // This resolver models NONE of that — it matches on the parent directory's + // path suffix alone. That is unchanged by #2881: the pre-#2881 rule + // (first `//`, nothing but a filename after it) accepted all three + // shapes too. These assertions record what the function actually does so + // the gap is visible and a change to it is deliberate; they document the + // behaviour rather than endorse it. + const files = [ + 'go.mod', + 'internal/auth/service.go', + 'vendor/example.com/dep/internal/auth/vendored.go', + 'testdata/internal/auth/fixture.go', + 'sub/go.mod', // `sub/` is its own module; its packages are not ours + 'sub/internal/auth/other_module.go', + ]; + expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ + 'internal/auth/service.go', + 'vendor/example.com/dep/internal/auth/vendored.go', + 'testdata/internal/auth/fixture.go', + 'sub/internal/auth/other_module.go', + ]); + // A `go.mod` beside the files changes nothing — it is not read here. + expect(resolve(['sub/go.mod', 'sub/pkg/x.go'], 'example.com/mod/pkg')).toEqual([ + 'sub/pkg/x.go', + ]); + }); + + it('agrees with the indexed leg on the repeated-name shapes', () => { + // The two legs are independent implementations of one rule. Before #2881 + // they agreed on the wrong answer; they must agree on the right one, or + // Go's LanguageProvider and ScopeResolver hooks disagree about which files + // a package holds. + for (const files of [ + ['pkg/src/go/pkg/repo.go'], + ['a/pkg/b/pkg/x.go'], + ['a/pkg/b/x.go'], + ['internal/auth/service.go', 'internal/auth/token.go'], + ['a/internal/models/b/internal/models/user.go'], + ]) { + for (const target of [ + 'example.com/mod/pkg', + 'example.com/mod/internal/auth', + 'example.com/mod/internal/models', + ]) { + expect(resolve(files, target)).toEqual([...indexed(files, target)]); + } + } + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts index d729ca314..311ca8aa2 100644 --- a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts @@ -10,19 +10,26 @@ * through anything the type system or the existing tests can see: * * - Go sorts the root-package leg and does NOT sort the package-dir leg; - * - Go and C# both take the FIRST occurrence of `//` in the path, so - * a directory nested inside a same-named directory does not match; + * - Go and C# answer when the file's PARENT directory ends with the queried + * segment. Both took the FIRST occurrence of `//` until #2881, so a + * directory nested inside a same-named one did not match; * - C#'s `resolveDirectMatch` lets a whole-path match win over a suffix match * found EARLIER in iteration order, while `resolveByProgressiveStripping` * takes whichever comes first; * - Dart tries `lib/` fully before bare ``, and compares raw paths * (no backslash normalization) on both legs. * - * So this file keeps verbatim copies of the pre-change implementations and - * asserts the new ones agree with them on a deterministic corpus built to force - * exactly those cases. The copies are the specification; if a future change - * makes one of these fail, the resolver's OUTPUT moved and the graph's edges - * move with it. + * So this file keeps copies of the pre-change implementations and asserts the + * new ones agree with them on a deterministic corpus built to force exactly + * those cases. The copies are the specification; if a future change makes one of + * these fail, the resolver's OUTPUT moved and the graph's edges move with it. + * + * They were verbatim until #2881, which deliberately changed one rule and so had + * to edit them too. Read them now as an independent re-derivation of the CURRENT + * spec, not as a frozen record of what shipped before the hoist — a weaker claim, + * and the reason the hand-built arm below pins ABSOLUTE expectations as well as + * differential ones: a differential where both sides were edited together proves + * only self-consistency. * * The second half asserts the index is built once per file set rather than once * per import, by counting how often the Set is iterated. It is the DETERMINISTIC @@ -57,7 +64,7 @@ import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/csharp- import { DART_HERITAGE_PREFIX } from '../../../src/core/ingestion/languages/dart/interpret.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; -// ─── verbatim pre-change implementations ───────────────────────────────────── +// ─── pre-change implementations, minus the rule #2881 removed ──────────────── function legacyFindRootPackageFiles(allFilePaths: ReadonlySet): string[] { const result: string[] = []; @@ -77,7 +84,10 @@ function legacyFindAllFilesInPkgDir(allFilePaths: ReadonlySet, pkgPath: const normalized = '/' + raw.replace(/\\/g, '/'); if (!normalized.includes(pkgDir)) continue; if (!normalized.endsWith('.go') || normalized.endsWith('_test.go')) continue; - const afterPkg = normalized.substring(normalized.indexOf(pkgDir) + pkgDir.length); + // `lastIndexOf` since #2881: `pkgDir` is '/'-anchored on both sides, so the + // LAST occurrence is the file's own parent. `indexOf` asked for the first, + // which made `a/pkg/b/pkg/x.go` not a member of `pkg`. + const afterPkg = normalized.substring(normalized.lastIndexOf(pkgDir) + pkgDir.length); if (!afterPkg.includes('/')) result.push(raw); } return result; @@ -203,17 +213,19 @@ function legacyFindDirectChild( allFilePaths: ReadonlySet, dirSegment: string, ): string | null { - const dirPrefix = `${dirSegment}/`; - const nestedDirPrefix = `/${dirPrefix}`; + // Since #2881 this is plain "the file's parent directory ends with + // `dirSegment`". The `atRoot`-then-`indexOf` pair it replaces expressed the + // same thing PLUS "…and that occurrence is the first", which is the half that + // was removed; the segment anchoring the leading '/' provided is kept by + // testing `'/' + dir + '/'` against `'/' + dirSegment + '/'`. + const needle = `/${dirSegment}/`; for (const raw of allFilePaths) { const f = raw.replace(/\\/g, '/'); if (!f.endsWith('.cs')) continue; - const atRoot = f.startsWith(dirPrefix); - const atNested = f.includes(nestedDirPrefix); - if (!atRoot && !atNested) continue; - const idx = atRoot ? 0 : f.indexOf(nestedDirPrefix) + 1; - const after = f.slice(idx + dirPrefix.length); - if (after.length > 0 && !after.includes('/')) return raw; + const lastSlash = f.lastIndexOf('/'); + if (lastSlash < 0) continue; + if (!`/${f.slice(0, lastSlash)}/`.endsWith(needle)) continue; + return raw; } return null; } @@ -298,11 +310,17 @@ function mix(n: number): number { } /** - * Directory shapes, chosen so the corpus contains every case where the naive - * "does the dir end with the segment" rewrite diverges from the original - * first-`indexOf` predicate: a directory name nested inside itself + * Directory shapes, chosen so the corpus contains every case where the two + * candidate predicates disagree: a directory name nested inside itself * (`pkg/pkg`, `a/pkg/b/pkg`), the same leaf under several parents (collision * tie-breaks), an absolute-rooted layout, and the repo root. + * + * The nested shapes were originally here to prove the "does the dir end with + * the segment" rewrite was NOT safe, because the shipped predicate additionally + * required the first `indexOf` occurrence. #2881 removed that requirement and + * made the ends-with form the shipped one, so these shapes now pin the removal + * instead — same shapes, opposite verdict, and still the only ones that can + * tell the two apart. */ const DIRS = [ '', @@ -526,7 +544,7 @@ describe('import-target index hoist — output parity with the pre-change scans' }, { lang: 'csharp', - why: 'a namespace dir nested inside itself does not answer the query', + why: 'a namespace dir nested inside itself DOES answer the query (#2881)', files: ['Models/Models/User.cs'], target: 'Models', }, @@ -570,15 +588,17 @@ describe('import-target index hoist — output parity with the pre-change scans' }, { lang: 'go', - why: 'a package dir nested inside itself does not answer the query', + why: 'a package dir nested inside itself DOES answer the query (#2881)', files: ['a/pkg/b/pkg/x.go'], // Addressed through the MODULE leg as the single segment `pkg`, not as - // `a/pkg`. `a/pkg` never reached the first-occurrence branch this case is - // named for: `'/a/pkg/b/pkg/'.endsWith('/a/pkg/')` is already false, so - // the naive `endsWith` rewrite agreed with the real predicate and the - // case passed either way. With `pkg`, `endsWith('/pkg/')` is TRUE and only - // the "…and that occurrence is the FIRST" half rejects it. The module leg - // is required because the GOPATH cascade skips single-segment targets. + // `a/pkg`. `a/pkg` never reached the first-occurrence branch this case + // was named for: `'/a/pkg/b/pkg/'.endsWith('/a/pkg/')` is already false, + // so the `endsWith` form agreed with the old predicate and the case + // passed either way. With `pkg`, `endsWith('/pkg/')` is TRUE and ONLY the + // "…and that occurrence is the FIRST" half rejected it — which is exactly + // why this case is the one that flips, and why it is still the case that + // tells the two predicates apart. The module leg is required because the + // GOPATH cascade skips single-segment targets. target: 'example.com/mod/pkg', modulePath: 'example.com/mod', }, @@ -667,10 +687,11 @@ describe('import-target index hoist — output parity with the pre-change scans' it('every hand-built layout resolves to something (they pin a winner, not a null)', () => { // `toEqual(null) === toEqual(null)` would make the arm above pass for the - // wrong reason. Only the three "must NOT match" layouts may be null. + // wrong reason. Only the "must NOT match" layouts may be null. The two + // nested-inside-itself layouts left this set in #2881: they now resolve, so + // they are held to the same "pin a winner" bar as everything else, which is + // a stronger assertion than the null they used to carry. const mustBeNull = new Set([ - 'a namespace dir nested inside itself does not answer the query', - 'a package dir nested inside itself does not answer the query', '_test.go files are a different package and never match', 'paths are matched RAW — a backslash path is not normalized into a hit', ]); @@ -713,9 +734,14 @@ describe('import-target index hoist — output parity with the pre-change scans' if (csharp(t, cs) !== null) hits.csharp++; } } - // Measured on this corpus: go 364, dart 75, ruby 259, csharp 196. Ruby and + // Measured on this corpus: go 366, dart 75, ruby 259, csharp 220. Ruby and // C# gained 40 each from the `win\dir\thing.` targets — one per repo, - // which is also the floor those two arms now defend. + // which is also the floor those two arms now defend. #2881 moved go 364 -> + // 366 and csharp 196 -> 220, from the corpus's `pkg/pkg`, `a/pkg/b/pkg` and + // `Models/Models` directories: those now answer their own name. The floors + // are deliberately NOT raised to lock that in — they exist to catch an arm + // that stopped resolving at all, and a revert of #2881 is caught precisely + // by the differential arms above, which compare against the real resolver. expect(hits.go).toBeGreaterThan(300); expect(hits.dart).toBeGreaterThan(60); expect(hits.ruby).toBeGreaterThan(220); diff --git a/gitnexus/test/unit/scope-resolution/java-import-target-parity.test.ts b/gitnexus/test/unit/scope-resolution/java-import-target-parity.test.ts index 739f245d7..868993f07 100644 --- a/gitnexus/test/unit/scope-resolution/java-import-target-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/java-import-target-parity.test.ts @@ -17,13 +17,17 @@ * — while its directory child is collected and returned only after the scan * completes, so file/suffix beats directory child within one `skip` level * regardless of order; - * - the directory-child leg takes the FIRST `'/' + pathLike + '/'` occurrence, - * so `com/example/com/example/Deep.java` does NOT answer `com.example`; + * - the directory-child leg answers when the file's PARENT directory ends + * with `pathLike`, so `com/example/com/example/Deep.java` DOES answer + * `com.example`. It took the FIRST `'/' + pathLike + '/'` occurrence until + * #2881, which made a package whose name repeats higher in its own path + * unresolvable; * - a wildcard import drops its trailing `.*` before any of that runs; * - paths are compared normalized (`\` → `/`) but returned RAW. * - * So this file keeps a VERBATIM copy of the pre-change implementation — the - * `resolveJavaImportTarget` that shipped before #2908, scans and all — and + * So this file keeps a copy of the pre-change implementation — the + * `resolveJavaImportTarget` that shipped before #2908, scans and all, minus the + * one rule #2881 deliberately removed (see tie-break 3) — and * asserts the new one agrees with it, both on hand-built corpora built to force * exactly those cases and on a generated corpus replayed under three insertion * orders — order being the only channel most of these tie-breaks travel on. @@ -46,7 +50,7 @@ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; import { resolveJavaImportTarget } from '../../../src/core/ingestion/languages/java/import-target.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; -// ─── verbatim pre-change implementation ────────────────────────────────────── +// ─── pre-change implementation, minus the rule #2881 removed ───────────────── interface LegacyJavaResolveContext { readonly fromFile: string; @@ -81,8 +85,7 @@ function legacyResolveJavaImportTarget( let exactFile: string | null = null; let suffixFile: string | null = null; let directoryChild: string | null = null; - const dirPrefix = `${pathLike}/`; - const suffixDirPrefix = `/${dirPrefix}`; + const suffixDirPrefix = `/${pathLike}/`; for (const raw of ctx.allFilePaths) { const f = raw.replace(/\\/g, '/'); @@ -95,14 +98,13 @@ function legacyResolveJavaImportTarget( suffixFile = raw; } if (directoryChild === null) { - const atRoot = f.startsWith(dirPrefix); - const atNested = f.includes(suffixDirPrefix); - if (atRoot || atNested) { - const idx = atRoot ? 0 : f.indexOf(suffixDirPrefix) + 1; - const after = f.slice(idx + dirPrefix.length); - if (after.length > 0 && !after.includes('/')) { - directoryChild = raw; - } + // Since #2881: "the file's parent directory ends with `pathLike`". The + // `atRoot`/`indexOf` pair this replaces said that AND "…and that is the + // first occurrence". `>= 0`, not `> 0` — a repo-root file has `lastSlash` + // 0 for `/Top.java` shapes and the bare-wildcard case depends on it. + const lastSlash = f.lastIndexOf('/'); + if (lastSlash >= 0 && `/${f.slice(0, lastSlash)}/`.endsWith(suffixDirPrefix)) { + directoryChild = raw; } } } @@ -119,8 +121,7 @@ function legacyResolveJavaImportTarget( if (tail === '') continue; const tailFile = `${tail}.java`; const tailSuffix = `/${tailFile}`; - const tailDir = `${tail}/`; - const tailSuffixDir = `/${tailDir}`; + const tailSuffixDir = `/${tail}/`; let tailDirectChild: string | null = null; for (const raw of ctx.allFilePaths) { const f = raw.replace(/\\/g, '/'); @@ -128,12 +129,9 @@ function legacyResolveJavaImportTarget( if (f === tailFile) return raw; if (f.endsWith(tailSuffix)) return raw; if (tailDirectChild === null) { - const atRoot = f.startsWith(tailDir); - const atNested = f.includes(tailSuffixDir); - if (atRoot || atNested) { - const idx = atRoot ? 0 : f.indexOf(tailSuffixDir) + 1; - const after = f.slice(idx + tailDir.length); - if (after.length > 0 && !after.includes('/')) tailDirectChild = raw; + const lastSlash = f.lastIndexOf('/'); + if (lastSlash >= 0 && `/${f.slice(0, lastSlash)}/`.endsWith(tailSuffixDir)) { + tailDirectChild = raw; } } } @@ -222,13 +220,20 @@ const HAND_CASES: readonly Case[] = [ target: 'com.example.service.*', }, { - // Tie-break 5: the FIRST `/com/example/` occurrence leaves `com/example/ - // Deep.java` after it, which still contains a slash — so no match. - label: 'self-nested-directory-does-not-match-outer', + // Tie-break 5: the parent directory `com/example/com/example` ends with + // `com/example`, so it answers. Until #2881 the leg took the FIRST + // `/com/example/` occurrence, which leaves `com/example/Deep.java` after it + // — still containing a slash — and the import resolved to null. + label: 'self-nested-directory-answers-the-outer-package', files: ['com/example/com/example/Deep.java'], target: 'com.example', }, { + // Kept beside `self-nested-directory-answers-the-outer-package` even though + // both now resolve to the same file: this one addresses the FULL path and + // hits the exact-file/suffix tier, that one addresses the outer package and + // hits the directory-child tier. Before #2881 the pair separated a hit from + // a null; it now separates two tiers, which is why it is still two cases. label: 'self-nested-directory-matches-full-path', files: ['com/example/com/example/Deep.java'], target: 'com.example.com.example', @@ -347,6 +352,30 @@ const HAND_CASES: readonly Case[] = [ files: ['com/example/model/User.java'], target: 'java.util.List', }, + // ── negative control for the widening (#2881), matching Kotlin's ────────── + // Everything above pins the widened leg from the POSITIVE side: a file whose + // package directory repeats higher in its own path now answers. Nothing here + // pinned the other half — that dropping the first-occurrence rule did not + // widen "the parent directory ends with `pathLike`" into "`pathLike` appears + // somewhere in the path". These three are the same trio + // `kotlin-import-target-parity.test.ts` carries: the two positions the old + // `atRoot`/`indexOf` pair distinguished, plus the positive control that keeps + // the pair from passing by refusing everything. + { + label: 'not-the-parent-directory-stays-out-leading', + files: ['com/example/sub/Repo.java'], + target: 'com.example', + }, + { + label: 'not-the-parent-directory-stays-out-mid-path', + files: ['top/com/example/mid/Repo.java'], + target: 'com.example', + }, + { + label: 'the-parent-directory-itself-does-answer', + files: ['top/com/example/Repo.java'], + target: 'com.example', + }, ]; /** Absolute pre-change behaviour, so the differential cannot pass vacuously. */ @@ -358,7 +387,7 @@ const HAND_EXPECTED: readonly string[] = [ 'directory-child-order-follows-insertion => com/example/service/Alpha.java', 'wildcard-resolves-as-package-directory => com/example/service/Beta.java', 'wildcard-exact-file-beats-directory => com/example/service.java', - 'self-nested-directory-does-not-match-outer => null', + 'self-nested-directory-answers-the-outer-package => com/example/com/example/Deep.java', 'self-nested-directory-matches-full-path => com/example/com/example/Deep.java', 'stripping-suffix-beats-earlier-directory-child => y/models/Order.java', 'stripping-reaches-root-file => Order.java', @@ -384,6 +413,12 @@ const HAND_EXPECTED: readonly string[] = [ 'directory-named-like-a-java-file => null', 'jdk-import-strips-into-a-local-lookalike => src/main/java/util/List.java', 'jdk-import-with-no-lookalike-resolves-to-nothing => null', + // `com/example/sub` ends with `example/sub`, not with `com/example`, and the + // stripping loop's `example` level does not reach it either — so the file is + // in no bucket the query can name. + 'not-the-parent-directory-stays-out-leading => null', + 'not-the-parent-directory-stays-out-mid-path => null', + 'the-parent-directory-itself-does-answer => top/com/example/Repo.java', ]; // ─── generated corpus ──────────────────────────────────────────────────────── @@ -612,6 +647,55 @@ describe('Java import target — index hoist parity (#2908)', () => { ]); }); + it('pins WHICH of two competing package directories the first-child leg takes', () => { + // `firstFileDirectlyInPkgDir` commits to ONE file with no downstream + // filter, and #2881 widened the set it chooses from. Every widened-shape + // case in HAND_CASES uses a ONE-FILE corpus, so the widened bucket has a + // single member and the choice is not exercised anywhere — yet a different + // first child is the largest class of movement the change produced. + // + // Both files below are legitimate members of the widened `com/example` + // set: `com/example/legacy/com/example` ends with `com/example` (it is the + // self-nested shape #2881 admitted) and `src/main/java/com/example` ends + // with it too. Nothing in the resolver prefers one over the other. The + // tie-break is FILE-SET ITERATION ORDER — the insertion order of the Set + // the caller passes — so reversing the corpus reverses the answer. That is + // the property these assertions pin, and the one nothing else watches: + // membership is already pinned above, the WINNER was not. + const set = (files: readonly string[]): WorkspaceIndex => + ({ fromFile: FROM_FILE, allFilePaths: new Set(files) }) as WorkspaceIndex; + const nestedFirst = [ + 'com/example/legacy/com/example/Old.java', + 'src/main/java/com/example/App.java', + ]; + const conventionalFirst = [...nestedFirst].reverse(); + + expect(resolveJavaImportTarget(javaImport('com.example'), set(nestedFirst))).toBe( + 'com/example/legacy/com/example/Old.java', + ); + expect(resolveJavaImportTarget(javaImport('com.example'), set(conventionalFirst))).toBe( + 'src/main/java/com/example/App.java', + ); + // A wildcard drops its `.*` before any of that, so it lands on the same leg + // and moves with it. Spelled out because `com.example.*` is how real Java + // source reaches this tier. + expect(resolveJavaImportTarget(javaImport('com.example.*'), set(nestedFirst))).toBe( + 'com/example/legacy/com/example/Old.java', + ); + expect(resolveJavaImportTarget(javaImport('com.example.*'), set(conventionalFirst))).toBe( + 'src/main/java/com/example/App.java', + ); + // The pre-change copy agrees on both orders, which places the movement in + // #2881's removal of the first-occurrence rule rather than in #2908's + // index hoist: the hoist did not touch the tie-break, it inherited it. + expect(legacyResolveJavaImportTarget(javaImport('com.example'), set(nestedFirst))).toBe( + 'com/example/legacy/com/example/Old.java', + ); + expect(legacyResolveJavaImportTarget(javaImport('com.example'), set(conventionalFirst))).toBe( + 'src/main/java/com/example/App.java', + ); + }); + it('builds each index once per file set rather than once per import', () => { const files = new CountingSet(generatedFiles()); const ws = { fromFile: FROM_FILE, allFilePaths: files }; diff --git a/gitnexus/test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts b/gitnexus/test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts index 887d6ab8a..d4104c9d2 100644 --- a/gitnexus/test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/kotlin/kotlin-import-target-parity.test.ts @@ -8,6 +8,21 @@ * the tie-breaks the scans implemented implicitly through iteration order. * These cases pin those semantics, so an index regression fails CI instead of * silently moving resolved edges in every Kotlin repository. + * + * ONE rule is deliberately no longer parity: #2881 removed the scan's + * first-occurrence restriction on `dirChildren`, so a file whose package + * directory name repeats higher in its path is now a child of that package. + * The cases carrying it say so and name the issue. + * + * That removal has two consequences a widened-shape case built on a ONE-FILE + * corpus cannot express, and both are pinned at the bottom of this file: + * + * - a bucket with TWO members makes `children[0]` a CHOICE. The wildcard tier + * commits to it with no downstream filter, so widening the bucket moves + * which file an already-resolving `import data.*` binds to. + * - tier 3 sits in front of tier 4, so a bucket the removed guards used to + * leave empty no longer lets tier 4 run — which can turn a bound answer + * into a candidate list that does not carry the symbol. */ import { describe, it, expect } from 'vitest'; import { resolveKotlinImportTarget } from '../../../../src/core/ingestion/languages/kotlin/import-target.js'; @@ -107,28 +122,37 @@ describe('resolveKotlinImportTarget — index parity', () => { expect(resolve(['pkg/A.java', 'pkg/A.md'], 'pkg.A')).toBeNull(); }); - it('only the FIRST occurrence of a repeated directory name counts', () => { - // Deliberate parity with the scan: it tested `startsWith` first and then - // used `indexOf` — the first `/data/` here is not the parent directory, and - // it never looked for a second one. The file is therefore NOT a child of - // `data`, even though it sits directly inside one. - // - // NOTE this case exercises the `startsWith` half only: `data` is the - // LEADING segment, so the guard fires and the `indexOf` equality is never - // reached. The mid-path case below is what pins that half — without it, a - // resolver whose position check is relaxed to `indexOf(...) >= 0` passes - // this whole file. - expect(resolve(['data/src/main/kotlin/com/example/data/Repo.kt'], 'data.something')).toBeNull(); + it('a package name repeated as the LEADING segment still fans out (#2881)', () => { + // The scan tested `startsWith` before `indexOf`, so a path whose leading + // segment repeats the parent directory name was dropped from the `data` + // bucket entirely and `import data.something` resolved to null. The file is + // a direct child of a `data` directory, so it belongs in the bucket. + expect(resolve(['data/src/main/kotlin/com/example/data/Repo.kt'], 'data.something')).toEqual([ + 'data/src/main/kotlin/com/example/data/Repo.kt', + ]); + // The single-file tiers were never affected — `suffixByStem` carries no + // such guard — so this one resolved before the fix and still does. + expect(resolve(['data/src/main/kotlin/com/example/data/Repo.kt'], 'data.Repo')).toBe( + 'data/src/main/kotlin/com/example/data/Repo.kt', + ); }); - it('a repeated directory name below the root still only counts its first occurrence', () => { - // Neither `data` is leading, so `startsWith` does not fire and the result - // is decided by the `indexOf` position check alone. The first `/data/` is - // not the parent, so this is not a child of `data`. - expect(resolve(['top/data/mid/data/Repo.kt'], 'data.something')).toBeNull(); - expect(resolve(['a/c/b/c/File.kt'], 'c.X')).toBeNull(); - // Same shape, but the first occurrence IS the parent — this one resolves, - // so the case above cannot pass by simply never matching anything. + it('a package name repeated MID-PATH also fans out (#2881)', () => { + // Neither `data` is leading, so `startsWith` never fired here and the null + // came from the `indexOf` position check alone — a second, independent + // guard. Both are gone; without this case a fix that only drops + // `startsWith` passes the file above and still leaves this shape broken. + expect(resolve(['top/data/mid/data/Repo.kt'], 'data.something')).toEqual([ + 'top/data/mid/data/Repo.kt', + ]); + // `['a/c/b/c/File.kt'], 'c.X'` used to sit here too. It is the same shape + // with the segments renamed — four components, second and fourth equal, + // query the repeated name — so it could not fail while the case above + // passed. The bench corpus still carries it, where a second spelling of a + // shape costs nothing; a unit case that cannot distinguish two + // implementations is just a slower way to assert the first one. + // + // Unrepeated control: the parent is the only occurrence. expect(resolve(['top/data/Repo.kt'], 'data.something')).toEqual(['top/data/Repo.kt']); }); @@ -143,8 +167,15 @@ describe('resolveKotlinImportTarget — index parity', () => { expect(resolve(['win\\pkg\\A.kt'], 'pkg.someFunction')).toEqual(['win\\pkg\\A.kt']); }); - it('a path starting with the directory name is not a child of it unless direct', () => { + it('a name that is not the PARENT directory stays out of the bucket', () => { + // The rule is "the parent directory is named `s`", not "`s` appears + // anywhere in the path" — dropping the two guards must not widen it that + // far. Leading and mid-path, since those were the two positions the guards + // distinguished; the new implementation has no positional logic at all, so + // one case would do, and the second is kept only because it is the exact + // shape the widened cases above use with the last segment changed. expect(resolve(['data/sub/Repo.kt'], 'data.something')).toBeNull(); + expect(resolve(['top/data/mid/Repo.kt'], 'data.something')).toBeNull(); expect(resolve(['data/Repo.kt'], 'data.something')).toEqual(['data/Repo.kt']); }); @@ -163,4 +194,70 @@ describe('resolveKotlinImportTarget — index parity', () => { it('an unknown target resolves to null', () => { expect(resolve(['pkg/A.kt'], 'nowhere.Thing')).toBeNull(); }); + + it('two competing `data` directories: WHICH one the first-child tier picks (#2881)', () => { + // The gap every other widened-shape case above leaves open. Each of them + // uses a ONE-FILE corpus, so the widened bucket has exactly one member and + // `findKotlinDirectoryChild`'s `children[0]` has nothing to choose between. + // #2881 moved 149 of the census's 235 records to a DIFFERENT first child, + // and not one of those 149 is a shape any single-file case can express. + // + // Both files below are legitimate members of the widened `data` bucket: + // each is a direct child of a directory named `data`. Neither is "the right + // answer" — the resolver has no rule that prefers one, and the ONLY thing + // deciding it is FILE-SET ITERATION ORDER, i.e. the insertion order of the + // Set the caller hands in. That is what these assertions pin: not that the + // bucket contains both (the cases above already pin membership) but WHICH + // member wins, which is the property nothing else in the repo watches. + const files = ['top/data/mid/data/Wrong.kt', 'src/data/Correct.kt']; + const reversed = ['src/data/Correct.kt', 'top/data/mid/data/Wrong.kt']; + + // Tier 3, the member path: `data.helper` strips to `data`, misses the file + // tiers and fans the WHOLE bucket out. Order is preserved but nothing is + // dropped, so this path commits to nothing on its own — the finalize pass + // still gets to pick by `localDefs` (#1759). + expect(resolve(files, 'data.helper')).toEqual([ + 'top/data/mid/data/Wrong.kt', + 'src/data/Correct.kt', + ]); + expect(resolve(reversed, 'data.helper')).toEqual([ + 'src/data/Correct.kt', + 'top/data/mid/data/Wrong.kt', + ]); + + // Tier 1, the wildcard path: `data.*` strips to `data`, which IS the whole + // `pathLike`, so `findKotlinFile` answers with `children[0]` — one file, + // unfiltered, no later tier and no downstream narrowing. This is the leg + // where the widening changes a bound answer rather than adding a candidate, + // and it flips with insertion order alone. + expect(resolve(files, 'data.*')).toBe('top/data/mid/data/Wrong.kt'); + expect(resolve(reversed, 'data.*')).toBe('src/data/Correct.kt'); + }); + + it('tier 3 preempts tier 4: a widened bucket replaces a BOUND answer (#2881)', () => { + // The class the published `54 / 149 / 32` census has no bucket for, because + // that taxonomy is shape-preserving (null→resolved, wider array, different + // first child) and this one is not. `findKotlinPackageFiles` runs BEFORE + // `findByProgressivePrefixStrip`, so a bucket the removed guards used to + // leave empty returned null and let tier 4 run; a now-populated bucket + // stops tier 4 from running at all. + // + // Read the two assertions together. The answer here is no longer a bound + // file — it is a CANDIDATE LIST, and the only file in it does not carry + // `helper`. `common/helper.kt`, the file tier 4 used to bind, is not in the + // list at all: it is not a child of any `data` directory, so no widening of + // the bucket can ever reach it. A resolved answer became an unresolved one. + // The bench corpus contains ZERO instances of this class, which is why it + // ships ungated — `bench/kotlin-import-target`'s own generator at 4000 + // repositories hits it only 4-12 times per seed. This case is the gate. + expect( + resolve(['data/src/main/kotlin/com/example/data/Repo.kt', 'common/helper.kt'], 'data.helper'), + ).toEqual(['data/src/main/kotlin/com/example/data/Repo.kt']); + + // The control that makes the arm above a transition rather than a fact: + // drop the `data` directory and tier 3 has nothing, so tier 4 runs and + // binds the same import to the file that actually holds `helper`. This is + // what the first assertion returned before #2881. + expect(resolve(['common/helper.kt'], 'data.helper')).toBe('common/helper.kt'); + }); }); diff --git a/gitnexus/test/unit/scope-resolution/kotlin/kotlin-index-internals.test.ts b/gitnexus/test/unit/scope-resolution/kotlin/kotlin-index-internals.test.ts new file mode 100644 index 000000000..c4f985677 --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/kotlin/kotlin-index-internals.test.ts @@ -0,0 +1,210 @@ +/** + * Structural guard for the two `getKotlinFileIndex` optimizations added in + * #2881 — the per-directory key memo and the bucket compaction. + * + * ## What this file can and cannot see + * + * Read this before adding a case here, and before citing this file as coverage + * for either optimization. Both claims below were checked by re-running every + * arm in this file against a mutated COPY of the resolver: + * + * - **the key memo (`dirKeys`) is not observable.** Deleting it outright — + * cutting the component-suffix key list once per FILE, the way the code did + * before — leaves every arm here green. That is not a hole to be plugged: it + * is the optimization's safety argument restated, since the key list is a + * pure function of `dir` and interning it cannot change the key set, the key + * insertion order or any bucket's order. In particular + * `expect(first).toBe(second)` proves nothing about it — bucket identity + * across calls comes from the OUTER `perFileSet` memo on the Set's identity, + * a different cache, guarded in + * `test/integration/kotlin-import-index-reuse.test.ts`. What the arms below + * pin is the OUTPUT INVARIANT the memo has to preserve, and the one + * plausible way to get the memo wrong — keying it on the last directory + * segment instead of the whole `dir`, which hands `x/pkg`'s key list to + * `y/pkg` and merges them — fails three of them. So: a MIS-KEYED memo is + * caught here, a DELETED one is not. + * + * - **the compaction (`bucket.slice()`) is not observable either.** Deleting + * the slice and freezing the grown bucket in place leaves every arm green, + * `Object.isFrozen` included. A JS array's backing-store capacity has no + * reflective surface, so no assertion through any API can see the reclaimed + * slack. The only instrument that can is `heap_ceiling_bytes.kotlin` in + * `bench/import-target/baselines.json` — a CEILING, not a floor: compaction + * reclaims, so deleting it makes the retained reading GROW (measured + * +12.57%, 42 805 256 -> 48 184 784 B), which no floor could see. + * `Object.isFrozen` is still worth + * asserting for what it DOES catch: no freeze at all, and "compact, freeze + * the copy, forget to `set` it back" — which hands out the original, + * unfrozen bucket, and which fails the arm (verified). + * + * ## What the arms are for + * + * The index is module-private, so these assertions run through the resolver's + * observable surface and reconstruct what they need: + * + * - bucket CONTENTS and ORDER come from the fan-out tier, which hands out the + * bucket array itself; + * - the FIRST-CHILD tier reads `[0]` of that same array, so the two tiers + * agreeing is what makes the freeze load-bearing rather than decorative; + * - a second file in the same directory is what reaches the memo's hit path + * at all, which a single-file corpus never exercises. + * + * A key-order assertion is deliberately absent: `dirChildren` is only ever read + * by `.get(key)`, so Map key order has no consumer and pinning it would assert + * an implementation detail nothing depends on. + */ +import { describe, expect, it } from 'vitest'; +import type { ParsedImport } from 'gitnexus-shared'; +import { resolveKotlinImportTarget } from '../../../../src/core/ingestion/languages/kotlin/import-target.js'; + +/** + * Takes the file Set directly. It used to take `(files, targetRaw, set = new + * Set(files))`, which three call sites drove as `bucket([], 'pkg.fn', set)` — + * an empty first argument that reads as "no files" in the one place the corpus + * matters most. Callers now spell `new Set(...)`, which also makes it visible + * where a Set is REUSED across calls (the `perFileSet` cache hit) and where a + * fresh one is built. + */ +function bucket(files: ReadonlySet, targetRaw: string) { + const parsed = { kind: 'named', localName: 'X', importedName: 'X', targetRaw } as ParsedImport; + return resolveKotlinImportTarget(parsed, { fromFile: 'App.kt', allFilePaths: files } as never); +} + +describe('getKotlinFileIndex internals (#2881)', () => { + it('the memo hit path produces the same bucket as the miss path', () => { + // Every file after the first in `pkg/` takes the memo, so a divergence + // between the two paths shows up as a missing or reordered member. The + // per-file form and the memoized form must agree element for element. + const files = ['a/b/pkg/One.kt', 'a/b/pkg/Two.kt', 'a/b/pkg/Three.kt', 'a/b/pkg/Four.kts']; + const set = new Set(files); + expect(bucket(set, 'pkg.someTopLevelFun')).toEqual(files); + expect(bucket(set, 'b.pkg.someTopLevelFun')).toEqual(files); + expect(bucket(set, 'a.b.pkg.someTopLevelFun')).toEqual(files); + }); + + it('two directories sharing a component-suffix keep separate buckets', () => { + // The memo is keyed on the full `dir`. Keying it on the last segment — the + // one way this optimization can move an answer — would hand `x/pkg`'s key + // list to `y/pkg` and merge them. + const files = ['x/pkg/One.kt', 'y/pkg/Two.kt']; + const set = new Set(files); + expect(bucket(set, 'x.pkg.fn')).toEqual(['x/pkg/One.kt']); + expect(bucket(set, 'y.pkg.fn')).toEqual(['y/pkg/Two.kt']); + // `pkg` alone is a component-suffix of both, so it legitimately holds both, + // in file-set iteration order. + expect(bucket(set, 'pkg.fn')).toEqual(files); + }); + + it('a shorter key list cached first does not truncate a longer one', () => { + // The case above has two directories of EQUAL depth, so a mis-keyed memo + // merges two lists of the same length and only the bucket contents move. + // Here the first directory seen (`pkg`) contributes one key and the second + // (`a/pkg`) contributes two, so reusing the first's list by last segment + // loses the `a/pkg` key entirely — a lookup that resolves today returning + // null. Different failure, same mis-keying. + const set = new Set(['pkg/One.kt', 'a/pkg/Two.kt']); + expect(bucket(set, 'pkg.fn')).toEqual(['pkg/One.kt', 'a/pkg/Two.kt']); + expect(bucket(set, 'a.pkg.fn')).toEqual(['a/pkg/Two.kt']); + }); + + it('directories sharing a MULTI-segment suffix keep separate buckets', () => { + // `q/pkg` is a shared suffix of both directories and `pkg` is a shared + // suffix of that, so the two files collide on two keys and stay apart on a + // third. A memo keyed on anything shorter than the whole `dir` merges the + // third as well. + const set = new Set(['p/q/pkg/One.kt', 'r/q/pkg/Two.kt']); + expect(bucket(set, 'p.q.pkg.fn')).toEqual(['p/q/pkg/One.kt']); + expect(bucket(set, 'r.q.pkg.fn')).toEqual(['r/q/pkg/Two.kt']); + expect(bucket(set, 'q.pkg.fn')).toEqual(['p/q/pkg/One.kt', 'r/q/pkg/Two.kt']); + expect(bucket(set, 'pkg.fn')).toEqual(['p/q/pkg/One.kt', 'r/q/pkg/Two.kt']); + }); + + it('the bucket handed out is frozen and the same object every call', () => { + // What this pins is the FREEZE, not the compaction (see the header): the + // array the fan-out tier hands out must be the one stored in the index and + // must be immutable. The finalize pass normalizes with `Array.isArray(t) ? + // t : [t]`, whose `arg is any[]` predicate widens the true branch, so + // `tsc --strict` accepts a `.sort()` or `.push()` there — and a sort would + // permanently reorder the cached bucket and flip the first-child tier's + // answer for every later import in the run. Freezing makes that a loud + // TypeError. It also fails if the compacted copy is frozen but never + // written back, since the array handed out is then the original. + const set = new Set(['pkg/One.kt', 'pkg/Two.kt']); + const first = bucket(set, 'pkg.fn') as readonly string[]; + const second = bucket(set, 'pkg.fn') as readonly string[]; + expect(first).toBe(second); + expect(Object.isFrozen(first)).toBe(true); + expect(() => (first as string[]).push('pkg/Three.kt')).toThrow(TypeError); + }); + + it('the first-child tier reads position 0 of the SAME bucket the fan-out returns', () => { + // The reason the freeze above matters, made observable. `import pkg.*` + // strips to `pkg`, which is the whole `pathLike`, so it answers from + // `findKotlinDirectoryChild`'s `children[0]`; `import pkg.fn` strips to + // `pkg` and fans the bucket out. One array, two tiers — so any reordering + // of the fan-out array moves the wildcard's single answer with it. + const set = new Set(['pkg/One.kt', 'pkg/Two.kt']); + const fanOut = bucket(set, 'pkg.fn') as readonly string[]; + expect(fanOut).toEqual(['pkg/One.kt', 'pkg/Two.kt']); + expect(bucket(set, 'pkg.*')).toBe(fanOut[0]); + }); + + it('every key of one directory hands out its own frozen array', () => { + // The compaction loop walks EVERY key, and a file's directory contributes + // one key per component-suffix. Checking a single key would leave a loop + // that freezes only the first entry — or that interns one array across the + // keys, which would make a future in-place edit of one bucket visible + // through all of them — passing. + const set = new Set(['a/b/pkg/One.kt', 'a/b/pkg/Two.kt']); + const full = bucket(set, 'a.b.pkg.fn') as readonly string[]; + const mid = bucket(set, 'b.pkg.fn') as readonly string[]; + const leaf = bucket(set, 'pkg.fn') as readonly string[]; + expect(Object.isFrozen(full)).toBe(true); + expect(Object.isFrozen(mid)).toBe(true); + expect(Object.isFrozen(leaf)).toBe(true); + expect(full).not.toBe(mid); + expect(mid).not.toBe(leaf); + expect(full).toEqual(leaf); + }); + + it('a single-child bucket is frozen too, on the length === 1 skip path', () => { + // Compaction skips `slice()` for a bucket that never grew. That branch must + // still freeze, or exactly the packages with one file stay mutable. + const only = bucket(new Set(['solo/One.kt']), 'solo.fn') as readonly string[]; + expect(only).toEqual(['solo/One.kt']); + expect(Object.isFrozen(only)).toBe(true); + }); + + it('a package larger than V8 s first growth steps keeps every member in order', () => { + // Measured on this repo's Node (v22.18.0, x64, 8 bytes per element slot), + // by allocating 40 000 push-grown arrays per length and reading retained + // heap against the same arrays rebuilt at exact length: a bucket minted as + // `[raw]` and pushed into takes its backing store through + // + // capacity 1 -> 19 -> 46 -> 86 -> 146 + // growing at lengths 2, 20, 47, 87 + // + // so 40 files sits inside the 46-slot store with 6 slots — 48 bytes — of + // retained slack, which is what compaction reclaims. (The older `1 -> 17 -> + // 41` note in this comment described a capacity that never appears here and + // under-counted that slack by 6x. The arm is unaffected either way: 40 is + // past a growth step under both models. The exact steps are a V8 detail and + // may move with the Node floor — the assertion deliberately depends only on + // there BEING slack, not on how much.) + const files = Array.from({ length: 40 }, (_, i) => `big/Item${i}.kt`); + expect(bucket(new Set(files), 'big.fn')).toEqual(files); + }); + + it('the memo keys on the NORMALIZED directory while storing raw paths', () => { + // `dir` is now sliced from `stem` rather than from `norm`. Both are the + // backslash-normalized form and an extension holds no '/', so the last + // separator is the same character at the same index — but only the KEY is + // normalized; the memo must not leak that into the stored value, which + // stays the raw path the file set holds. + const set = new Set(['win\\pkg\\A.kt', 'win\\pkg\\B.kt']); + expect(bucket(set, 'win.pkg.fn')).toEqual(['win\\pkg\\A.kt', 'win\\pkg\\B.kt']); + // Same directory reached by its component-suffix, i.e. through the memo's + // second and later keys rather than the full-dir key. + expect(bucket(set, 'pkg.fn')).toEqual(['win\\pkg\\A.kt', 'win\\pkg\\B.kt']); + }); +});