Skip to content

perf(scoreboard): qualify edit-loop latency and memory after landed optimizations #12947

Open

Description

@EffortlessSteven

Current execution and correctness bar — 2026-11-07

The repeated-sample/tier instrument #13076 is merged at dc153734aeb3d6da13a707d9935e097eefc7eb2d; the older open-candidate status below is superseded. Instrument delivery is not acceptance of the runtime target.

Retained failing workload

Hosted report, run 42350776018 / job 128338233978, analyzer 6c1ce93d12ba33a0ecd44a413431cad0a5615af4, runner github-hosted-linux-x86_64-4cpu-amd-epyc-9v74-80-core-processor:

  • Fixed heavy consumer 8fbe8bd1598e0b11752c6c989aa54198a0510a2f: warm check p50 92.877 s, sample-max p95 93.040 s, sampled peak 1,586.387 MiB. These breach the configured 60 s / 1,536 MiB ratchets.
  • Cold pilot, a different command: 233.992 s / 1,476.523 MiB.
  • Edited-save LSP refresh: 49.517 s / 1,722.316 MiB.
  • Older, smaller consumer 7c64b9c8d0778cc7a6aeaab0deb0452d9e521663: warm check 11.258 s / 582.332 MiB, also above its 11 s ceiling.

The report is recovered from the complete hosted log; retained artifact ID is 13566817823. N=3 makes the reported p95 a sample maximum, not a stable population-tail estimate. The instrument samples direct-process VmHWM every 10 ms; it does not establish aggregate process-tree memory or CPU time. Different hosts/subjects prevent calling this a causal regression from the historical 31 s / 0.90 GB observation. The resource gate really fails; it is not solely an ineligible cross-host comparison.

Next implementation selection

  1. Preserve this fixed failing subject. Add attribution around fact read/decode/integrity, index/post-process, related-test/macro preparation, classification and output. Retain end-to-end wall, actual user/system CPU and correctly scoped peak memory alongside component results.
  2. Reconcile the existing cheap avoided-work carriers first: perf(lsp): opening a 6,000-line unsaved Rust buffer spends ~12s in analysis, and exit waits for it #11439's claimed lazy-binding-helper candidate, perf(seam-inventory): fold corpus hash into single-pass index build on proved misses (#8643) #13314 single-pass hash/index, and perf(stub): reuse complete content-bound file guidance inventory (#11358, carrier for #12008) #13542 guidance-cache carrier. No duplicate branches and no component-only speedup claim.
  3. Use the measured remaining cost to order perf(cache): warm file-fact load re-serializes every FileFacts to verify its digest; cache is 429 MB of pretty JSON for 1,043 files #9216 decode/integrity, perf(pilot): cold pilot peak is ~1.3 GB RSS; ~400 MB is run-scoped evidence-context state that grows during evidence_for_seams #9494 retained context, perf(cache): bound classified-seam cache loads across single and sharded entries #5124/fix(cache): bound classified related-test reference expansion #13535 bounded reconstruction and perf(check): warm check on a product-Rust diff in a macro-dense workspace costs ~90 CPU-s; needs per-probe incremental analysis #9784 semantic reuse. File-cache hits alone do not imply semantic work was avoided.

Discriminating acceptance

  • Retain exact analyzer/source-built or installed binary digest, consumer/base/diff, config/features/toolchain, runner, worker count, cache posture and command.
  • Measure cold check, cold pilot, unchanged warm check, production-edit warm, related-test-only edit warm and editor refresh separately. Retain raw samples, all terminal outcomes and declared sample count.
  • Compare each optimized result with independent cold recomputation on the same edited state, preserving normalized findings, complete counts, limitations, test reach and output detail.
  • A changed related-test assertion invalidates affected evidence. A stale-result mutant fails this check; a recompute-all mutant fails an avoided-work/selectivity check.
  • No timeout, refusal, omitted inventory, truncated evidence or zero-subject result can satisfy a complete-analysis speed bar. Do not drop failed samples from percentiles.
  • Meet and progressively tighten the existing ratchets through matched evidence; do not raise them, switch to the smaller pin, or shrink semantic scope to turn the board green.
  • Report original aspirational goals separately from enforced ratchets and accepted product promises.

This issue owns measured edit-loop performance; #12906 owns session residency/instrument semantics. #1693 remains the adoption objective and #2379/#2766 retain finite release authority. Broad architectural completion is not silently added to the 0.11 cut.


Earlier evidence and plan (retained; status corrections above govern)

Delivered ratchet, current candidate, and next edit-loop measurement — November 4, 2026

The original large-tier goals and later floating-head/cold-check/stage-timing/speedup acceptance below remain. The premise “no ceiling gates these rows” is historical for the covered rows.

Merged delivery, with measured scope preserved

  • #12958, merge 78f990504274fc63790ff3a7933f166265d1595b, supplies runner-independent ratchet ceilings. At main 547910773a24d2ab97eb812fff0e44ba31114e08, benchmarks/dx_scoreboard/scoreboards.toml gives the old ripr-swarm pin warm ceilings 11,000 ms / 720 MB and ripr-swarm-2026-10 ceilings 60,000 ms / 1,536 MB plus cold pilot 300,000 ms / 2,048 MB. They prevent covered regressions; they do not meet the original goals.
  • #12985, merge 94fbdc134d522250955571ac8dd3722a3c0db61c, parallelized selected whole-index scans and added diff-stage timings. Its retained same-workload report is warm 40.2→31.3 seconds with identical output; cold values were noisy. This is reported predecessor A/B evidence, not a current rerun or general 10-second pass.
  • #12999, merge 8e602579707eded4a3bfcde094320ac30d6a888f, extends same-run admission core state. Its quiet-box report is roughly 1.34→0.90 GB with identical output, and unchanged wall time around 32→31 seconds. Do not recast the memory result as a latency gain or a sealed per-probe cache.
  • #13076 remains the selected open repeated-sample/tier-budget candidate at head 7506368624884688c963fe73e76e7984b4aa61bb. Its author explicitly has not run real corpus samples. Finish its current source/proof/review/normal protected delivery before using its proposed --samples interface as landed evidence.

Next executable evidence after that instrument lands

Use the same pinned consumer diff, host, exact identified release-profile binary digest/version, toolchain, configuration and budgets. Record whether the binary is source-built or installed: source-built A/B proof establishes only performance on that measured artifact; an installed ordinary-use/adoption claim requires its separately identified installed artifact. Retain a cold check, unchanged warm repeat, one production-file edit and one related-test edit. Materialize each edited state from a retained clean state and keep the base/source mode fixed. The unchanged repeat alone cannot establish the normal edit cost. Use the current scoreboard command/help and producer latency receipts; do not substitute CI build time, whole pilot time, debug/release mixtures or a different main diff.

Record raw repeated sample series, completion/admission status, scoped nonzero subject count where required, phase spans, peak memory, cache regime and normalized semantic output digest. Compare each warm edited state against its independent cold same-state analysis. No parallel benchmark competing for the same target/cache/memory budget. Retain process cleanup.

Discriminating acceptance and dependencies

The handoff to #1693 is the measured ordinary edit-loop cost and its actual success/limitation state on this exact artifact. This does not turn a performance target, four-workload study or broad adoption into a new finite 0.11 release gate.


Measured on main (3,280 tracked .rs files), ripr check --base HEAD~1 for an 8-line diff: 59.6 s cold, 35.5 s warm, 1.3 GB peak RSS. Hosted nightly run 41750179854: ripr-swarm-2026-10 warm 49.8 s / 1,275 MB, cold pilot 269 s / 1,446 MB.

Neither ripr-swarm corpus row has ceilings, and the baseline never compares (runner class differs), so the speed board reports below_target without failing.

Goals for the large tier: warm check 10 s / 768 MB, cold pilot 60 s.

Step 1 (this issue's first PR): ratchet ceilings just above measured values on both ripr-swarm rows. Later: floating ripr-swarm-head row, cold-check metrics, per-stage timing, and the actual speedups, each lowering the ceilings.

Evidence: /mnt/project-files/audit/speed-memory-scoreboard-gap-2026-11-04.md (see also #9216).

Activity

  1. coderabbitai commented on Nov 4, 2026

    @coderabbitai
    🔗 Related PRs

    #9980 - perf(probes): count unchanged token runs once per line, not once per probe shape (#9895) [closed]
    #10085 - perf(lsp): cache the worktree-diff git origin across saves (#10083) [closed]
    #11320 - perf(analysis): shorter owner-pin lock hold, mask once per file, bounded rename key (#5361) [closed]
    #12008 - perf(stub): reuse complete content-bound file guidance inventory (#11358) [open]


    📝 Issue Planner

    Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.

    • Create Plan

    🧪 Issue enrichment is currently in open beta.

    You can configure auto-planning by selecting labels in the issue_enrichment configuration.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false

    💬 Have feedback or questions? Drop into our discord!

  2. added
    status/needs-work
    on Nov 4, 2026
  3. changed the title [-]perf(scoreboard): ripr check on ripr-swarm itself is 35-60 s / 1.3 GB and no speed row gates it[/-] [+]perf(scoreboard): qualify edit-loop latency and memory after landed optimizations[/+] on Nov 5, 2026
  4. added and removed
    status/needs-work
    on Nov 5, 2026
  5. 10 remaining items

  6. EffortlessSteven commented on Nov 9, 2026

    @EffortlessSteven
    MemberAuthor

    Implemented avoided-work candidate: borrowed snapshot-name matching

    Current source checked at main 28b102c01f03e750e5ea387778e881d1c1bb0786; rust_snapshot_files.rs blob 51454cccfd5652d4c5dcb0bb74013d74c3cf1f3f. No equivalent PR was found by exact-symbol/all-state snapshot-claim search. This is independent of #13542.

    SnapshotListing::holds_any invokes stem_names_snapshot for each potential snapshot name. The current predicate constructs format!("__{name}") for each non-exact comparison. The repair checks the borrowed suffix and its preceding __ separator. Matching, counter/settings handling, input limits, tracked-file filtering and unknown-listing decisions are unchanged.

    What was actually established

    • The 20,000-file/two-name complete negative lookup constructs 80,000 suffix Strings / 920,000 payload bytes on the old matcher and 0 / 0 after the repair. This counts formatted temporary construction, not allocator events or retained/RSS bytes.
    • Native exact-source component: old implementation fails only that work assertion (6 semantic controls pass); repaired implementation passes 7/7.
    • A separator-free suffix mutant passes the work assertion but fails three semantic tests. A 128-file truncation mutant passes it but fails the genuine last-file match. The speed result cannot be obtained by that scope reduction.
    • Preservation includes 26 literal expected decisions, 4,536 differential comparisons, UTF-8/empty/separator cases, and tracked/unknown behavior.
    • Five uninstrumented optimized samples of 100 lookups each: median 545,341→155,585 microseconds. Total process user CPU 2.734→0.775 seconds. The base ran before the candidate; this is a synthetic component comparison, not a randomized real-repo or installed-CLI study.
    • Direct-process VmHWM 3,248→3,228 KiB is effectively unchanged; no RSS improvement is claimed.

    Root reviewed all three changed paths, read the current caller and matching contract, verified the exact-source extraction/blob identities and reran the seven native controls. Source review is complete for this bounded delta; full-crate, golden, real-repo and hosted qualification are not established.

    The in-repository new tests preserve semantics. The separately retained native harness below supplies the red avoided-work assertion and microbenchmark; it is not silently claimed as an installed CI ratchet.

    Exact implementation

    Patch SHA256: ed2f59f339dff718bf3abf105e8a03e0d8275c4a0aec7a7cffe8e67d7898f434. Apply only this delta to a full repository after the usual current-claim/source check.

    Complete source patch
    diff --git a/changelog.d/12947-borrow-snapshot-name-suffixes.md b/changelog.d/12947-borrow-snapshot-name-suffixes.md
    new file mode 100644
    index 0000000..60bdcdb
    --- /dev/null
    +++ b/changelog.d/12947-borrow-snapshot-name-suffixes.md
    @@ -0,0 +1,4 @@
    +<!-- section: Changed -->
    +- Rust snapshot-file matching avoids building a temporary suffix string for
    +  each compared file name, preserving accepted names and missing-file decisions
    +  (#12947).
    diff --git a/crates/ripr/src/analysis/rust_snapshot_files/tests.rs b/crates/ripr/src/analysis/rust_snapshot_files/tests.rs
    index 4d097de..40b86ad 100644
    --- a/crates/ripr/src/analysis/rust_snapshot_files/tests.rs
    +++ b/crates/ripr/src/analysis/rust_snapshot_files/tests.rs
    @@ -388,3 +388,138 @@ fn a_bare_call_is_marked_bare_and_a_path_call_is_not() {
         assert_eq!(bare.map(|call| call.bare), Some(true));
         assert_eq!(path.map(|call| call.bare), Some(false));
     }
    +
    +#[test]
    +fn stem_matching_preserves_separator_and_utf8_boundaries() {
    +    let cases = [
    +        ("record", "record", true),
    +        ("crate__record", "record", true),
    +        ("crate_record", "record", false),
    +        ("myrecord", "record", false),
    +        ("crate___record", "record", true),
    +        ("crate__re__cord", "re__cord", true),
    +        ("crate__re__cord", "cord", true),
    +        ("crate__record-02@linux", "record", true),
    +        ("crate__record-2x", "record", false),
    +        ("crate__record-٢", "record", false),
    +        ("crate__record-", "record", false),
    +        ("crate__record-2-3", "record", false),
    +        ("crate__record-2-3", "record-2", true),
    +        ("crate__record@linux-2", "record", true),
    +        ("préfixe__记录-2@linux", "记录", true),
    +        ("préfixe__记录x", "记录", false),
    +        ("crate__e\u{301}", "e\u{301}", true),
    +        ("crate__é", "e\u{301}", false),
    +        ("anything", "", false),
    +        ("crate__", "", true),
    +        ("", "", true),
    +        ("__", "_", false),
    +        ("___", "_", true),
    +        ("record-0", "record", true),
    +        ("@linux", "", true),
    +        ("crate__record@first@second", "record", true),
    +    ];
    +    for (stem, name, expected) in cases {
    +        assert_eq!(
    +            stem_names_snapshot(stem, name),
    +            expected,
    +            "{stem:?}, {name:?}"
    +        );
    +    }
    +}
    +
    +#[test]
    +fn stem_matching_agrees_with_literal_suffix_reading() {
    +    // Keep the previous allocation-based predicate as a differential oracle;
    +    // the literal cases above separately pin the naming contract.
    +    let names = [
    +        "",
    +        "_",
    +        "__",
    +        "record",
    +        "test_record",
    +        "a__b",
    +        "a-b",
    +        "记录",
    +        "e\u{301}",
    +    ];
    +    let prefixes = [
    +        "",
    +        "_",
    +        "__",
    +        "crate__",
    +        "crate___",
    +        "crate__tests__",
    +        "préfixe__",
    +    ];
    +    let suffixes = ["", "-0", "-01", "-2-3", "-x", "-٢", "@linux", "-2@linux"];
    +
    +    for name in names {
    +        for prefix in prefixes {
    +            for suffix in suffixes {
    +                let stem = format!("{prefix}{name}{suffix}");
    +                let core = stem.split('@').next().unwrap_or(&stem);
    +                let counted = core
    +                    .rsplit_once('-')
    +                    .filter(|(_, digits)| {
    +                        !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
    +                    })
    +                    .map(|(rest, _)| rest);
    +                for query in names {
    +                    let expected = [Some(core), counted]
    +                        .into_iter()
    +                        .flatten()
    +                        .any(|part| part == query || part.ends_with(&format!("__{query}")));
    +                    assert_eq!(
    +                        stem_names_snapshot(&stem, query),
    +                        expected,
    +                        "{stem:?}, {query:?}"
    +                    );
    +                }
    +            }
    +        }
    +    }
    +}
    +
    +#[test]
    +fn listing_search_keeps_late_tracked_matches_at_the_limit() -> Result<(), String> {
    +    let names = ["test_record".to_string(), "record".to_string()];
    +    let mut listing = SnapshotListing {
    +        files: (0..LISTING_LIMIT)
    +            .map(|i| ListedSnapshot {
    +                path: format!("snapshots/crate__unrelated_{i}-2.snap"),
    +                tracked: Some(true),
    +            })
    +            .collect(),
    +        unknown: false,
    +    };
    +    assert!(listing.certainly_lacks(&names));
    +    let last = listing.files.last_mut().ok_or("listing must be nonempty")?;
    +    last.path = "snapshots/crate__record-2@linux.snap".to_string();
    +    last.tracked = Some(false);
    +    assert!(
    +        listing.certainly_lacks(&names),
    +        "untracked files lend no credit"
    +    );
    +    listing
    +        .files
    +        .last_mut()
    +        .ok_or("listing must be nonempty")?
    +        .tracked = Some(true);
    +    assert!(
    +        listing.holds_any(&names),
    +        "do not cut the search before the last file"
    +    );
    +    assert!(!listing.certainly_lacks(&names));
    +    listing
    +        .files
    +        .last_mut()
    +        .ok_or("listing must be nonempty")?
    +        .tracked = Some(false);
    +    listing.unknown = true;
    +    assert!(
    +        !listing.certainly_lacks(&names),
    +        "partial listings cannot establish absence"
    +    );
    +    Ok(())
    +}
    diff --git a/crates/ripr/src/analysis/rust_snapshot_files.rs b/crates/ripr/src/analysis/rust_snapshot_files.rs
    index 51454cc..f9888fb 100644
    --- a/crates/ripr/src/analysis/rust_snapshot_files.rs
    +++ b/crates/ripr/src/analysis/rust_snapshot_files.rs
    @@ -196,10 +196,15 @@ fn stem_names_snapshot(stem: &str, name: &str) -> bool {
             .rsplit_once('-')
             .filter(|(_, digits)| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
             .map(|(rest, _)| rest);
    -    [Some(core), counted]
    -        .into_iter()
    -        .flatten()
    -        .any(|core| core == name || core.ends_with(&format!("__{name}")))
    +    [Some(core), counted].into_iter().flatten().any(|core| {
    +        // A listing can compare every file with every expected name. Check
    +        // the separator in the borrowed prefix instead of allocating the
    +        // same `__<name>` suffix for each comparison.
    +        core == name
    +            || core
    +                .strip_suffix(name)
    +                .is_some_and(|prefix| prefix.ends_with("__"))
    +    })
     }
     
     /// One analysis run's listing of the workspace's `.snap` files, read on first
    Native raw samples and passing component result
    sample=0 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=499474
    sample=1 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=638889
    sample=2 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=505821
    sample=3 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=564064
    sample=4 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=545341
    process_peak=VmHWM:	    3248 kB
    wall_s=2.762 user_s=2.734 system_s=0.014
    sample=0 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=161756
    sample=1 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=160984
    sample=2 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=155585
    sample=3 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=147701
    sample=4 lookups=100 listed_files=20000 names=2 absent=100 elapsed_us=141640
    process_peak=VmHWM:	    3228 kB
    wall_s=0.777 user_s=0.775 system_s=0.000
    
    running 7 tests
    test production::tests::an_unknown_listing_never_says_a_snapshot_is_missing ... ok
    test production::tests::an_untracked_snapshot_is_not_one_ci_sees ... ok
    test production::tests::listed_snapshot_matching_does_not_format_suffix_temporaries ... listed_files=20000 names=2 formatted_suffix_temporaries=0 formatted_suffix_payload_bytes=0
    ok
    test production::tests::listing_search_keeps_late_tracked_matches_at_the_limit ... ok
    test production::tests::stem_matching_agrees_with_literal_suffix_reading ... ok
    test production::tests::stem_matching_is_lenient_about_prefix_counter_and_suffix ... ok
    test production::tests::stem_matching_preserves_separator_and_utf8_boundaries ... ok
    
    test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s
    
    Reproducible native component harness

    Rust 1.95.0 on Linux x86_64. This contains seven verbatim production items and six actual repository tests plus the counter control. Use rustc --edition=2024 --test --cfg instrument_format -C debuginfo=0, then run serially (--test-threads=1 --nocapture); the counters are shared. For timing use rustc --edition=2024 -C opt-level=3 -C debuginfo=0 without --cfg instrument_format. To reconstruct the old-work control replace only the matcher with the exact original body from the bound source; the semantic tests remain unchanged.

    #![forbid(unsafe_code)]
    
    use std::sync::atomic::{AtomicU64, Ordering};
    static FORMAT_CALLS: AtomicU64 = AtomicU64::new(0);
    static FORMATTED_BYTES: AtomicU64 = AtomicU64::new(0);
    
    mod production {
        #[cfg(instrument_format)]
        macro_rules! format {
            ($($arguments:tt)*) => {{
                let text = std::format!($($arguments)*);
                crate::FORMAT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                crate::FORMATTED_BYTES.fetch_add(text.len() as u64, std::sync::atomic::Ordering::Relaxed);
                text
            }};
        }
    
    #[derive(Debug, PartialEq, Eq)]
    struct ListedSnapshot {
        /// Root-relative, `/`-separated.
        path: String,
        /// `Some(false)` when the repository lists its tracked snapshots and this
        /// one is not among them; `None` when the repository cannot say.
        tracked: Option<bool>,
    }
    
    #[derive(Debug, PartialEq, Eq)]
    pub(crate) struct SnapshotListing {
        files: Vec<ListedSnapshot>,
        /// Incomplete walk (size limit, an unreadable directory or a non-UTF-8 name), or a committed-history overlay that disagrees with the
        /// working tree about a snapshot input: the listing cannot say a file is
        /// absent.
        unknown: bool,
    }
    
    const LISTING_LIMIT: usize = 20_000;
    
    impl SnapshotListing {
        pub(crate) fn identity(&self) -> String {
            let mut text = format!("unknown={}\n", self.unknown);
            for file in &self.files {
                let tracked = match file.tracked {
                    Some(true) => "tracked",
                    Some(false) => "untracked",
                    None => "unlisted",
                };
                text.push_str(&file.path);
                text.push('\0');
                text.push_str(tracked);
                text.push('\n');
            }
            text
        }
        fn certainly_lacks(&self, names: &[String]) -> bool {
            !self.unknown && !self.holds_any(names)
        }
        fn holds_any(&self, names: &[String]) -> bool {
            self.files
                .iter()
                .filter(|file| file.tracked != Some(false))
                .filter_map(|file| file.path.rsplit('/').next())
                .filter_map(|name| name.strip_suffix(".snap"))
                .any(|stem| names.iter().any(|name| stem_names_snapshot(stem, name)))
        }
    }
    
    fn stem_names_snapshot(stem: &str, name: &str) -> bool {
        let core = stem.split('@').next().unwrap_or(stem);
        let counted = core
            .rsplit_once('-')
            .filter(|(_, digits)| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
            .map(|(rest, _)| rest);
        [Some(core), counted].into_iter().flatten().any(|core| {
            // A listing can compare every file with every expected name. Check
            // the separator in the borrowed prefix instead of allocating the
            // same `__<name>` suffix for each comparison.
            core == name
                || core
                    .strip_suffix(name)
                    .is_some_and(|prefix| prefix.ends_with("__"))
        })
    }
    
    
        fn large_listing() -> SnapshotListing {
            SnapshotListing {
                files: (0..LISTING_LIMIT).map(|i| ListedSnapshot {
                    path: std::format!("snapshots/crate__unrelated_{i}-2.snap"),
                    tracked: Some(true),
                }).collect(),
                unknown: false,
            }
        }
    
        pub(super) fn benchmark() {
            let listing = large_listing();
            let names = ["test_missing".to_string(), "missing".to_string()];
            for sample in 0..5 {
                let start = std::time::Instant::now();
                let mut absent = 0;
                for _ in 0..100 {
                    absent += std::hint::black_box(&listing).certainly_lacks(std::hint::black_box(&names)) as usize;
                }
                assert_eq!(absent, 100);
                std::println!("sample={sample} lookups=100 listed_files=20000 names=2 absent={absent} elapsed_us={}", start.elapsed().as_micros());
            }
        }
    
        #[cfg(test)]
        mod tests {
            use super::*;
    
    #[test]
    fn stem_matching_is_lenient_about_prefix_counter_and_suffix() {
        for stem in [
            "record",
            "krate__tests__record",
            "krate__tests__record-2",
            "krate__tests__record@linux",
            "krate__tests__record-3@linux",
        ] {
            assert!(stem_names_snapshot(stem, "record"), "{stem}");
        }
        for stem in [
            "krate__tests__other",
            "krate__tests__my_record",
            "records",
            "krate__recordx",
        ] {
            assert!(!stem_names_snapshot(stem, "record"), "{stem}");
        }
    }
    
    #[test]
    fn an_untracked_snapshot_is_not_one_ci_sees() -> Result<(), String> {
        let listing = SnapshotListing {
            files: vec![ListedSnapshot {
                path: "src/snapshots/krate__tests__record.snap".to_string(),
                tracked: Some(false),
            }],
            unknown: false,
        };
        assert!(!listing.holds_any(&["record".to_string()]));
        let unlisted = SnapshotListing {
            files: vec![ListedSnapshot {
                path: "src/snapshots/krate__tests__record.snap".to_string(),
                tracked: None,
            }],
            unknown: false,
        };
        assert!(unlisted.holds_any(&["record".to_string()]));
        assert_ne!(listing.identity(), unlisted.identity());
        Ok(())
    }
    
    #[test]
    fn an_unknown_listing_never_says_a_snapshot_is_missing() {
        let names = ["record".to_string()];
        let complete = SnapshotListing {
            files: Vec::new(),
            unknown: false,
        };
        let unknown = SnapshotListing {
            files: Vec::new(),
            unknown: true,
        };
        assert!(complete.certainly_lacks(&names));
        assert!(!unknown.certainly_lacks(&names));
        assert_ne!(complete.identity(), unknown.identity());
    }
    
    #[test]
    fn stem_matching_preserves_separator_and_utf8_boundaries() {
        let cases = [
            ("record", "record", true),
            ("crate__record", "record", true),
            ("crate_record", "record", false),
            ("myrecord", "record", false),
            ("crate___record", "record", true),
            ("crate__re__cord", "re__cord", true),
            ("crate__re__cord", "cord", true),
            ("crate__record-02@linux", "record", true),
            ("crate__record-2x", "record", false),
            ("crate__record-٢", "record", false),
            ("crate__record-", "record", false),
            ("crate__record-2-3", "record", false),
            ("crate__record-2-3", "record-2", true),
            ("crate__record@linux-2", "record", true),
            ("préfixe__记录-2@linux", "记录", true),
            ("préfixe__记录x", "记录", false),
            ("crate__e\u{301}", "e\u{301}", true),
            ("crate__é", "e\u{301}", false),
            ("anything", "", false),
            ("crate__", "", true),
            ("", "", true),
            ("__", "_", false),
            ("___", "_", true),
            ("record-0", "record", true),
            ("@linux", "", true),
            ("crate__record@first@second", "record", true),
        ];
        for (stem, name, expected) in cases {
            assert_eq!(
                stem_names_snapshot(stem, name),
                expected,
                "{stem:?}, {name:?}"
            );
        }
    }
    
    #[test]
    fn stem_matching_agrees_with_literal_suffix_reading() {
        // Keep the previous allocation-based predicate as a differential oracle;
        // the literal cases above separately pin the naming contract.
        let names = [
            "",
            "_",
            "__",
            "record",
            "test_record",
            "a__b",
            "a-b",
            "记录",
            "e\u{301}",
        ];
        let prefixes = [
            "",
            "_",
            "__",
            "crate__",
            "crate___",
            "crate__tests__",
            "préfixe__",
        ];
        let suffixes = ["", "-0", "-01", "-2-3", "-x", "-٢", "@linux", "-2@linux"];
    
        for name in names {
            for prefix in prefixes {
                for suffix in suffixes {
                    let stem = format!("{prefix}{name}{suffix}");
                    let core = stem.split('@').next().unwrap_or(&stem);
                    let counted = core
                        .rsplit_once('-')
                        .filter(|(_, digits)| {
                            !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
                        })
                        .map(|(rest, _)| rest);
                    for query in names {
                        let expected = [Some(core), counted]
                            .into_iter()
                            .flatten()
                            .any(|part| part == query || part.ends_with(&format!("__{query}")));
                        assert_eq!(
                            stem_names_snapshot(&stem, query),
                            expected,
                            "{stem:?}, {query:?}"
                        );
                    }
                }
            }
        }
    }
    
    #[test]
    fn listing_search_keeps_late_tracked_matches_at_the_limit() -> Result<(), String> {
        let names = ["test_record".to_string(), "record".to_string()];
        let mut listing = SnapshotListing {
            files: (0..LISTING_LIMIT)
                .map(|i| ListedSnapshot {
                    path: format!("snapshots/crate__unrelated_{i}-2.snap"),
                    tracked: Some(true),
                })
                .collect(),
            unknown: false,
        };
        assert!(listing.certainly_lacks(&names));
        let last = listing.files.last_mut().ok_or("listing must be nonempty")?;
        last.path = "snapshots/crate__record-2@linux.snap".to_string();
        last.tracked = Some(false);
        assert!(
            listing.certainly_lacks(&names),
            "untracked files lend no credit"
        );
        listing
            .files
            .last_mut()
            .ok_or("listing must be nonempty")?
            .tracked = Some(true);
        assert!(
            listing.holds_any(&names),
            "do not cut the search before the last file"
        );
        assert!(!listing.certainly_lacks(&names));
        listing
            .files
            .last_mut()
            .ok_or("listing must be nonempty")?
            .tracked = Some(false);
        listing.unknown = true;
        assert!(
            !listing.certainly_lacks(&names),
            "partial listings cannot establish absence"
        );
        Ok(())
    }
    
    
            #[test]
            fn listed_snapshot_matching_does_not_format_suffix_temporaries() {
                let listing = large_listing();
                let names = ["test_missing".to_string(), "missing".to_string()];
                crate::FORMAT_CALLS.store(0, crate::Ordering::Relaxed);
                crate::FORMATTED_BYTES.store(0, crate::Ordering::Relaxed);
                let absent = listing.certainly_lacks(&names);
                let calls = crate::FORMAT_CALLS.load(crate::Ordering::Relaxed);
                let bytes = crate::FORMATTED_BYTES.load(crate::Ordering::Relaxed);
                std::println!("listed_files=20000 names=2 formatted_suffix_temporaries={calls} formatted_suffix_payload_bytes={bytes}");
                assert!(absent);
                assert_eq!(calls, 0, "the actual matcher must not construct a formatted suffix for each comparison");
                assert_eq!(bytes, 0);
            }
        }
    }
    
    fn main() {
        production::benchmark();
        match std::fs::read_to_string("/proc/self/status") {
            Ok(status) => {
                for line in status.lines().filter(|line| line.starts_with("VmHWM:")) {
                    std::println!("process_peak={line}");
                }
            }
            Err(error) => std::println!("process_peak=unavailable: {error}"),
        }
    }

    Continuation

    This delta is implemented and retained here, not yet committed on a remote candidate or merged. Configured Git publication must preserve the requested EffortlessSteven author/noreply identity; the available connector lacks an author override. #13984 owns the separate current-main compiler repair. After publication, qualify the affected production path and then measure the fixed #12947 subject—do not substitute this microbenchmark for its wall/CPU/peak-memory acceptance, change its pin, or relax its ceilings. No new cache, schema, semantics, support tier or release action is included.

  7. EffortlessSteven commented on Nov 9, 2026

    @EffortlessSteven
    MemberAuthor

    Selected implementation: remove warm candidate-list copies and cold module-prefix strings

    This is one composed candidate for the existing #12947 performance owner, relevant to the #12940 workload. It does not close either issue or assert that the end-to-end budgets now pass.

    Delivery state: implemented and component-reviewed; exact patch and reproducible proof below. No remote branch commit or merge is claimed. This environment's GitHub commit tool cannot set the requested author identity, and an authenticated author-capable native transport is not configured. The local source-subset commits use EffortlessSteven 15812269+EffortlessSteven@users.noreply.github.com; do not push their incomplete source-subset tree as a repository tree.

    Candidate identity and reconciliation

    • Upstream source: 28b102c01f03e750e5ea387778e881d1c1bb0786, rechecked unchanged immediately before publication.
    • Exact base blobs: context 93263927427f59038c83a1d3d1c9fd9e81452beb; parent df51aa2895d644f6ffc4af623a05017c12bdb33e.
    • Composed source-subset candidate: 2a9c24f48359d67ee79c5883a503ea25a572f0b6.
    • Exact patch: 19,392 bytes, SHA-256 c8f60586e75317fa9de59c702ab78b3783b9a8c1ec004ab7d1ccc32860352586.
    • Five changed paths: context, its parent, a new pure predicate-test module, and two changelog fragments; +326/-16.
    • Final blobs: context f92ef654d5724552069452dbeb476f6d5a747a7e; parent b6938616b1c042990b5c8549d1e6577b185fc051; predicate tests cbf16508a381fa1ead0f36ad8b045004a2c8f8f6.
    • All-state symbol/claim searches found merged perf(rust): index owner-name and module test candidates (#3861) #4160 as the candidate-index owner, not an equivalent active repair. No new parallel tracker or branch is created.

    Apply this one composed delta, not its earlier standalone warm-copy or lazy-flattening intermediates on top.

    What changes

    1. The owner-name and same-module memos store Option<Arc<[usize]>>. Nonempty hits share immutable backing after releasing the lock; cached emptiness and empty keys do not allocate an empty Arc.
    2. Both consumers still visit every admitted index in order. Window clearing drops cache ownership while existing readers remain valid.
    3. Direct module matching uses borrowed prefix/boundary checks. The flattened fallback compares a checked UTF-8 prefix with only slash bytes mapped to underscores, without constructing a temporary String. Exact-parent, empty-parent, underscore-collision, Unicode, close-segment and crowded-filter semantics stay intact.

    There is no new scope cap, result truncation, cache retention policy, serialized format, cross-run reuse or cold-miss coalescing.

    Measured native component result

    Linux x86_64 / Rust 1.95.0, serial source-exact component tests. Fixture setup is outside thread-local-gated System-allocation counters. Counts include allocation/reallocation requests; bytes are requested bytes, not current or peak live memory.

    Same complete fixture Original source Composed candidate
    256 warm nonempty queries, 4,096 indices per result 256 requests / 8,388,608 bytes 0 / 0
    512 warm empty queries 0 / 0 0 / 0
    First empty-key queries 0 / 0 0 / 0
    Direct cold module query, all 4,096 ordered results 8,197 / 119,344 5 / 66,024
    Flattened cold module query, all 4,096 ordered results 16,389 / 156,204 5 / 66,020
    4,096 direct predicate pairs 8,192 / 53,248 0 / 0
    4,096 flattened predicate pairs 16,384 / 90,112 0 / 0

    Root independently compiled and ran the composed instrument: 18/18 pass. The original source compiled and ran the common controls: 10 pass, 6 intended assertion failures, not compiler failures. Those six detect warm copying/backing identity and cold per-row allocation. Candidate-only controls additionally compile the actual consumer loops and check Arc ownership release.

    The source checker verifies 11 exact candidate items, 8 exact baseline items, both cache-field declarations and both original Git blobs. The three pure predicate tests are included directly from the new repository file and run natively; they preserve semantics and intentionally also pass on the original source. They cover 52 literal pairs plus 924 differential pairs. Three additional parser-backed cache tests are added to the repository, but have not been typechecked/run in the full RIPR crate here.

    Root and a separate reviewer read both complete deltas; no actionable source findings remain. Changed-file formatting and whitespace checks pass.

    Acceptance still pending

    This component does not run parser construction, classification, the full evidence pass or installed CLI. Full-crate tests, Clippy, Windows, hosted required qualification, output parity and matched edit-loop replay remain pending. The original #12947 heavy subject and budgets remain unchanged. Allocation-request reductions do not establish lower whole-run RSS, provider tokens, CPU time or elapsed time.

    The duplicate owner_opt_outs test initializer was repaired separately by #13982, merged as 79ca845369eb8b5050310dec41ef241b33723b6a; #13984 was closed as a duplicate. Readback confirms the landing is a sole-parent child of the recorded source basis and changes only that one line in output/human.rs. None of this candidate's paths changed, so its patch/source identity remains applicable without a behind-only restack. No full build was launched against the earlier known failure; full repository qualification remains pending in this bounded source-subset environment. No protection was bypassed.

    Reproduce the bounded proof

    After applying the patch to a normal source checkout, save the two native component files from this comment and its original-source/negative-control companion under proof/; the checker uses upstream source by default:

    node proof/check-source-identity.mjs
    rustc --edition=2024 --test proof/candidate_component.rs -o proof/candidate-tests
    proof/candidate-tests --test-threads=1 --nocapture
    rustc --edition=2024 --test proof/baseline_component.rs -o proof/baseline-tests
    proof/baseline-tests --test-threads=1 --nocapture

    The baseline is expected to exit 101 at the six stated assertions. In the local source-subset packet only, pass fb78e348c457f182c89fb2c6e5fad5752f6d1cfe to the checker as the base argument; exact upstream blob checks still apply. This is not a substitute for repository-native qualification.

    Exact composed patch — 19,392 bytes
    diff --git a/changelog.d/12947-borrow-module-parent-prefixes.md b/changelog.d/12947-borrow-module-parent-prefixes.md
    new file mode 100644
    index 0000000000000000000000000000000000000000..05885999f27b3513440c10b328ecb3c2edf5f506
    --- /dev/null
    +++ b/changelog.d/12947-borrow-module-parent-prefixes.md
    @@ -0,0 +1,4 @@
    +<!-- section: Changed -->
    +- Rust related-test module matching checks direct and flattened parent-path
    +  boundaries with borrowed strings instead of allocating temporary prefixes
    +  per candidate, preserving related-test membership (#12947).
    diff --git a/changelog.d/shared-relation-candidate-indices.md b/changelog.d/shared-relation-candidate-indices.md
    new file mode 100644
    index 0000000000000000000000000000000000000000..ff8a9a855bc6779175df48e6282fa775645a29a2
    --- /dev/null
    +++ b/changelog.d/shared-relation-candidate-indices.md
    @@ -0,0 +1,5 @@
    +<!-- section: Changed -->
    +- Repeated owner-name and same-module candidate queries share immutable index
    +  lists instead of copying every index on a cache hit. Empty results remain
    +  allocation-free on hits; matching, ordering and evidence-window cache clearing
    +  are unchanged (#3861, #12940).
    diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs
    index df51aa2895d644f6ffc4af623a05017c12bdb33e..b6938616b1c042990b5c8549d1e6577b185fc051 100644
    --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs
    +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs
    @@ -8,6 +8,8 @@ use crate::analysis::facts::FunctionImplContext;
     use std::sync::Arc;
     
     pub(super) mod context;
    +#[cfg(test)]
    +mod module_match_tests;
     mod visibility;
     
     pub(crate) use context::CompactGripContext;
    @@ -588,7 +590,11 @@ pub(super) fn match_same_module(
         let Some(module_path) = owner.module_path.as_deref() else {
             return;
         };
    -    for test_index in context.same_module_indices(module_path) {
    +    for &test_index in context
    +        .same_module_indices(module_path)
    +        .as_deref()
    +        .unwrap_or_default()
    +    {
             insert_related_candidate(
                 candidates,
                 context,
    @@ -605,7 +611,11 @@ pub(super) fn match_owner_named_test(
         prefix: Option<&str>,
         owner: &OwnerContext<'_>,
     ) {
    -    for test_index in context.owner_named_indices(&owner.name_lower) {
    +    for &test_index in context
    +        .owner_named_indices(&owner.name_lower)
    +        .as_deref()
    +        .unwrap_or_default()
    +    {
             insert_related_candidate(
                 candidates,
                 context,
    @@ -972,6 +982,18 @@ pub(super) fn crowded_relation_limit(test_count: usize) -> usize {
         (test_count / 100).max(64)
     }
     
    +/// Match the slash-to-underscore parent spelling without allocating it.
    +fn flattened_module_rest<'a>(parent: &str, test_module: &'a str) -> Option<&'a str> {
    +    let prefix = test_module.get(..parent.len())?;
    +    let rest = test_module.get(parent.len()..)?.strip_prefix('/')?;
    +    prefix
    +        .bytes()
    +        .eq(parent
    +            .bytes()
    +            .map(|byte| if byte == b'/' { b'_' } else { byte }))
    +        .then_some(rest)
    +}
    +
     /// In a crowded parent module, keep only the tests that sit close to the
     /// owner: the parent itself, the owner's own module and its children, and a
     /// test-named sibling (`tests`, `*_tests`, `test_*`). Distant siblings such as
    @@ -983,15 +1005,10 @@ pub(super) fn close_module(owner_module: &str, test_module: &str) -> bool {
         if test_module == parent {
             return true;
         }
    -    let flattened = parent.replace('/', "_");
         let Some(rest) = test_module
             .strip_prefix(parent)
             .and_then(|rest| rest.strip_prefix('/'))
    -        .or_else(|| {
    -            test_module
    -                .strip_prefix(flattened.as_str())
    -                .and_then(|rest| rest.strip_prefix('/'))
    -        })
    +        .or_else(|| flattened_module_rest(parent, test_module))
         else {
             return false;
         };
    @@ -1016,8 +1033,10 @@ pub(super) fn same_module(owner_module: &str, test_module: &str) -> bool {
             return false;
         }
         test_module == parent
    -        || test_module.starts_with(&format!("{parent}/"))
    -        || test_module.starts_with(&format!("{}/", parent.replace('/', "_")))
    +        || test_module
    +            .strip_prefix(parent)
    +            .is_some_and(|rest| rest.starts_with('/'))
    +        || flattened_module_rest(parent, test_module).is_some()
     }
     
     /// Body mentions the owner via an explicit qualified-path or `use`
    diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs
    index 93263927427f59038c83a1d3d1c9fd9e81452beb..f92ef654d5724552069452dbeb476f6d5a747a7e 100644
    --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs
    +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs
    @@ -40,8 +40,11 @@ pub(crate) struct CompactGripContext<'a> {
         function_name_counts: BTreeMap<String, usize>,
         name_module_candidates: NameModuleCandidateIndex,
         inherent_helper_reach: Mutex<BTreeMap<(usize, String), bool>>,
    -    owner_named_cache: Mutex<BTreeMap<String, Vec<usize>>>,
    -    same_module_cache: Mutex<BTreeMap<String, Vec<usize>>>,
    +    // None is a cached empty result, without allocating an empty Arc. Nonempty
    +    // immutable results can be read after releasing the memo lock without
    +    // copying every candidate index for every seam.
    +    owner_named_cache: Mutex<BTreeMap<String, Option<Arc<[usize]>>>>,
    +    same_module_cache: Mutex<BTreeMap<String, Option<Arc<[usize]>>>>,
         pub(in crate::analysis::test_grip_evidence) source_digest_cache:
             Mutex<BTreeMap<&'a Path, String>>,
         /// Per test file: evidence-role function indices grouped by start line,
    @@ -851,9 +854,9 @@ impl<'a> CompactGripContext<'a> {
             names
         }
     
    -    pub(super) fn owner_named_indices(&self, owner_name_lower: &str) -> Vec<usize> {
    +    pub(super) fn owner_named_indices(&self, owner_name_lower: &str) -> Option<Arc<[usize]>> {
             if owner_name_lower.is_empty() {
    -            return Vec::new();
    +            return None;
             }
             if let Some(indices) = memo(&self.owner_named_cache).get(owner_name_lower) {
                 return indices.clone();
    @@ -864,13 +867,14 @@ impl<'a> CompactGripContext<'a> {
                 .into_iter()
                 .filter(|&index| self.tests[index].name_lower.contains(owner_name_lower))
                 .collect::<Vec<_>>();
    +        let indices: Option<Arc<[usize]>> = (!indices.is_empty()).then(|| Arc::from(indices));
             memo(&self.owner_named_cache).insert(owner_name_lower.to_string(), indices.clone());
             indices
         }
     
    -    pub(super) fn same_module_indices(&self, owner_module: &str) -> Vec<usize> {
    +    pub(super) fn same_module_indices(&self, owner_module: &str) -> Option<Arc<[usize]>> {
             if owner_module.is_empty() {
    -            return Vec::new();
    +            return None;
             }
             if let Some(indices) = memo(&self.same_module_cache).get(owner_module) {
                 return indices.clone();
    @@ -899,6 +903,7 @@ impl<'a> CompactGripContext<'a> {
             } else {
                 indices
             };
    +        let indices: Option<Arc<[usize]>> = (!indices.is_empty()).then(|| Arc::from(indices));
             memo(&self.same_module_cache).insert(owner_module.to_string(), indices.clone());
             indices
         }
    @@ -908,6 +913,153 @@ impl<'a> CompactGripContext<'a> {
     mod candidate_index_tests {
         use super::*;
     
    +    fn candidate_cache_index() -> Result<RustIndex, String> {
    +        use crate::analysis::rust_index::{RaRustSyntaxAdapter, RustSyntaxAdapter};
    +
    +        let mut owned = crate::analysis::facts::OwnedRustIndex::default();
    +        let mut files = Vec::new();
    +        for (file, name, count) in [
    +            ("src/a/tests.rs", "owner_near", 64),
    +            ("src/a/distant.rs", "owner_far", 65),
    +        ] {
    +            let path = PathBuf::from(file);
    +            let source = (0..count)
    +                .map(|i| format!("#[test] fn {name}_{i}() {{}}\n"))
    +                .collect::<String>();
    +            let facts = RaRustSyntaxAdapter.summarize_file(&path, &source)?;
    +            owned.tests.extend(facts.tests.iter().cloned());
    +            owned.functions.extend(facts.functions.iter().cloned());
    +            files.push((path, facts));
    +        }
    +        let mut index = RustIndex::from_owned(owned);
    +        for (path, facts) in files {
    +            index.insert_file_only(path, facts);
    +        }
    +        Ok(index)
    +    }
    +
    +    #[test]
    +    fn candidate_query_memos_share_nonempty_results_and_preserve_full_scan_order()
    +    -> Result<(), String> {
    +        let index = candidate_cache_index()?;
    +        let context = CompactGripContext::new(&index);
    +        assert_eq!(context.tests.len(), 129);
    +        for query in ["owner", "own", "o", "near", "absent", ""] {
    +            // Independent of the candidate index and memo: scan every test.
    +            let expected = context
    +                .tests
    +                .iter()
    +                .enumerate()
    +                .filter_map(|(i, test)| {
    +                    (!query.is_empty() && test.name_lower.contains(query)).then_some(i)
    +                })
    +                .collect::<Vec<_>>();
    +            for _ in 0..2 {
    +                assert_eq!(
    +                    context
    +                        .owner_named_indices(query)
    +                        .as_deref()
    +                        .unwrap_or_default(),
    +                    expected,
    +                    "name query {query}"
    +                );
    +            }
    +        }
    +        let first = context
    +            .owner_named_indices("owner")
    +            .ok_or("missing owner candidates")?;
    +        let second = context
    +            .owner_named_indices("owner")
    +            .ok_or("missing cached owner candidates")?;
    +        assert!(
    +            Arc::ptr_eq(&first, &second),
    +            "warm lookup copied owner candidates"
    +        );
    +
    +        // Both files share parent a, but 129 relations exceed the 64-test
    +        // crowded limit. Only the test-named sibling remains; do not compute
    +        // this oracle with same_module or close_module.
    +        let expected = context
    +            .tests
    +            .iter()
    +            .enumerate()
    +            .filter_map(|(i, test)| (test.module_path.as_deref() == Some("a/tests")).then_some(i))
    +            .collect::<Vec<_>>();
    +        assert_eq!(expected.len(), 64);
    +        let first = context
    +            .same_module_indices("a/owner")
    +            .ok_or("missing module candidates")?;
    +        let second = context
    +            .same_module_indices("a/owner")
    +            .ok_or("missing cached module candidates")?;
    +        assert_eq!(first.as_ref(), expected);
    +        assert_eq!(second.as_ref(), expected);
    +        assert!(
    +            Arc::ptr_eq(&first, &second),
    +            "warm lookup copied module candidates"
    +        );
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn candidate_query_memos_keep_empty_results_without_shared_buffers() {
    +        let index = RustIndex::default();
    +        let context = CompactGripContext::new(&index);
    +        for _ in 0..2 {
    +            assert!(context.owner_named_indices("").is_none());
    +            assert!(context.same_module_indices("").is_none());
    +        }
    +        assert!(memo(&context.owner_named_cache).is_empty());
    +        assert!(memo(&context.same_module_cache).is_empty());
    +        for _ in 0..2 {
    +            assert!(context.owner_named_indices("absent").is_none());
    +            assert!(context.same_module_indices("absent/owner").is_none());
    +        }
    +        assert!(
    +            memo(&context.owner_named_cache)
    +                .get("absent")
    +                .is_some_and(Option::is_none)
    +        );
    +        assert!(
    +            memo(&context.same_module_cache)
    +                .get("absent/owner")
    +                .is_some_and(Option::is_none)
    +        );
    +    }
    +
    +    #[test]
    +    fn candidate_query_memo_clear_releases_cache_ownership_not_live_readers() -> Result<(), String>
    +    {
    +        let index = candidate_cache_index()?;
    +        let context = CompactGripContext::new(&index);
    +        let owner = context
    +            .owner_named_indices("owner")
    +            .ok_or("missing owner candidates")?;
    +        let module = context
    +            .same_module_indices("a/owner")
    +            .ok_or("missing module candidates")?;
    +        let owner_weak = Arc::downgrade(&owner);
    +        let module_weak = Arc::downgrade(&module);
    +        context.clear_window_memos();
    +        assert!(memo(&context.owner_named_cache).is_empty());
    +        assert!(memo(&context.same_module_cache).is_empty());
    +        let rebuilt_owner = context
    +            .owner_named_indices("owner")
    +            .ok_or("missing rebuilt owner candidates")?;
    +        let rebuilt_module = context
    +            .same_module_indices("a/owner")
    +            .ok_or("missing rebuilt module candidates")?;
    +        assert_eq!(owner, rebuilt_owner);
    +        assert_eq!(module, rebuilt_module);
    +        assert!(!Arc::ptr_eq(&owner, &rebuilt_owner));
    +        assert!(!Arc::ptr_eq(&module, &rebuilt_module));
    +        drop(owner);
    +        drop(module);
    +        assert!(owner_weak.upgrade().is_none());
    +        assert!(module_weak.upgrade().is_none());
    +        Ok(())
    +    }
    +
         #[test]
         fn retained_import_lines_preserve_unbounded_affinity_and_owner_matching() -> Result<(), String>
         {
    diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs
    new file mode 100644
    index 0000000000000000000000000000000000000000..cbf16508a381fa1ead0f36ad8b045004a2c8f8f6
    --- /dev/null
    +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs
    @@ -0,0 +1,130 @@
    +use super::{close_module, same_module};
    +
    +#[test]
    +fn module_match_preserves_slash_boundaries_and_close_segments() {
    +    for (test, same, close) in [
    +        ("a/b", true, true),
    +        ("a/b/", true, false),
    +        ("a/b/owner", true, true),
    +        ("a/b/owner/child", true, true),
    +        ("a/b/owner_extra", true, false),
    +        ("a/b/distant", true, false),
    +        ("a/b/test", true, true),
    +        ("a/b/tests", true, true),
    +        ("a/b/test_cache", true, true),
    +        ("a/b/cache_test", true, true),
    +        ("a/b/cache_tests", true, true),
    +        ("a/b/contest", true, false),
    +        ("a/b/tests_extra", true, false),
    +        ("a/b/testing", true, false),
    +        ("a/b/café_tests", true, true),
    +        ("a_b/tests", true, true),
    +        ("a_b/owner/child", true, true),
    +        ("a_b/distant", true, false),
    +        ("a_b/", true, false),
    +        ("a_b", false, false),
    +        ("a/b_extra/tests", false, false),
    +        ("a_bc/tests", false, false),
    +        ("a_bé/tests", false, false),
    +        ("a_é/tests", false, false),
    +        ("a/bc/tests", false, false),
    +        ("other/a/b/tests", false, false),
    +        ("a/b\\tests", false, false),
    +        ("", false, false),
    +    ] {
    +        assert_eq!(same_module("a/b/owner", test), same, "same: {test:?}");
    +        assert_eq!(close_module("a/b/owner", test), close, "close: {test:?}");
    +    }
    +}
    +
    +#[test]
    +fn module_match_preserves_empty_and_unicode_inputs() {
    +    for (owner, test, same, close) in [
    +        ("", "", false, false),
    +        ("flat", "flat/tests", false, false),
    +        ("/owner", "", false, true),
    +        ("/owner", "/tests", false, true),
    +        ("/owner", "tests", false, false),
    +        ("/", "/", false, true),
    +        ("a/b/", "a/b/", true, true),
    +        ("a//owner", "a//tests", true, true),
    +        ("a//owner", "a_/tests", true, true),
    +        ("a/b/owner", "a/b//tests", true, false),
    +        ("a_b/owner", "a/b/tests", false, false),
    +        ("a/b_c/owner", "a_b_c/tests", true, true),
    +        ("a_b/c/owner", "a_b_c/tests", true, true),
    +        ("/é/owner", "_é/tests", true, true),
    +        ("é/owner", "根/tests", false, false),
    +        ("ab/owner", "é/tests", false, false),
    +        ("根/éclair/所有者", "根/éclair", true, true),
    +        ("根/éclair/所有者", "根/éclair/所有者/子", true, true),
    +        ("根/éclair/所有者", "根_éclair/tests", true, true),
    +        ("根/éclair/所有者", "根_éclair", false, false),
    +        ("根/éclair/所有者", "根/éclair/遠方", true, false),
    +        ("根/éclair/所有者", "根/éclairé/tests", false, false),
    +        ("根/éclair/所有者", "根_éclairé/tests", false, false),
    +        ("e\u{301}/owner", "é/tests", false, false),
    +    ] {
    +        assert_eq!(same_module(owner, test), same, "same: {owner:?}, {test:?}");
    +        assert_eq!(
    +            close_module(owner, test),
    +            close,
    +            "close: {owner:?}, {test:?}"
    +        );
    +    }
    +}
    +
    +#[test]
    +fn module_match_agrees_with_literal_prefix_reading() {
    +    for parent in ["", "a", "a/b", "a_b", "a/", "/a", "根/éclair"] {
    +        for leaf in ["", "owner", "tests", "所有者"] {
    +            let owner = format!("{parent}/{leaf}");
    +            for prefix in [parent.to_string(), parent.replace('/', "_"), "other".into()] {
    +                for tail in [
    +                    "",
    +                    "/",
    +                    "/owner",
    +                    "/owner/child",
    +                    "/tests",
    +                    "/test_name",
    +                    "/name_tests",
    +                    "/distant",
    +                    "/所有者",
    +                    "x/tests",
    +                    "_tests",
    +                ] {
    +                    let test = format!("{prefix}{tail}");
    +                    let same = !parent.is_empty()
    +                        && (test == parent
    +                            || test.starts_with(&format!("{parent}/"))
    +                            || test.starts_with(&format!("{}/", parent.replace('/', "_"))));
    +                    let direct = format!("{parent}/");
    +                    let flattened = format!("{}/", parent.replace('/', "_"));
    +                    let close = test == parent
    +                        || test
    +                            .strip_prefix(&direct)
    +                            .or_else(|| test.strip_prefix(&flattened))
    +                            .is_some_and(|rest| {
    +                                let segment = rest.split('/').next().unwrap_or(rest);
    +                                segment == leaf
    +                                    || segment == "test"
    +                                    || segment == "tests"
    +                                    || segment.ends_with("_test")
    +                                    || segment.ends_with("_tests")
    +                                    || segment.starts_with("test_")
    +                            });
    +                    assert_eq!(
    +                        same_module(&owner, &test),
    +                        same,
    +                        "same: {owner:?}, {test:?}"
    +                    );
    +                    assert_eq!(
    +                        close_module(&owner, &test),
    +                        close,
    +                        "close: {owner:?}, {test:?}"
    +                    );
    +                }
    +            }
    +        }
    +    }
    +}
    proof/candidate_component.rs — complete instrument; SHA-256 dfe79d83af1f562d437f73a6b41d8a1a04199ccc107cdec2938ea1b3db36a60d
    //! Disposable source-exact query component; not a complete RIPR crate.
    //! Query/index/clear/predicate functions are copied unchanged from this candidate.
    //! Unrelated context fields have empty shells; no parser or classifier is run.
    #![allow(dead_code)]
    use std::sync::Arc;
    use std::cell::Cell;
    use std::alloc::{GlobalAlloc,Layout,System};
    thread_local! {
     static TRACK: Cell<bool> = const { Cell::new(false) };
     static CALLS: Cell<usize> = const { Cell::new(0) };
     static BYTES: Cell<usize> = const { Cell::new(0) };
    }
    struct CountAlloc;
    fn record(bytes:usize) { TRACK.with(|active| {if active.get() {CALLS.with(|v|v.set(v.get()+1));BYTES.with(|v|v.set(v.get()+bytes));}}); }
    unsafe impl GlobalAlloc for CountAlloc {
     unsafe fn alloc(&self,l:Layout)->*mut u8 {record(l.size());unsafe{System.alloc(l)}}
     unsafe fn alloc_zeroed(&self,l:Layout)->*mut u8 {record(l.size());unsafe{System.alloc_zeroed(l)}}
     unsafe fn realloc(&self,p:*mut u8,l:Layout,n:usize)->*mut u8 {record(n);unsafe{System.realloc(p,l,n)}}
     unsafe fn dealloc(&self,p:*mut u8,l:Layout) {unsafe{System.dealloc(p,l)}}
    }
    #[global_allocator] static ALLOCATOR: CountAlloc=CountAlloc;
    fn measure<T>(work:impl FnOnce()->T)->(T,usize,usize) {CALLS.with(|v|v.set(0));BYTES.with(|v|v.set(0));TRACK.with(|v|v.set(true));let result=work();TRACK.with(|v|v.set(false));(result,CALLS.with(Cell::get),BYTES.with(Cell::get))}
    trait View {fn view(&self)->&[usize];}
    impl View for Vec<usize> {fn view(&self)->&[usize]{self.as_slice()}}
    impl View for Option<Arc<[usize]>> {fn view(&self)->&[usize]{self.as_deref().unwrap_or_default()}}
    mod subject {
    use std::collections::{BTreeMap,BTreeSet};
    use std::sync::{Arc,Mutex,MutexGuard,PoisonError};
    #[derive(Default)] struct DummyGrips;
    impl DummyGrips {fn release_unheld(&mut self){}}
    struct CompactTest {name_lower:String,module_path:Option<String>}
    pub(super) struct CompactGripContext<'a> {
     _scope:std::marker::PhantomData<&'a ()>,
     tests:Vec<CompactTest>,
     name_module_candidates:NameModuleCandidateIndex,
        owner_named_cache: Mutex<BTreeMap<String, Option<Arc<[usize]>>>>,
        same_module_cache: Mutex<BTreeMap<String, Option<Arc<[usize]>>>>,
     parsed_sources:Mutex<BTreeMap<usize,usize>>,
     inherent_helper_reach:Mutex<BTreeMap<usize,usize>>,
     shared_grips:Mutex<DummyGrips>,
    }
    fn memo<T>(memo:&Mutex<T>)->MutexGuard<'_,T>{memo.lock().unwrap_or_else(PoisonError::into_inner)}
    #[derive(Default)]
    struct NameModuleCandidateIndex {
        name_trigrams: BTreeMap<[u8; 3], Vec<usize>>,
        module_prefixes: BTreeMap<String, Vec<usize>>,
    }
    
    impl NameModuleCandidateIndex {
        fn insert(&mut self, index: usize, name: &str, module: Option<&str>) {
            let trigrams = name
                .as_bytes()
                .windows(3)
                .map(|window| [window[0], window[1], window[2]]);
            for trigram in trigrams.collect::<BTreeSet<_>>() {
                self.name_trigrams.entry(trigram).or_default().push(index);
            }
            if let Some(module) = module {
                // Include the exact module and all slash-delimited ancestors.
                // An owner parent may also match an underscore-flattened prefix.
                self.module_prefixes
                    .entry(module.to_string())
                    .or_default()
                    .push(index);
                for (position, _) in module.match_indices('/') {
                    self.module_prefixes
                        .entry(module[..position].to_string())
                        .or_default()
                        .push(index);
                }
            }
        }
    
        fn name_candidates(&self, query: &str, test_count: usize) -> Vec<usize> {
            if query.len() < 3 {
                // Sub-byte-trigram names have no safe indexed key.
                return (0..test_count).collect();
            }
            let mut rarest: Option<&Vec<usize>> = None;
            for window in query.as_bytes().windows(3) {
                let Some(indices) = self.name_trigrams.get(&[window[0], window[1], window[2]]) else {
                    return Vec::new();
                };
                if rarest.is_none_or(|prior| indices.len() < prior.len()) {
                    rarest = Some(indices);
                }
            }
            rarest.cloned().unwrap_or_default()
        }
    
        fn module_candidates(&self, owner_module: &str) -> Vec<usize> {
            let Some((parent, _)) = owner_module.rsplit_once('/') else {
                return Vec::new();
            };
            if parent.is_empty() {
                return Vec::new();
            }
            let mut indices = self
                .module_prefixes
                .get(parent)
                .cloned()
                .unwrap_or_default();
            let flattened = parent.replace('/', "_");
            if flattened != parent {
                indices.extend(
                    self.module_prefixes
                        .get(&flattened)
                        .into_iter()
                        .flatten()
                        .copied(),
                );
            }
            indices.sort_unstable();
            indices.dedup();
            indices
        }
    }
    impl CompactGripContext<'_> {
        pub(crate) fn clear_window_memos(&self) {
            memo(&self.owner_named_cache).clear();
            memo(&self.same_module_cache).clear();
            memo(&self.parsed_sources).clear();
            memo(&self.inherent_helper_reach).clear();
            memo(&self.shared_grips).release_unheld();
        }
        pub(super) fn owner_named_indices(&self, owner_name_lower: &str) -> Option<Arc<[usize]>> {
            if owner_name_lower.is_empty() {
                return None;
            }
            if let Some(indices) = memo(&self.owner_named_cache).get(owner_name_lower) {
                return indices.clone();
            }
            let indices = self
                .name_module_candidates
                .name_candidates(owner_name_lower, self.tests.len())
                .into_iter()
                .filter(|&index| self.tests[index].name_lower.contains(owner_name_lower))
                .collect::<Vec<_>>();
            let indices: Option<Arc<[usize]>> = (!indices.is_empty()).then(|| Arc::from(indices));
            memo(&self.owner_named_cache).insert(owner_name_lower.to_string(), indices.clone());
            indices
        }
    
        pub(super) fn same_module_indices(&self, owner_module: &str) -> Option<Arc<[usize]>> {
            if owner_module.is_empty() {
                return None;
            }
            if let Some(indices) = memo(&self.same_module_cache).get(owner_module) {
                return indices.clone();
            }
            let indices = self
                .name_module_candidates
                .module_candidates(owner_module)
                .into_iter()
                .filter(|&index| {
                    self.tests[index]
                        .module_path
                        .as_deref()
                        .is_some_and(|test_module| same_module(owner_module, test_module))
                })
                .collect::<Vec<_>>();
            let indices = if indices.len() > crowded_relation_limit(self.tests.len()) {
                indices
                    .into_iter()
                    .filter(|&index| {
                        self.tests[index]
                            .module_path
                            .as_deref()
                            .is_some_and(|test_module| close_module(owner_module, test_module))
                    })
                    .collect()
            } else {
                indices
            };
            let indices: Option<Arc<[usize]>> = (!indices.is_empty()).then(|| Arc::from(indices));
            memo(&self.same_module_cache).insert(owner_module.to_string(), indices.clone());
            indices
        }
    }
    pub(super) fn crowded_relation_limit(test_count: usize) -> usize {
        (test_count / 100).max(64)
    }
    
    fn flattened_module_rest<'a>(parent: &str, test_module: &'a str) -> Option<&'a str> {
        let prefix = test_module.get(..parent.len())?;
        let rest = test_module.get(parent.len()..)?.strip_prefix('/')?;
        prefix
            .bytes()
            .eq(parent
                .bytes()
                .map(|byte| if byte == b'/' { b'_' } else { byte }))
            .then_some(rest)
    }
    
    pub(super) fn close_module(owner_module: &str, test_module: &str) -> bool {
        let Some((parent, leaf)) = owner_module.rsplit_once('/') else {
            return false;
        };
        if test_module == parent {
            return true;
        }
        let Some(rest) = test_module
            .strip_prefix(parent)
            .and_then(|rest| rest.strip_prefix('/'))
            .or_else(|| flattened_module_rest(parent, test_module))
        else {
            return false;
        };
        let segment = rest.split('/').next().unwrap_or(rest);
        segment == leaf
            || segment == "test"
            || segment == "tests"
            || segment.ends_with("_test")
            || segment.ends_with("_tests")
            || segment.starts_with("test_")
    }
    
    pub(super) fn same_module(owner_module: &str, test_module: &str) -> bool {
        let parent = match owner_module.rsplit_once('/') {
            Some((parent, _leaf)) => parent,
            None => return false,
        };
        if parent.is_empty() {
            return false;
        }
        test_module == parent
            || test_module
                .strip_prefix(parent)
                .is_some_and(|rest| rest.starts_with('/'))
            || flattened_module_rest(parent, test_module).is_some()
    }
    pub(super) fn fixture(rows:&[(String,Option<String>)])->CompactGripContext<'static> {
     let tests=rows.iter().map(|(name,module)|CompactTest{name_lower:name.clone(),module_path:module.clone()}).collect::<Vec<_>>();
     let mut name_module_candidates=NameModuleCandidateIndex::default();
     for(i,test)in tests.iter().enumerate(){name_module_candidates.insert(i,&test.name_lower,test.module_path.as_deref());}
     CompactGripContext {_scope:std::marker::PhantomData,tests,name_module_candidates,owner_named_cache:Mutex::new(BTreeMap::new()),same_module_cache:Mutex::new(BTreeMap::new()),parsed_sources:Mutex::new(BTreeMap::new()),inherent_helper_reach:Mutex::new(BTreeMap::new()),shared_grips:Mutex::new(DummyGrips)}
    }
    
    pub(super) struct OwnerContext<'a>{pub(super) module_path:Option<String>,pub(super) name_lower:String,pub(super)_scope:std::marker::PhantomData<&'a ()>}
    #[derive(Clone,Copy,PartialEq,Eq,Debug)]pub(super) enum RelationReason{SameModule,OwnerNamedTest}
    fn insert_related_candidate(c:&mut BTreeMap<usize,RelationReason>,_:&CompactGripContext,_:Option<&str>,i:usize,r:RelationReason){c.insert(i,r);}
    pub(super) fn match_same_module(
        candidates: &mut BTreeMap<usize, RelationReason>,
        context: &CompactGripContext<'_>,
        prefix: Option<&str>,
        owner: &OwnerContext<'_>,
    ) {
        let Some(module_path) = owner.module_path.as_deref() else {
            return;
        };
        for &test_index in context
            .same_module_indices(module_path)
            .as_deref()
            .unwrap_or_default()
        {
            insert_related_candidate(
                candidates,
                context,
                prefix,
                test_index,
                RelationReason::SameModule,
            );
        }
    }
    pub(super) fn match_owner_named_test(
        candidates: &mut BTreeMap<usize, RelationReason>,
        context: &CompactGripContext<'_>,
        prefix: Option<&str>,
        owner: &OwnerContext<'_>,
    ) {
        for &test_index in context
            .owner_named_indices(&owner.name_lower)
            .as_deref()
            .unwrap_or_default()
        {
            insert_related_candidate(
                candidates,
                context,
                prefix,
                test_index,
                RelationReason::OwnerNamedTest,
            );
        }
    }
    #[cfg(test)]mod upstream_controls{use super::*;
    #[test]
    fn name_and_module_candidates_match_independent_full_scans() {
            let fixtures = [
                ("owner_start", Some("a/b/nested")),
                ("prefix_owner_middle_suffix", Some("a_b/nested")),
                ("suffix_owner", Some("a/b")),
                ("ownowner", Some("a_b")),
                ("éclair_owner", Some("a_b/nested/child")),
                ("owner_éclair", Some("a/b_else/sibling")),
                ("unrelated", Some("a/b_else")),
                ("", None),
            ];
            let mut index = NameModuleCandidateIndex::default();
            for (i, (name, module)) in fixtures.iter().enumerate() {
                index.insert(i, name, *module);
            }
            for query in [
                "owner", "own", "ow", "o", "é", "éclair", "", "no-match", "ownown",
            ] {
                let actual = if query.is_empty() {
                    Vec::new()
                } else {
                    index
                        .name_candidates(query, fixtures.len())
                        .into_iter()
                        .filter(|&i| fixtures[i].0.contains(query))
                        .collect::<Vec<_>>()
                };
                let expected = fixtures
                    .iter()
                    .enumerate()
                    .filter_map(|(i, (name, _))| {
                        (!query.is_empty() && name.contains(query)).then_some(i)
                    })
                    .collect::<Vec<_>>();
                assert_eq!(actual, expected, "name query {query:?}");
            }
            for owner in [
                "a/b/owner",
                "a_b/owner",
                "a/b",
                "a/owner",
                "flat",
                "/owner",
                "missing/owner",
            ] {
                let actual = index
                    .module_candidates(owner)
                    .into_iter()
                    .filter(|&i| {
                        fixtures[i]
                            .1
                            .is_some_and(|module| same_module(owner, module))
                    })
                    .collect::<Vec<_>>();
                // Inline legacy predicate: deliberately independent of the indexed
                // candidate generator and of `same_module`.
                let expected = fixtures
                    .iter()
                    .enumerate()
                    .filter_map(|(i, (_, module))| {
                        let parent = owner
                            .rsplit_once('/')
                            .map(|(parent, _)| parent)
                            .unwrap_or("");
                        let related = !parent.is_empty()
                            && module.is_some_and(|module| {
                                module == parent
                                    || module.starts_with(&format!("{parent}/"))
                                    || module.starts_with(&format!("{}/", parent.replace('/', "_")))
                            });
                        related.then_some(i)
                    })
                    .collect::<Vec<_>>();
                assert_eq!(actual, expected, "module query {owner:?}");
            }
        }
    #[test]
    fn new_queries_inspect_only_indexed_candidates() {
            let mut index = NameModuleCandidateIndex::default();
            // Every noise name shares the query's `tar` trigram, so only the
            // rarest-trigram choice keeps the candidate list at one entry.
            for i in 0..4096 {
                index.insert(i, &format!("noise_tar_{i}"), Some("unrelated/tests"));
            }
            index.insert(4096, "prefix_target_suffix", Some("target/nested"));
            assert_eq!(index.name_candidates("target", 4097), [4096]);
            assert_eq!(index.module_candidates("target/owner"), [4096]);
            assert!(index.name_candidates("absent", 4097).is_empty());
            assert!(index.name_candidates("target_absent", 4097).is_empty());
        }
    }
    }
    fn large_rows()->Vec<(String,Option<String>)> {(0..4096).map(|i|(format!("owner_{i}"),Some("crate/owner/tests".to_string()))).collect()}
    #[test]
    fn warm_nonempty_results_share_backing(){let c=subject::fixture(&large_rows());let a=c.owner_named_indices("owner");let b=c.owner_named_indices("owner");assert_eq!(a.view(),b.view());assert_eq!(a.view().len(),4096);assert_eq!(a.view().as_ptr(),b.view().as_ptr(),"warm owner lookup cloned the vector");let a=c.same_module_indices("crate/owner");let b=c.same_module_indices("crate/owner");assert_eq!(a.view(),b.view());assert_eq!(a.view().len(),4096);assert_eq!(a.view().as_ptr(),b.view().as_ptr(),"warm module lookup cloned the vector");}
    #[test]
    fn warm_nonempty_queries_allocate_no_candidate_buffers(){let c=subject::fixture(&large_rows());std::hint::black_box(c.owner_named_indices("owner"));std::hint::black_box(c.same_module_indices("crate/owner"));let(_,calls,bytes)=measure(||for _ in 0..128{std::hint::black_box(c.owner_named_indices("owner"));std::hint::black_box(c.same_module_indices("crate/owner"));});println!("warm_nonempty lookups=256 calls={calls} requested_bytes={bytes}");assert_eq!((calls,bytes),(0,0));}
    #[test]
    fn empty_queries_are_allocation_free_when_empty_key_or_warm(){let c=subject::fixture(&large_rows());let(_,calls,bytes)=measure(||{assert!(c.owner_named_indices("").view().is_empty());assert!(c.same_module_indices("").view().is_empty());});assert_eq!((calls,bytes),(0,0),"first empty-key query allocates");let(a,calls,bytes)=measure(||c.owner_named_indices("absent_query"));assert!(a.view().is_empty());println!("cold_empty_owner calls={calls} requested_bytes={bytes}");let(a,calls,bytes)=measure(||c.same_module_indices("absent/owner"));assert!(a.view().is_empty());println!("cold_empty_module calls={calls} requested_bytes={bytes}");let(_,calls,bytes)=measure(||for _ in 0..128{std::hint::black_box(c.owner_named_indices("absent_query"));std::hint::black_box(c.same_module_indices("absent/owner"));std::hint::black_box(c.owner_named_indices(""));std::hint::black_box(c.same_module_indices(""));});println!("warm_empty lookups=512 calls={calls} requested_bytes={bytes}");assert_eq!((calls,bytes),(0,0));}
    #[test]
    fn cold_nonempty_reports_allocation_requests_and_exact_order(){let c=subject::fixture(&large_rows());let(a,calls,bytes)=measure(||c.owner_named_indices("owner"));assert_eq!(a.view(),(0..4096).collect::<Vec<_>>());println!("cold_nonempty_owner calls={calls} requested_bytes={bytes}");let(a,calls,bytes)=measure(||c.same_module_indices("crate/owner"));assert_eq!(a.view(),(0..4096).collect::<Vec<_>>());println!("cold_nonempty_module calls={calls} requested_bytes={bytes}");}
    #[test]
    fn clear_preserves_held_results_and_rebuild_order(){let c=subject::fixture(&large_rows());let a=c.owner_named_indices("owner");let m=c.same_module_indices("crate/owner");c.clear_window_memos();let b=c.owner_named_indices("owner");let n=c.same_module_indices("crate/owner");assert_eq!(a.view(),b.view());assert_eq!(m.view(),n.view());assert_ne!(a.view().as_ptr(),b.view().as_ptr());assert_ne!(m.view().as_ptr(),n.view().as_ptr());}
    #[test]
    fn cold_warm_full_scan_parity_including_crowded_modules(){let mut rows=vec![("owner_éclair".to_string(),Some("a/b/tests".to_string())),("éclair_owner".to_string(),Some("a_b/test_owner".to_string())),("o".to_string(),None)];for i in 0..70{rows.push((format!("owner_far_{i}"),Some("a/b/distant".to_string())));}let c=subject::fixture(&rows);for q in["owner","own","ow","o","é","éclair","","absent"]{let expect=rows.iter().enumerate().filter_map(|(i,(name,_))|(!q.is_empty()&&name.contains(q)).then_some(i)).collect::<Vec<_>>();for _ in 0..2 {assert_eq!(c.owner_named_indices(q).view(),expect,"{q}");}}for _ in 0..2{assert_eq!(c.same_module_indices("a/b/owner").view(),[0,1],"crowded distant modules must stay excluded");assert!(c.same_module_indices("").view().is_empty());assert!(c.same_module_indices("missing/owner").view().is_empty());}}
    
    #[test]fn actual_consumer_loops_iterate_the_complete_shared_results(){use std::collections::BTreeMap;let c=subject::fixture(&large_rows());let owner=subject::OwnerContext{module_path:Some("crate/owner".to_string()),name_lower:"owner".to_string(),_scope:std::marker::PhantomData};let mut seen=BTreeMap::new();subject::match_same_module(&mut seen,&c,None,&owner);assert_eq!(seen.len(),4096);assert!(seen.values().all(|r|*r==subject::RelationReason::SameModule));seen.clear();subject::match_owner_named_test(&mut seen,&c,None,&owner);assert_eq!(seen.len(),4096);assert!(seen.values().all(|r|*r==subject::RelationReason::OwnerNamedTest));}
    
    #[test]
    fn clearing_drops_cache_ownership_but_keeps_only_live_readers() -> Result<(),String> {
     let c=subject::fixture(&large_rows());
     let owner=c.owner_named_indices("owner").ok_or("missing owner candidates")?;
     let module=c.same_module_indices("crate/owner").ok_or("missing module candidates")?;
     let owner_weak=Arc::downgrade(&owner);let module_weak=Arc::downgrade(&module);
     assert_eq!(Arc::strong_count(&owner),2);assert_eq!(Arc::strong_count(&module),2);
     c.clear_window_memos();
     assert_eq!(Arc::strong_count(&owner),1);assert_eq!(Arc::strong_count(&module),1);
     assert_eq!(owner.len(),4096);assert_eq!(module.len(),4096);
     drop(owner);drop(module);
     assert!(owner_weak.upgrade().is_none());assert!(module_weak.upgrade().is_none());
     Ok(())
    }
    
    use subject::{close_module, same_module};
    #[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    mod repository_module_match_tests;
    #[cfg(test)]
    mod component_controls {
    use super::*;
    use std::hint::black_box;
    fn rows(module: &str) -> Vec<(String, Option<String>)> {
        (0..4096).map(|i| (format!("owner_{i}"), Some(module.to_owned()))).collect()
    }
    
    #[test]
    fn direct_predicates_create_no_temporary_strings() {
        let (answers, calls, bytes) = measure(|| {
            let mut answers = 0;
            for _ in 0..4096 {
                answers += usize::from(subject::same_module(
                    black_box("crate/owner"), black_box("crate/owner/tests")));
                answers += usize::from(subject::close_module(
                    black_box("crate/owner"), black_box("crate/owner/tests")));
            }
            answers
        });
        assert_eq!(answers, 8192);
        println!("direct_predicates comparisons=8192 calls={calls} requested_bytes={bytes}");
        assert_eq!((calls, bytes), (0, 0), "direct matches build temporary strings");
    }
    
    
    #[test]
    fn flattened_predicates_create_no_temporary_strings() {
        let (answers, calls, bytes) = measure(|| {
            let mut answers = 0;
            for _ in 0..4096 {
                answers += usize::from(subject::same_module(
                    black_box("a/b/owner"), black_box("a_b/test_owner")));
                answers += usize::from(subject::close_module(
                    black_box("a/b/owner"), black_box("a_b/test_owner")));
            }
            answers
        });
        assert_eq!(answers, 8192);
        println!("flattened_predicates comparisons=8192 calls={calls} requested_bytes={bytes}");
        assert_eq!((calls, bytes), (0, 0), "flattened matches build temporary strings");
    }
    
    #[test]
    fn cold_direct_query_keeps_all_rows_without_per_row_allocations() {
        let context = subject::fixture(&rows("crate/owner/tests"));
        let expected = (0..4096).collect::<Vec<_>>();
        let (actual, calls, bytes) =
            measure(|| context.same_module_indices(black_box("crate/owner")));
        assert_eq!(actual.view(), expected, "every admitted row must remain in exact order");
        println!("cold_direct_query rows={} calls={calls} requested_bytes={bytes}", actual.view().len());
        assert!(calls <= 8, "cold query still allocates per candidate: {calls}");
        assert!(bytes <= 80_000, "cold query still builds temporary parent strings: {bytes}");
    }
    
    #[test]
    fn cold_flattened_query_keeps_all_rows() {
        let context = subject::fixture(&rows("a_b/test_owner"));
        let expected = (0..4096).collect::<Vec<_>>();
        let (actual, calls, bytes) =
            measure(|| context.same_module_indices(black_box("a/b/owner")));
        assert_eq!(actual.view(), expected, "flattened candidates must remain in exact order");
        println!("cold_flattened_query rows={} calls={calls} requested_bytes={bytes}", actual.view().len());
        assert!(calls <= 8, "flattened query still allocates per candidate: {calls}");
        assert!(bytes <= 80_000, "flattened query still builds temporary parent strings: {bytes}");
    }
    
    #[test]
    fn crowded_query_retains_last_flattened_match_and_drops_distant_rows() {
        let mut inputs = rows("a/b/distant");
        inputs[4095].1 = Some("a_b/test_owner".to_owned());
        let context = subject::fixture(&inputs);
        for _ in 0..2 {
            assert_eq!(context.same_module_indices("a/b/owner").view(), [4095]);
        }
        assert!(context.same_module_indices("").view().is_empty());
        assert!(context.same_module_indices("missing/owner").view().is_empty());
    }
    }
    proof/check-source-identity.mjs — exact-source checks
    import assert from 'node:assert/strict';
    import { readFileSync } from 'node:fs';
    import { createHash } from 'node:crypto';
    import { execFileSync } from 'node:child_process';
    
    const contextPath = 'crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs';
    const parentPath = 'crates/ripr/src/analysis/test_grip_evidence/related_tests.rs';
    const context = readFileSync(contextPath, 'utf8');
    const parent = readFileSync(parentPath, 'utf8');
    const candidate = readFileSync('proof/candidate_component.rs', 'utf8');
    const baseline = readFileSync('proof/baseline_component.rs', 'utf8');
    // A source-subset witness may supply its local base. The exact Git-blob
    // assertions below still require the two original upstream file contents.
    const baseRef = process.argv[2] ?? '28b102c01f03e750e5ea387778e881d1c1bb0786';
    const baseContext = execFileSync('git', ['show', `${baseRef}:${contextPath}`], { encoding: 'utf8' });
    const baseParent = execFileSync('git', ['show', `${baseRef}:${parentPath}`], { encoding: 'utf8' });
    
    function blob(text) {
      const body = Buffer.from(text);
      return createHash('sha1').update(`blob ${body.length}\0`).update(body).digest('hex');
    }
    assert.equal(blob(baseContext), '93263927427f59038c83a1d3d1c9fd9e81452beb');
    assert.equal(blob(baseParent), 'df51aa2895d644f6ffc4af623a05017c12bdb33e');
    const testPath = 'crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs';
    assert.equal(blob(readFileSync(testPath, 'utf8')), 'cbf16508a381fa1ead0f36ad8b045004a2c8f8f6');
    const includedTests = `#[path = "../${testPath}"]\nmod repository_module_match_tests;`;
    assert.ok(candidate.includes(includedTests));
    assert.ok(baseline.includes(includedTests));
    
    // Each selected item has a unique signature and its own indentation-aligned
    // closing brace. Compare complete source items, not a rewritten algorithm.
    function item(source, marker, indent) {
      const start = source.indexOf(marker);
      assert.ok(start >= 0, `missing ${marker}`);
      assert.equal(source.indexOf(marker, start + marker.length), -1, `duplicate ${marker}`);
      const end = source.indexOf(`\n${indent}}`, start);
      assert.ok(end > start, `unclosed ${marker}`);
      return source.slice(start, end + indent.length + 2);
    }
    
    const methods = [
      ['pub(super) fn owner_named_indices(', '    '],
      ['pub(super) fn same_module_indices(', '    '],
      ['pub(crate) fn clear_window_memos(', '    '],
      ['struct NameModuleCandidateIndex {', ''],
      ['impl NameModuleCandidateIndex {', ''],
    ];
    const functions = [
      'pub(super) fn crowded_relation_limit(',
      'pub(super) fn close_module(',
      'pub(super) fn same_module(',
      'pub(super) fn match_same_module(',
      'pub(super) fn match_owner_named_test(',
    ];
    for (const [marker, indent] of methods) {
      assert.equal(item(candidate, marker, indent), item(context, marker, indent), `candidate ${marker}`);
      assert.equal(item(baseline, marker, indent), item(baseContext, marker, indent), `baseline ${marker}`);
    }
    for (const marker of functions) {
      assert.equal(item(candidate, marker, ''), item(parent, marker, ''), `candidate ${marker}`);
      // The baseline component does not claim to compile the unchanged consumers.
      if (!marker.includes('match_')) {
        assert.equal(item(baseline, marker, ''), item(baseParent, marker, ''), `baseline ${marker}`);
      }
    }
    assert.equal(item(candidate, "fn flattened_module_rest<'a>(", ''), item(parent, "fn flattened_module_rest<'a>(", ''), 'flattened borrowed helper');
    for (const field of ['owner_named_cache', 'same_module_cache']) {
      const fieldLine = (s) => s.match(new RegExp(`^    ${field}:.*$`, 'm'))?.[0];
      assert.ok(fieldLine(context));
      assert.equal(fieldLine(candidate), fieldLine(context));
      assert.equal(fieldLine(baseline), fieldLine(baseContext));
    }
    console.log(JSON.stringify({
      base: '28b102c01f03e750e5ea387778e881d1c1bb0786',
      base_blobs_verified: 2,
      candidate_exact_source_items: methods.length + functions.length + 1,
      baseline_exact_source_items: methods.length + functions.length - 2,
      cache_field_pairs_verified: 2,
      actual_repository_predicate_tests_included: 3,
      status: 'pass',
    }, null, 2));
    Complete root composed run
    {
      "base": "28b102c01f03e750e5ea387778e881d1c1bb0786",
      "base_blobs_verified": 2,
      "candidate_exact_source_items": 11,
      "baseline_exact_source_items": 8,
      "cache_field_pairs_verified": 2,
      "actual_repository_predicate_tests_included": 3,
      "status": "pass"
    }
    
    running 18 tests
    test actual_consumer_loops_iterate_the_complete_shared_results ... ok
    test clear_preserves_held_results_and_rebuild_order ... ok
    test clearing_drops_cache_ownership_but_keeps_only_live_readers ... ok
    test cold_nonempty_reports_allocation_requests_and_exact_order ... cold_nonempty_owner calls=4 requested_bytes=66013
    cold_nonempty_module calls=5 requested_bytes=66024
    ok
    test cold_warm_full_scan_parity_including_crowded_modules ... ok
    test component_controls::cold_direct_query_keeps_all_rows_without_per_row_allocations ... cold_direct_query rows=4096 calls=5 requested_bytes=66024
    ok
    test component_controls::cold_flattened_query_keeps_all_rows ... cold_flattened_query rows=4096 calls=5 requested_bytes=66020
    ok
    test component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows ... ok
    test component_controls::direct_predicates_create_no_temporary_strings ... direct_predicates comparisons=8192 calls=0 requested_bytes=0
    ok
    test component_controls::flattened_predicates_create_no_temporary_strings ... flattened_predicates comparisons=8192 calls=0 requested_bytes=0
    ok
    test empty_queries_are_allocation_free_when_empty_key_or_warm ... cold_empty_owner calls=2 requested_bytes=468
    cold_empty_module calls=3 requested_bytes=474
    warm_empty lookups=512 calls=0 requested_bytes=0
    ok
    test repository_module_match_tests::module_match_agrees_with_literal_prefix_reading ... ok
    test repository_module_match_tests::module_match_preserves_empty_and_unicode_inputs ... ok
    test repository_module_match_tests::module_match_preserves_slash_boundaries_and_close_segments ... ok
    test subject::upstream_controls::name_and_module_candidates_match_independent_full_scans ... ok
    test subject::upstream_controls::new_queries_inspect_only_indexed_candidates ... ok
    test warm_nonempty_queries_allocate_no_candidate_buffers ... warm_nonempty lookups=256 calls=0 requested_bytes=0
    ok
    test warm_nonempty_results_share_backing ... ok
    
    test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 7.44s
    
  8. EffortlessSteven commented on Nov 9, 2026

    @EffortlessSteven
    MemberAuthor

    Original-source and wrong-implementation controls for the selected query-allocation repair

    Companion to the exact composed patch and candidate proof, patch SHA-256 c8f60586e75317fa9de59c702ab78b3783b9a8c1ec004ab7d1ccc32860352586.

    Original source: compiled successfully, then 10 passing tests / 6 intended assertion failures, exit 101. The common semantic oracles pass. The failures detect non-shared warm backing, repeated warm allocations, direct and flattened per-row predicate allocations, and direct and flattened full-query allocations.

    Wrong implementations: each independently compiles (exit 0) under the same Rust 1.95 / edition 2024, then one deliberately selected test fails on its assertion (exit 101; 17 filtered). These are not missing dependencies or compilation failures.

    Wrong change Independent discriminator
    Allocate an empty Arc for each empty-key return Two calls allocate 2 times / 32 bytes, versus zero
    Accept a direct prefix without the slash boundary Owner a/, test ax/tests is wrongly admitted
    Stop mapping slash to underscore in the fallback Required flattened match at row 4,095 is lost
    Inspect only the first 128 indexed candidates The same required final match is lost

    The three pure predicate repository tests run by direct include in both candidate and baseline. The parser-backed cache tests still await full-crate execution; these controls do not claim otherwise. The allocator is an external proof instrument, not production code.

    The four complete mutation diffs below are relative to proof/candidate_component.rs from the first comment. The only common instrument-only adjustment is its repository-test include changing from ../crates/ to ../../crates/, because the variants live under proof/mutations/. Each variant's complete source can be reconstructed from that candidate plus its exact diff; source/diff hashes and commands are in the receipt.

    The initial mutation run used edition 2021. Review caught that configuration mismatch; it was superseded by the retained edition-2024 compile and assertion runs below. No production or test source changed between those instrument runs.

    The new main-health fix is separately merged as #13982 / 79ca845369eb8b5050310dec41ef241b33723b6a. Its one-line output/human.rs deletion has no overlap with these five candidate paths. Full repository qualification and the fixed-subject #12947 replay remain pending; no end-to-end acceptance or branch publication is implied.

    proof/baseline_component.rs — complete original-source instrument; SHA-256 3932aa2ae2e3940c31428d716b25b6f30a3cabbb0d28c5341e548e21784b3fed
    //! Disposable source-exact query component; not a complete RIPR crate.
    //! Query/index/clear/predicate functions are copied unchanged from main28b102c.
    //! Unrelated context fields have empty shells; no parser or classifier is run.
    #![allow(dead_code)]
    use std::sync::Arc;
    use std::cell::Cell;
    use std::alloc::{GlobalAlloc,Layout,System};
    thread_local! {
     static TRACK: Cell<bool> = const { Cell::new(false) };
     static CALLS: Cell<usize> = const { Cell::new(0) };
     static BYTES: Cell<usize> = const { Cell::new(0) };
    }
    struct CountAlloc;
    fn record(bytes:usize) { TRACK.with(|active| {if active.get() {CALLS.with(|v|v.set(v.get()+1));BYTES.with(|v|v.set(v.get()+bytes));}}); }
    unsafe impl GlobalAlloc for CountAlloc {
     unsafe fn alloc(&self,l:Layout)->*mut u8 {record(l.size());unsafe{System.alloc(l)}}
     unsafe fn alloc_zeroed(&self,l:Layout)->*mut u8 {record(l.size());unsafe{System.alloc_zeroed(l)}}
     unsafe fn realloc(&self,p:*mut u8,l:Layout,n:usize)->*mut u8 {record(n);unsafe{System.realloc(p,l,n)}}
     unsafe fn dealloc(&self,p:*mut u8,l:Layout) {unsafe{System.dealloc(p,l)}}
    }
    #[global_allocator] static ALLOCATOR: CountAlloc=CountAlloc;
    fn measure<T>(work:impl FnOnce()->T)->(T,usize,usize) {CALLS.with(|v|v.set(0));BYTES.with(|v|v.set(0));TRACK.with(|v|v.set(true));let result=work();TRACK.with(|v|v.set(false));(result,CALLS.with(Cell::get),BYTES.with(Cell::get))}
    trait View {fn view(&self)->&[usize];}
    impl View for Vec<usize> {fn view(&self)->&[usize]{self.as_slice()}}
    impl View for Option<Arc<[usize]>> {fn view(&self)->&[usize]{self.as_deref().unwrap_or_default()}}
    mod subject {
    use std::collections::{BTreeMap,BTreeSet};
    use std::sync::{Arc,Mutex,MutexGuard,PoisonError};
    #[derive(Default)] struct DummyGrips;
    impl DummyGrips {fn release_unheld(&mut self){}}
    struct CompactTest {name_lower:String,module_path:Option<String>}
    pub(super) struct CompactGripContext {
     tests:Vec<CompactTest>,
     name_module_candidates:NameModuleCandidateIndex,
        owner_named_cache: Mutex<BTreeMap<String, Vec<usize>>>,
        same_module_cache: Mutex<BTreeMap<String, Vec<usize>>>,
     parsed_sources:Mutex<BTreeMap<usize,usize>>,
     inherent_helper_reach:Mutex<BTreeMap<usize,usize>>,
     shared_grips:Mutex<DummyGrips>,
    }
    fn memo<T>(memo:&Mutex<T>)->MutexGuard<'_,T>{memo.lock().unwrap_or_else(PoisonError::into_inner)}
    #[derive(Default)]
    struct NameModuleCandidateIndex {
        name_trigrams: BTreeMap<[u8; 3], Vec<usize>>,
        module_prefixes: BTreeMap<String, Vec<usize>>,
    }
    
    impl NameModuleCandidateIndex {
        fn insert(&mut self, index: usize, name: &str, module: Option<&str>) {
            let trigrams = name
                .as_bytes()
                .windows(3)
                .map(|window| [window[0], window[1], window[2]]);
            for trigram in trigrams.collect::<BTreeSet<_>>() {
                self.name_trigrams.entry(trigram).or_default().push(index);
            }
            if let Some(module) = module {
                // Include the exact module and all slash-delimited ancestors.
                // An owner parent may also match an underscore-flattened prefix.
                self.module_prefixes
                    .entry(module.to_string())
                    .or_default()
                    .push(index);
                for (position, _) in module.match_indices('/') {
                    self.module_prefixes
                        .entry(module[..position].to_string())
                        .or_default()
                        .push(index);
                }
            }
        }
    
        fn name_candidates(&self, query: &str, test_count: usize) -> Vec<usize> {
            if query.len() < 3 {
                // Sub-byte-trigram names have no safe indexed key.
                return (0..test_count).collect();
            }
            let mut rarest: Option<&Vec<usize>> = None;
            for window in query.as_bytes().windows(3) {
                let Some(indices) = self.name_trigrams.get(&[window[0], window[1], window[2]]) else {
                    return Vec::new();
                };
                if rarest.is_none_or(|prior| indices.len() < prior.len()) {
                    rarest = Some(indices);
                }
            }
            rarest.cloned().unwrap_or_default()
        }
    
        fn module_candidates(&self, owner_module: &str) -> Vec<usize> {
            let Some((parent, _)) = owner_module.rsplit_once('/') else {
                return Vec::new();
            };
            if parent.is_empty() {
                return Vec::new();
            }
            let mut indices = self
                .module_prefixes
                .get(parent)
                .cloned()
                .unwrap_or_default();
            let flattened = parent.replace('/', "_");
            if flattened != parent {
                indices.extend(
                    self.module_prefixes
                        .get(&flattened)
                        .into_iter()
                        .flatten()
                        .copied(),
                );
            }
            indices.sort_unstable();
            indices.dedup();
            indices
        }
    }
    impl CompactGripContext {
        pub(crate) fn clear_window_memos(&self) {
            memo(&self.owner_named_cache).clear();
            memo(&self.same_module_cache).clear();
            memo(&self.parsed_sources).clear();
            memo(&self.inherent_helper_reach).clear();
            memo(&self.shared_grips).release_unheld();
        }
        pub(super) fn owner_named_indices(&self, owner_name_lower: &str) -> Vec<usize> {
            if owner_name_lower.is_empty() {
                return Vec::new();
            }
            if let Some(indices) = memo(&self.owner_named_cache).get(owner_name_lower) {
                return indices.clone();
            }
            let indices = self
                .name_module_candidates
                .name_candidates(owner_name_lower, self.tests.len())
                .into_iter()
                .filter(|&index| self.tests[index].name_lower.contains(owner_name_lower))
                .collect::<Vec<_>>();
            memo(&self.owner_named_cache).insert(owner_name_lower.to_string(), indices.clone());
            indices
        }
    
        pub(super) fn same_module_indices(&self, owner_module: &str) -> Vec<usize> {
            if owner_module.is_empty() {
                return Vec::new();
            }
            if let Some(indices) = memo(&self.same_module_cache).get(owner_module) {
                return indices.clone();
            }
            let indices = self
                .name_module_candidates
                .module_candidates(owner_module)
                .into_iter()
                .filter(|&index| {
                    self.tests[index]
                        .module_path
                        .as_deref()
                        .is_some_and(|test_module| same_module(owner_module, test_module))
                })
                .collect::<Vec<_>>();
            let indices = if indices.len() > crowded_relation_limit(self.tests.len()) {
                indices
                    .into_iter()
                    .filter(|&index| {
                        self.tests[index]
                            .module_path
                            .as_deref()
                            .is_some_and(|test_module| close_module(owner_module, test_module))
                    })
                    .collect()
            } else {
                indices
            };
            memo(&self.same_module_cache).insert(owner_module.to_string(), indices.clone());
            indices
        }
    }
    pub(super) fn crowded_relation_limit(test_count: usize) -> usize {
        (test_count / 100).max(64)
    }
    
    pub(super) fn close_module(owner_module: &str, test_module: &str) -> bool {
        let Some((parent, leaf)) = owner_module.rsplit_once('/') else {
            return false;
        };
        if test_module == parent {
            return true;
        }
        let flattened = parent.replace('/', "_");
        let Some(rest) = test_module
            .strip_prefix(parent)
            .and_then(|rest| rest.strip_prefix('/'))
            .or_else(|| {
                test_module
                    .strip_prefix(flattened.as_str())
                    .and_then(|rest| rest.strip_prefix('/'))
            })
        else {
            return false;
        };
        let segment = rest.split('/').next().unwrap_or(rest);
        segment == leaf
            || segment == "test"
            || segment == "tests"
            || segment.ends_with("_test")
            || segment.ends_with("_tests")
            || segment.starts_with("test_")
    }
    
    pub(super) fn same_module(owner_module: &str, test_module: &str) -> bool {
        let parent = match owner_module.rsplit_once('/') {
            Some((parent, _leaf)) => parent,
            None => return false,
        };
        if parent.is_empty() {
            return false;
        }
        test_module == parent
            || test_module.starts_with(&format!("{parent}/"))
            || test_module.starts_with(&format!("{}/", parent.replace('/', "_")))
    }
    pub(super) fn fixture(rows:&[(String,Option<String>)])->CompactGripContext {
     let tests=rows.iter().map(|(name,module)|CompactTest{name_lower:name.clone(),module_path:module.clone()}).collect::<Vec<_>>();
     let mut name_module_candidates=NameModuleCandidateIndex::default();
     for(i,test)in tests.iter().enumerate(){name_module_candidates.insert(i,&test.name_lower,test.module_path.as_deref());}
     CompactGripContext {tests,name_module_candidates,owner_named_cache:Mutex::new(BTreeMap::new()),same_module_cache:Mutex::new(BTreeMap::new()),parsed_sources:Mutex::new(BTreeMap::new()),inherent_helper_reach:Mutex::new(BTreeMap::new()),shared_grips:Mutex::new(DummyGrips)}
    }
    #[cfg(test)]mod upstream_controls{use super::*;
    #[test]
    fn name_and_module_candidates_match_independent_full_scans() {
            let fixtures = [
                ("owner_start", Some("a/b/nested")),
                ("prefix_owner_middle_suffix", Some("a_b/nested")),
                ("suffix_owner", Some("a/b")),
                ("ownowner", Some("a_b")),
                ("éclair_owner", Some("a_b/nested/child")),
                ("owner_éclair", Some("a/b_else/sibling")),
                ("unrelated", Some("a/b_else")),
                ("", None),
            ];
            let mut index = NameModuleCandidateIndex::default();
            for (i, (name, module)) in fixtures.iter().enumerate() {
                index.insert(i, name, *module);
            }
            for query in [
                "owner", "own", "ow", "o", "é", "éclair", "", "no-match", "ownown",
            ] {
                let actual = if query.is_empty() {
                    Vec::new()
                } else {
                    index
                        .name_candidates(query, fixtures.len())
                        .into_iter()
                        .filter(|&i| fixtures[i].0.contains(query))
                        .collect::<Vec<_>>()
                };
                let expected = fixtures
                    .iter()
                    .enumerate()
                    .filter_map(|(i, (name, _))| {
                        (!query.is_empty() && name.contains(query)).then_some(i)
                    })
                    .collect::<Vec<_>>();
                assert_eq!(actual, expected, "name query {query:?}");
            }
            for owner in [
                "a/b/owner",
                "a_b/owner",
                "a/b",
                "a/owner",
                "flat",
                "/owner",
                "missing/owner",
            ] {
                let actual = index
                    .module_candidates(owner)
                    .into_iter()
                    .filter(|&i| {
                        fixtures[i]
                            .1
                            .is_some_and(|module| same_module(owner, module))
                    })
                    .collect::<Vec<_>>();
                // Inline legacy predicate: deliberately independent of the indexed
                // candidate generator and of `same_module`.
                let expected = fixtures
                    .iter()
                    .enumerate()
                    .filter_map(|(i, (_, module))| {
                        let parent = owner
                            .rsplit_once('/')
                            .map(|(parent, _)| parent)
                            .unwrap_or("");
                        let related = !parent.is_empty()
                            && module.is_some_and(|module| {
                                module == parent
                                    || module.starts_with(&format!("{parent}/"))
                                    || module.starts_with(&format!("{}/", parent.replace('/', "_")))
                            });
                        related.then_some(i)
                    })
                    .collect::<Vec<_>>();
                assert_eq!(actual, expected, "module query {owner:?}");
            }
        }
    #[test]
    fn new_queries_inspect_only_indexed_candidates() {
            let mut index = NameModuleCandidateIndex::default();
            // Every noise name shares the query's `tar` trigram, so only the
            // rarest-trigram choice keeps the candidate list at one entry.
            for i in 0..4096 {
                index.insert(i, &format!("noise_tar_{i}"), Some("unrelated/tests"));
            }
            index.insert(4096, "prefix_target_suffix", Some("target/nested"));
            assert_eq!(index.name_candidates("target", 4097), [4096]);
            assert_eq!(index.module_candidates("target/owner"), [4096]);
            assert!(index.name_candidates("absent", 4097).is_empty());
            assert!(index.name_candidates("target_absent", 4097).is_empty());
        }
    }
    }
    fn large_rows()->Vec<(String,Option<String>)> {(0..4096).map(|i|(format!("owner_{i}"),Some("crate/owner/tests".to_string()))).collect()}
    #[test]
    fn warm_nonempty_results_share_backing(){let c=subject::fixture(&large_rows());let a=c.owner_named_indices("owner");let b=c.owner_named_indices("owner");assert_eq!(a.view(),b.view());assert_eq!(a.view().len(),4096);assert_eq!(a.view().as_ptr(),b.view().as_ptr(),"warm owner lookup cloned the vector");let a=c.same_module_indices("crate/owner");let b=c.same_module_indices("crate/owner");assert_eq!(a.view(),b.view());assert_eq!(a.view().len(),4096);assert_eq!(a.view().as_ptr(),b.view().as_ptr(),"warm module lookup cloned the vector");}
    #[test]
    fn warm_nonempty_queries_allocate_no_candidate_buffers(){let c=subject::fixture(&large_rows());std::hint::black_box(c.owner_named_indices("owner"));std::hint::black_box(c.same_module_indices("crate/owner"));let(_,calls,bytes)=measure(||for _ in 0..128{std::hint::black_box(c.owner_named_indices("owner"));std::hint::black_box(c.same_module_indices("crate/owner"));});println!("warm_nonempty lookups=256 calls={calls} requested_bytes={bytes}");assert_eq!((calls,bytes),(0,0));}
    #[test]
    fn empty_queries_are_allocation_free_when_empty_key_or_warm(){let c=subject::fixture(&large_rows());let(_,calls,bytes)=measure(||{assert!(c.owner_named_indices("").view().is_empty());assert!(c.same_module_indices("").view().is_empty());});assert_eq!((calls,bytes),(0,0),"first empty-key query allocates");let(a,calls,bytes)=measure(||c.owner_named_indices("absent_query"));assert!(a.view().is_empty());println!("cold_empty_owner calls={calls} requested_bytes={bytes}");let(a,calls,bytes)=measure(||c.same_module_indices("absent/owner"));assert!(a.view().is_empty());println!("cold_empty_module calls={calls} requested_bytes={bytes}");let(_,calls,bytes)=measure(||for _ in 0..128{std::hint::black_box(c.owner_named_indices("absent_query"));std::hint::black_box(c.same_module_indices("absent/owner"));std::hint::black_box(c.owner_named_indices(""));std::hint::black_box(c.same_module_indices(""));});println!("warm_empty lookups=512 calls={calls} requested_bytes={bytes}");assert_eq!((calls,bytes),(0,0));}
    #[test]
    fn cold_nonempty_reports_allocation_requests_and_exact_order(){let c=subject::fixture(&large_rows());let(a,calls,bytes)=measure(||c.owner_named_indices("owner"));assert_eq!(a.view(),(0..4096).collect::<Vec<_>>());println!("cold_nonempty_owner calls={calls} requested_bytes={bytes}");let(a,calls,bytes)=measure(||c.same_module_indices("crate/owner"));assert_eq!(a.view(),(0..4096).collect::<Vec<_>>());println!("cold_nonempty_module calls={calls} requested_bytes={bytes}");}
    #[test]
    fn clear_preserves_held_results_and_rebuild_order(){let c=subject::fixture(&large_rows());let a=c.owner_named_indices("owner");let m=c.same_module_indices("crate/owner");c.clear_window_memos();let b=c.owner_named_indices("owner");let n=c.same_module_indices("crate/owner");assert_eq!(a.view(),b.view());assert_eq!(m.view(),n.view());assert_ne!(a.view().as_ptr(),b.view().as_ptr());assert_ne!(m.view().as_ptr(),n.view().as_ptr());}
    #[test]
    fn cold_warm_full_scan_parity_including_crowded_modules(){let mut rows=vec![("owner_éclair".to_string(),Some("a/b/tests".to_string())),("éclair_owner".to_string(),Some("a_b/test_owner".to_string())),("o".to_string(),None)];for i in 0..70{rows.push((format!("owner_far_{i}"),Some("a/b/distant".to_string())));}let c=subject::fixture(&rows);for q in["owner","own","ow","o","é","éclair","","absent"]{let expect=rows.iter().enumerate().filter_map(|(i,(name,_))|(!q.is_empty()&&name.contains(q)).then_some(i)).collect::<Vec<_>>();for _ in 0..2 {assert_eq!(c.owner_named_indices(q).view(),expect,"{q}");}}for _ in 0..2{assert_eq!(c.same_module_indices("a/b/owner").view(),[0,1],"crowded distant modules must stay excluded");assert!(c.same_module_indices("").view().is_empty());assert!(c.same_module_indices("missing/owner").view().is_empty());}}
    
    use subject::{close_module, same_module};
    #[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    mod repository_module_match_tests;
    #[cfg(test)]
    mod component_controls {
    use super::*;
    use std::hint::black_box;
    fn rows(module: &str) -> Vec<(String, Option<String>)> {
        (0..4096).map(|i| (format!("owner_{i}"), Some(module.to_owned()))).collect()
    }
    
    #[test]
    fn direct_predicates_create_no_temporary_strings() {
        let (answers, calls, bytes) = measure(|| {
            let mut answers = 0;
            for _ in 0..4096 {
                answers += usize::from(subject::same_module(
                    black_box("crate/owner"), black_box("crate/owner/tests")));
                answers += usize::from(subject::close_module(
                    black_box("crate/owner"), black_box("crate/owner/tests")));
            }
            answers
        });
        assert_eq!(answers, 8192);
        println!("direct_predicates comparisons=8192 calls={calls} requested_bytes={bytes}");
        assert_eq!((calls, bytes), (0, 0), "direct matches build temporary strings");
    }
    
    
    #[test]
    fn flattened_predicates_create_no_temporary_strings() {
        let (answers, calls, bytes) = measure(|| {
            let mut answers = 0;
            for _ in 0..4096 {
                answers += usize::from(subject::same_module(
                    black_box("a/b/owner"), black_box("a_b/test_owner")));
                answers += usize::from(subject::close_module(
                    black_box("a/b/owner"), black_box("a_b/test_owner")));
            }
            answers
        });
        assert_eq!(answers, 8192);
        println!("flattened_predicates comparisons=8192 calls={calls} requested_bytes={bytes}");
        assert_eq!((calls, bytes), (0, 0), "flattened matches build temporary strings");
    }
    
    #[test]
    fn cold_direct_query_keeps_all_rows_without_per_row_allocations() {
        let context = subject::fixture(&rows("crate/owner/tests"));
        let expected = (0..4096).collect::<Vec<_>>();
        let (actual, calls, bytes) =
            measure(|| context.same_module_indices(black_box("crate/owner")));
        assert_eq!(actual.view(), expected, "every admitted row must remain in exact order");
        println!("cold_direct_query rows={} calls={calls} requested_bytes={bytes}", actual.view().len());
        assert!(calls <= 8, "cold query still allocates per candidate: {calls}");
        assert!(bytes <= 80_000, "cold query still builds temporary parent strings: {bytes}");
    }
    
    #[test]
    fn cold_flattened_query_keeps_all_rows() {
        let context = subject::fixture(&rows("a_b/test_owner"));
        let expected = (0..4096).collect::<Vec<_>>();
        let (actual, calls, bytes) =
            measure(|| context.same_module_indices(black_box("a/b/owner")));
        assert_eq!(actual.view(), expected, "flattened candidates must remain in exact order");
        println!("cold_flattened_query rows={} calls={calls} requested_bytes={bytes}", actual.view().len());
        assert!(calls <= 8, "flattened query still allocates per candidate: {calls}");
        assert!(bytes <= 80_000, "flattened query still builds temporary parent strings: {bytes}");
    }
    
    #[test]
    fn crowded_query_retains_last_flattened_match_and_drops_distant_rows() {
        let mut inputs = rows("a/b/distant");
        inputs[4095].1 = Some("a_b/test_owner".to_owned());
        let context = subject::fixture(&inputs);
        for _ in 0..2 {
            assert_eq!(context.same_module_indices("a/b/owner").view(), [4095]);
        }
        assert!(context.same_module_indices("").view().is_empty());
        assert!(context.same_module_indices("missing/owner").view().is_empty());
    }
    }
    Complete original-source run — six assertion failures
    Compile completed; test harness exited 101 at the intended assertions.
    
    
    running 16 tests
    test clear_preserves_held_results_and_rebuild_order ... ok
    test cold_nonempty_reports_allocation_requests_and_exact_order ... cold_nonempty_owner calls=4 requested_bytes=66085
    cold_nonempty_module calls=8197 requested_bytes=119344
    ok
    test cold_warm_full_scan_parity_including_crowded_modules ... ok
    test component_controls::cold_direct_query_keeps_all_rows_without_per_row_allocations ... cold_direct_query rows=4096 calls=8197 requested_bytes=119344
    
    thread 'component_controls::cold_direct_query_keeps_all_rows_without_per_row_allocations' (8) panicked at proof/baseline_component.rs:389:5:
    cold query still allocates per candidate: 8197
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    FAILED
    test component_controls::cold_flattened_query_keeps_all_rows ... 
    thread 'component_controls::cold_flattened_query_keeps_all_rows' (9) panicked at proof/baseline_component.rs:401:5:
    flattened query still allocates per candidate: 16389
    cold_flattened_query rows=4096 calls=16389 requested_bytes=156204
    FAILED
    test component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows ... ok
    test component_controls::direct_predicates_create_no_temporary_strings ... 
    thread 'component_controls::direct_predicates_create_no_temporary_strings' (11) panicked at proof/baseline_component.rs:360:5:
    assertion `left == right` failed: direct matches build temporary strings
      left: (8192, 53248)
     right: (0, 0)
    direct_predicates comparisons=8192 calls=8192 requested_bytes=53248
    FAILED
    test component_controls::flattened_predicates_create_no_temporary_strings ... 
    thread 'component_controls::flattened_predicates_create_no_temporary_strings' (12) panicked at proof/baseline_component.rs:378:5:
    assertion `left == right` failed: flattened matches build temporary strings
      left: (16384, 90112)
     right: (0, 0)
    flattened_predicates comparisons=8192 calls=16384 requested_bytes=90112
    FAILED
    test empty_queries_are_allocation_free_when_empty_key_or_warm ... cold_empty_owner calls=2 requested_bytes=556
    cold_empty_module calls=3 requested_bytes=562
    warm_empty lookups=512 calls=0 requested_bytes=0
    ok
    test repository_module_match_tests::module_match_agrees_with_literal_prefix_reading ... ok
    test repository_module_match_tests::module_match_preserves_empty_and_unicode_inputs ... ok
    test repository_module_match_tests::module_match_preserves_slash_boundaries_and_close_segments ... ok
    test subject::upstream_controls::name_and_module_candidates_match_independent_full_scans ... ok
    test subject::upstream_controls::new_queries_inspect_only_indexed_candidates ... ok
    test warm_nonempty_queries_allocate_no_candidate_buffers ... 
    thread 'warm_nonempty_queries_allocate_no_candidate_buffers' (19) panicked at proof/baseline_component.rs:325:444:
    assertion `left == right` failed
      left: (256, 8388608)
     right: (0, 0)
    warm_nonempty lookups=256 calls=256 requested_bytes=8388608
    FAILED
    test warm_nonempty_results_share_backing ... 
    thread 'warm_nonempty_results_share_backing' (20) panicked at proof/baseline_component.rs:323:216:
    assertion `left == right` failed: warm owner lookup cloned the vector
      left: 0x7fc390000cb0
     right: 0x7fc390010cd0
    FAILED
    
    failures:
    
    failures:
        component_controls::cold_direct_query_keeps_all_rows_without_per_row_allocations
        component_controls::cold_flattened_query_keeps_all_rows
        component_controls::direct_predicates_create_no_temporary_strings
        component_controls::flattened_predicates_create_no_temporary_strings
        warm_nonempty_queries_allocate_no_candidate_buffers
        warm_nonempty_results_share_backing
    
    test result: FAILED. 10 passed; 6 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.62s
    
    fresh-empty-arc — exact wrong-implementation diff
    --- proof/candidate_component.rs
    +++ proof/mutations/fresh-empty-arc.rs
    @@ -125,7 +125,7 @@
         }
         pub(super) fn owner_named_indices(&self, owner_name_lower: &str) -> Option<Arc<[usize]>> {
             if owner_name_lower.is_empty() {
    -            return None;
    +            return Some(Arc::from([]));
             }
             if let Some(indices) = memo(&self.owner_named_cache).get(owner_name_lower) {
                 return indices.clone();
    @@ -143,7 +143,7 @@
     
         pub(super) fn same_module_indices(&self, owner_module: &str) -> Option<Arc<[usize]>> {
             if owner_module.is_empty() {
    -            return None;
    +            return Some(Arc::from([]));
             }
             if let Some(indices) = memo(&self.same_module_cache).get(owner_module) {
                 return indices.clone();
    @@ -408,7 +408,7 @@
     }
     
     use subject::{close_module, same_module};
    -#[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    +#[path = "../../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
     mod repository_module_match_tests;
     #[cfg(test)]
     mod component_controls {
    fresh-empty-arc — complete focused test output; compile 0, test 101
    
    running 1 test
    test empty_queries_are_allocation_free_when_empty_key_or_warm ... 
    thread 'empty_queries_are_allocation_free_when_empty_key_or_warm' (6) panicked at proof/mutations/fresh-empty-arc.rs:385:240:
    assertion `left == right` failed: first empty-key query allocates
      left: (2, 32)
     right: (0, 0)
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    FAILED
    
    failures:
    
    failures:
        empty_queries_are_allocation_free_when_empty_key_or_warm
    
    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 17 filtered out; finished in 0.04s
    
    
    missing-slash-boundary — exact wrong-implementation diff
    --- proof/candidate_component.rs
    +++ proof/mutations/missing-slash-boundary.rs
    @@ -226,7 +226,7 @@
         test_module == parent
             || test_module
                 .strip_prefix(parent)
    -            .is_some_and(|rest| rest.starts_with('/'))
    +            .is_some()
             || flattened_module_rest(parent, test_module).is_some()
     }
     pub(super) fn fixture(rows:&[(String,Option<String>)])->CompactGripContext<'static> {
    @@ -408,7 +408,7 @@
     }
     
     use subject::{close_module, same_module};
    -#[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    +#[path = "../../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
     mod repository_module_match_tests;
     #[cfg(test)]
     mod component_controls {
    missing-slash-boundary — complete focused test output; compile 0, test 101
    
    running 1 test
    test repository_module_match_tests::module_match_agrees_with_literal_prefix_reading ... 
    thread 'repository_module_match_tests::module_match_agrees_with_literal_prefix_reading' (6) panicked at proof/mutations/../../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs:116:21:
    assertion `left == right` failed: same: "a/", "ax/tests"
      left: true
     right: false
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    FAILED
    
    failures:
    
    failures:
        repository_module_match_tests::module_match_agrees_with_literal_prefix_reading
    
    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 17 filtered out; finished in 0.00s
    
    
    missing-flattening — exact wrong-implementation diff
    --- proof/candidate_component.rs
    +++ proof/mutations/missing-flattening.rs
    @@ -186,9 +186,7 @@
         let rest = test_module.get(parent.len()..)?.strip_prefix('/')?;
         prefix
             .bytes()
    -        .eq(parent
    -            .bytes()
    -            .map(|byte| if byte == b'/' { b'_' } else { byte }))
    +        .eq(parent.bytes())
             .then_some(rest)
     }
     
    @@ -408,7 +406,7 @@
     }
     
     use subject::{close_module, same_module};
    -#[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    +#[path = "../../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
     mod repository_module_match_tests;
     #[cfg(test)]
     mod component_controls {
    missing-flattening — complete focused test output; compile 0, test 101
    
    running 1 test
    test component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows ... 
    thread 'component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows' (6) panicked at proof/mutations/missing-flattening.rs:484:9:
    assertion `left == right` failed
      left: []
     right: [4095]
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    FAILED
    
    failures:
    
    failures:
        component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows
    
    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 17 filtered out; finished in 0.05s
    
    
    truncate-at-128 — exact wrong-implementation diff
    --- proof/candidate_component.rs
    +++ proof/mutations/truncate-at-128.rs
    @@ -152,6 +152,7 @@
                 .name_module_candidates
                 .module_candidates(owner_module)
                 .into_iter()
    +            .take(128)
                 .filter(|&index| {
                     self.tests[index]
                         .module_path
    @@ -408,7 +409,7 @@
     }
     
     use subject::{close_module, same_module};
    -#[path = "../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
    +#[path = "../../crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs"]
     mod repository_module_match_tests;
     #[cfg(test)]
     mod component_controls {
    truncate-at-128 — complete focused test output; compile 0, test 101
    
    running 1 test
    test component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows ... 
    thread 'component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows' (6) panicked at proof/mutations/truncate-at-128.rs:487:9:
    assertion `left == right` failed
      left: []
     right: [4095]
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    FAILED
    
    failures:
    
    failures:
        component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows
    
    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 17 filtered out; finished in 0.05s
    
    
    Selected edition-2024 commands, outcomes and source/log hashes
    {
      "candidate_commit": "2a9c24f48359d67ee79c5883a503ea25a572f0b6",
      "candidate_component_sha256": "dfe79d83af1f562d437f73a6b41d8a1a04199ccc107cdec2938ea1b3db36a60d",
      "repository_test_sha256": "58c0acbb5ffd0fcd6addb0bde8f4e80232c0fc0762a7e25e5ac8f633743a837f",
      "compiler": "rustc 1.95.0 (59807616e 2026-04-14)",
      "edition": "2024",
      "compilation": "Direct rustc --test -C debuginfo=0; std only; no Cargo or network access.",
      "common_instrument_adjustment": "Only #[path] changes from ../crates/... to ../../crates/... because variants are nested one directory deeper. All variants include the same unchanged repository module_match_tests.rs.",
      "source_and_main_proof_mutated": false,
      "variants": [
        {
          "name": "fresh-empty-arc",
          "compile_command": "/home/agent/.cargo/bin/rustc --edition=2024 --test -C debuginfo=0 --crate-name fresh_empty_arc proof/mutations/fresh-empty-arc.rs -o proof/mutations/native/fresh-empty-arc",
          "test_command": "proof/mutations/native/fresh-empty-arc --exact empty_queries_are_allocation_free_when_empty_key_or_warm --nocapture --test-threads=1",
          "compile_exit": 0,
          "test_exit": 101,
          "test_count": 1,
          "passed": 0,
          "failed": 1,
          "ignored": 0,
          "filtered_out": 17,
          "observed_assertion": "First two empty-key queries allocate 2 times / 32 requested bytes; expected 0 / 0.",
          "source": "proof/mutations/fresh-empty-arc.rs",
          "diff": "proof/mutations/fresh-empty-arc.diff",
          "compile_log": "proof/mutations/fresh-empty-arc.compile.log",
          "test_log": "proof/mutations/fresh-empty-arc.test.log",
          "binary": "proof/mutations/native/fresh-empty-arc"
        },
        {
          "name": "missing-slash-boundary",
          "compile_command": "/home/agent/.cargo/bin/rustc --edition=2024 --test -C debuginfo=0 --crate-name missing_slash_boundary proof/mutations/missing-slash-boundary.rs -o proof/mutations/native/missing-slash-boundary",
          "test_command": "proof/mutations/native/missing-slash-boundary --exact repository_module_match_tests::module_match_agrees_with_literal_prefix_reading --nocapture --test-threads=1",
          "compile_exit": 0,
          "test_exit": 101,
          "test_count": 1,
          "passed": 0,
          "failed": 1,
          "ignored": 0,
          "filtered_out": 17,
          "observed_assertion": "Literal boundary oracle rejects owner \"a/\", test \"ax/tests\": mutated same_module returned true; expected false.",
          "source": "proof/mutations/missing-slash-boundary.rs",
          "diff": "proof/mutations/missing-slash-boundary.diff",
          "compile_log": "proof/mutations/missing-slash-boundary.compile.log",
          "test_log": "proof/mutations/missing-slash-boundary.test.log",
          "binary": "proof/mutations/native/missing-slash-boundary"
        },
        {
          "name": "missing-flattening",
          "compile_command": "/home/agent/.cargo/bin/rustc --edition=2024 --test -C debuginfo=0 --crate-name missing_flattening proof/mutations/missing-flattening.rs -o proof/mutations/native/missing-flattening",
          "test_command": "proof/mutations/native/missing-flattening --exact component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows --nocapture --test-threads=1",
          "compile_exit": 0,
          "test_exit": 101,
          "test_count": 1,
          "passed": 0,
          "failed": 1,
          "ignored": 0,
          "filtered_out": 17,
          "observed_assertion": "Crowded query returned []; independently required final flattened match is [4095].",
          "source": "proof/mutations/missing-flattening.rs",
          "diff": "proof/mutations/missing-flattening.diff",
          "compile_log": "proof/mutations/missing-flattening.compile.log",
          "test_log": "proof/mutations/missing-flattening.test.log",
          "binary": "proof/mutations/native/missing-flattening"
        },
        {
          "name": "truncate-at-128",
          "compile_command": "/home/agent/.cargo/bin/rustc --edition=2024 --test -C debuginfo=0 --crate-name truncate_at_128 proof/mutations/truncate-at-128.rs -o proof/mutations/native/truncate-at-128",
          "test_command": "proof/mutations/native/truncate-at-128 --exact component_controls::crowded_query_retains_last_flattened_match_and_drops_distant_rows --nocapture --test-threads=1",
          "compile_exit": 0,
          "test_exit": 101,
          "test_count": 1,
          "passed": 0,
          "failed": 1,
          "ignored": 0,
          "filtered_out": 17,
          "observed_assertion": "Crowded query returned []; independently required final flattened match is [4095].",
          "source": "proof/mutations/truncate-at-128.rs",
          "diff": "proof/mutations/truncate-at-128.diff",
          "compile_log": "proof/mutations/truncate-at-128.compile.log",
          "test_log": "proof/mutations/truncate-at-128.test.log",
          "binary": "proof/mutations/native/truncate-at-128"
        }
      ],
      "hashes": {
        "proof/candidate_component.rs": "dfe79d83af1f562d437f73a6b41d8a1a04199ccc107cdec2938ea1b3db36a60d",
        "crates/ripr/src/analysis/test_grip_evidence/related_tests/module_match_tests.rs": "58c0acbb5ffd0fcd6addb0bde8f4e80232c0fc0762a7e25e5ac8f633743a837f",
        "proof/mutations/fresh-empty-arc.rs": "cf06345970e207471fe688fed914eb3e591006170226e9540b91d01cd80d00ae",
        "proof/mutations/missing-flattening.rs": "1a2cdf8cd2b72239b4faee8709a883767dd3c6539adb3b6be9e04511af6fdce0",
        "proof/mutations/missing-slash-boundary.rs": "101efb75faa70107203a81c2b070434e2ff137c9c63d33b66256a7c6dd0da8b7",
        "proof/mutations/truncate-at-128.rs": "1a6a74da54e248743d9a3b1550aeea8ac6b65e66a1edd0e7c34a1448add6cbca",
        "proof/mutations/fresh-empty-arc.diff": "a06de54dcd87baebe63ce935ec4ba7cb0529a2985b8c6cb9f20872584e27810c",
        "proof/mutations/missing-flattening.diff": "eb0804cf18f7f60c1658aaa0635eb917c88a408d93e1cdeb4cf1dc7607eda6e6",
        "proof/mutations/missing-slash-boundary.diff": "4bbfc3b05903a2e9f1ff7477a0637d31f8d39c6593b75f6cdfe3f8fd7f72d86b",
        "proof/mutations/truncate-at-128.diff": "5de4c7ce4aed75da0d7946a0480f509aa3e19e6ee62ce75279d34026b158e70b",
        "proof/mutations/fresh-empty-arc.compile.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "proof/mutations/missing-flattening.compile.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "proof/mutations/missing-slash-boundary.compile.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "proof/mutations/truncate-at-128.compile.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "proof/mutations/fresh-empty-arc.test.log": "4524a4c02be2bdc08b15314d5116ab6ecacd3780a0c5e4c2a51a4b1546e5736d",
        "proof/mutations/missing-flattening.test.log": "fa1c9b46a5da98b9d90b77b2a9ca047722c95cb995c5782854cfc4cdaf940905",
        "proof/mutations/missing-slash-boundary.test.log": "a87130ab7084b44f280c16841c07d0b345119cd715eb12c9c22d89c5e4ed1cd8",
        "proof/mutations/truncate-at-128.test.log": "3d70837671e5289cd69d5cb2cab789366ee81224f3c5aff7d3cfa05fa9a8ba37",
        "proof/mutations/native/fresh-empty-arc": "e2ac1220764a5c4b4607c67d7334f7ea23b9092f2e020e7aadd0fda4f0fadfde",
        "proof/mutations/native/missing-flattening": "ae9f0b529f4341bb69697a801d5efa618b54d6942b850d66ce1319f2bbbd210a",
        "proof/mutations/native/missing-slash-boundary": "b85a809a02c780c3ab143f34b41b41d9e13fa8f610376360a33d9b12bf7b8e63",
        "proof/mutations/native/truncate-at-128": "ec51d5c18d5083d9d4f92b2a01952aba5ac6b0756394a95fc33b7e0d43cd590c"
      },
      "bounds": {
        "generated_binaries_bytes": 30077536,
        "current_available_bytes": 57127620608,
        "required_available_floor_bytes": 42949672960,
        "no_binaries_deleted": true
      },
      "limits": "Disposable source-extracted component controls. Not full crate typechecking, whole-repository integration, hosted CI clearance, peak RSS, or end-to-end efficiency evidence.",
      "historical_note": "Edition 2021 was an initial instrument configuration. The selected proof is the unchanged-source rerun with edition 2024; only final 2024 receipts are selected for publication."
    }
  9. removed
    status/needs-work
    on Nov 11, 2026
  10. EffortlessSteven commented on Nov 15, 2026

    @EffortlessSteven
    MemberAuthor

    #13911 landed on main as d6c9bfa. With it, the withheld indirect-owner pass skips parsing test bodies that never mention the owner. Warm check --base HEAD~3 on ripr-swarm dropped from 172.5 s to 115.2 s (medians), with byte-identical JSON. HEAD~1 is flat because that pass isn't hot there.

    Still in flight under this issue:

    I'm leaving this issue open: the edit-loop latency and memory scoreboard qualification isn't done yet.


    Generated by Claude Code

  11. EffortlessSteven commented on Nov 16, 2026

    @EffortlessSteven
    MemberAuthor

    Two more landed on main under this issue:

    Still queued:

    All of these keep the JSON byte-identical.

    A cold-run trace shows the roughly 31 s cold-only review stage (a whole-workspace inventory for the stub route's weak-oracle guidance) can't be narrowed or reused without changing results. Workspace-wide tables such as function_name_counts decide evidence filtering. The remaining cold-only costs:

    • the admission-core index_cached_parse: +10 s over warm;
    • index_test_helper_credit: about 4 s per index build, sequential;
    • the diff_drop_unreached_test_files module-tree parses: +4 s.

    Generated by Claude Code

  12. EffortlessSteven commented on Nov 16, 2026

    @EffortlessSteven
    MemberAuthor

    Reconciliation receipt — partial-continue

    Merges: cd1d1a23b4 (PR #14880, landed 2026-11-16T13:43:25Z) and 46bf55ef7b (PR #14865, landed 2026-11-16T07:44:01Z). Claim: #12947.

    Read on the landed tree, not the PR bodies:

    • cd1d1a23b4 — crates/ripr/src/analysis/classify/owner_pin.rs builds the workspace constant table through map_scans(&files, |(_, source)| file_constants(source)), so the per-file parses fan out off the pool and stay in line on a pool worker under the perf: share RelatedTestCandidateIndex memos across threads so per-probe classify can run in parallel (#8629 follow-up) #8756 guard. Test the_workspace_constant_table_fans_out_off_the_pool_with_the_same_table is present in owner_pin/tests.rs; changelog fragment 12947-parallel-workspace-constant-table.md is present. Delivered row: the cold single-seam review stage's constant-table build is parallel, output unchanged.
    • 46bf55ef7b — crates/ripr/src/analysis/syntax/bolero.rs gates the use bolero::check binding scan on a bare check path (file_binds_bolero_check, use_imports_bolero_check, is_bolero_check); changelog fragment bolero-escape-skips-binding-scan.md is present. Delivered row: the bolero escape no longer scans bindings for qualified paths.

    Remaining rows (still open under this issue):

    • The cold-only costs named in perf(owner-pin): fan the workspace constant table parse out off the pool #14880's claim boundary: first index_cached_parse (~12 s cold vs 2.2 s warm), diff_drop_unreached_test_files module-tree parses (5.1 s vs 0.9 s), the whole-workspace index rebuild for the review stage (~12 s, 668 misses), and evidence_context over 30,669 tests (~8.9 s).
    • End-to-end edit-loop latency and memory qualification against the scoreboard budgets — no landed slice has asserted the budgets now pass.

    Disposition: partial-continue. The claimed slices landed and are verified on the tree; the outcome stays open. Continuing owner: this issue's performance campaign (orchestrator ripr-swarm). Next executable slice: the cold index_cached_parse cost, the largest remaining named cold-only row, as one bounded candidate with an A/B on the same cold harness.

    No premature auto-close: the issue is open and no closing keyword was used by either PR.

  13. EffortlessSteven commented on Nov 17, 2026

    @EffortlessSteven
    MemberAuthor

    Progress on the diff-speed claim (all with byte-identical ripr check JSON on ripr-swarm):

    No ratchet in this issue is claimed as met by these alone.

    Remaining measured cold-only hot spots for the next lane:

    1. admission-core first index_cached_parse, about +10 s cold.
    2. diff_drop_unreached_test_files module-tree parses, about +4 s cold.
    3. The residual ~1.3 s of the helper-credit fold (forward-target oracles are not prefetched).

    The ~31 s whole-workspace inventory in the cold review stage is required for stub weak-oracle guidance (workspace-wide tables such as function_name_counts decide the result), so it should be made cheaper rather than narrowed.


    Generated by Claude Code

  14. EffortlessSteven commented on Nov 17, 2026

    @EffortlessSteven
    MemberAuthor

    Claiming the next lane of remaining cold hot spots from the list above, in order: (1) admission-core first index_cached_parse (~+10 s cold), then (2) diff_drop_unreached_test_files module-tree parses, then (3) the residual helper-credit fold. Byte-identical ripr check JSON on ripr-swarm is the bar; before/after timings will be posted per PR.


    Generated by Claude Code

  15. EffortlessSteven commented on Nov 17, 2026

    @EffortlessSteven
    MemberAuthor

    Lane progress (subject: detached ripr-swarm at 3603ffa, check --root . --base HEAD~1 --format json, 210 probes, interleaved release binaries with their own warm RIPR_CACHE_DIR, JSON cmp byte-identical in every pair):

    Finding: on this subject the largest cost was not in the listed cold items but in untraced probe classification (the ripr-classify-* pool): about 80 s of a 104–124 s warm run. gdb sampling attributed it as follows.

    PR change warm wall peak RSS
    #15009 (queued) test-module shadow check answers false without fetching/parsing the test file's snapshot when the file never spells the name (~60% of classify samples were snapshot re-parses or OnceLock waits after 8 MiB window eviction) 124 s → 75 s 1,955 → 1,765 MB
    #15015 (queued) implicit-dispatch checks probe the ~40-name method list against the reaching set instead of scanning the whole set per test/assertion (18% of top frames) 70 s → 64 s (on top of #15009) unchanged

    Measured and parked (no PR):

    • Listed item 1 (first index_cached_parse, cold): encoding/writing fresh fact-cache entries in parallel cut it 11.5 s → 10.3 s, about 1% of a 118 s cold run; the rest is the parse itself on 4 cores. Patch kept locally, not worth a qualification run alone.
    • Parallel ModuleDeclarations::read (serial whole-file parses before classification): 64.8 s → 62.1 s, but peak RSS rose ~50 MB (concurrent trees / per-thread arenas) even with a memo-free parse. Not taken given the memory goal.

    Remaining classify profile after #15015 (~45 s of ~62 s): spread across reveal_outcome → admits_equality_assertion → context_refusal_inner (~31% of samples: per-file owner_pin_assertions_with_default_features builds, source_provenance_refusal, macro_root_verified_in_contexts per assertion), whole-file re-parses from owner_pin.rs:15650, element_field_pin.rs:619, syntax/owner_pin.rs:983/3293 and macro_item_names.rs:71 thrashing the 4-entry per-thread parse memo, and workspace_drop_impls. No single hot line remains above ~15%.

    Listed items 2 (diff_drop_unreached_test_files, 4.6 s cold / 0.9 s warm) and 3 (helper-credit residual ~1.3 s) are still open for the next lane. No ratchet in this issue is claimed as met.


    Generated by Claude Code

  16. EffortlessSteven commented on Nov 24, 2026

    @EffortlessSteven
    MemberAuthor

    Fixed heavy workload: warmer check and editor readings moved together

    Nov 24 hosted job, analyzer 3c5dd25e9c7c69a753298957566e5ae50dd20342, vs Nov 20 hosted job, analyzer bcc5e7d98de8c2976b32c45c547c5ece49b495aa. Both use heavy consumer 8fbe8bd1598e0b11752c6c989aa54198a0510a2f, HEAD~1, draft mode, and report 131 findings. Warm check samples were [29.550, 29.914, 29.974]s then [40.235, 40.781, 40.784]s; successful edited-save refresh on crates/ripr/src/analysis/classifier/evidence.rs was 29.972s then 39.713s. Same declared Intel 4-CPU runner class, different VM images/regions. The Nov 22→23 matched AMD runner-class trend points the same way (warm 32.048→40.999s, edited save 30.692→40.238s). These are workload measurements, not commit attribution. The heavy current observation is still below the 60s workload ratchet and is not itself the reason that the nightly is red.

    Next discriminating measurement for this issue: interleave prebuilt Nov 22 (e7eff2ae65f5eace44bbc46a1fe4f35b11c58331) and Nov 23 (dbfcc9d1555f87cdb21207a56ba2df5df0086dde) analyzer endpoints on one host with the fixed consumer pin, matched build/cache settings, and the same edited-save fixture. Preserve repeated warm samples, phase timings, peak RSS, and the result/finding equivalence. That separates analyzer movement from host/run drift without repeating the full nightly, rebasing the thresholds, or taking over the existing allocation candidate. No run was dispatched.

  17. EffortlessSteven commented on Nov 25, 2026

    @EffortlessSteven
    MemberAuthor

    Nov 25 readback: the heavy warm slowdown persists, but the first two measured phases do not explain it

    Nov 22 → Nov 23: warm median 32.048 → 40.999 s, edited save 30.692 → 40.238 s. The two retained warm phase medians, diff_drop_unreached_test_files and diff_main_index, total 5.269 → 5.226 s. The trace hit its phase cap, so this rules out those two rows as the explanation for the observed +8.951 s, not any unrecorded phase. Workflow, lockfile and compiler identities match, as do AMD runner class and image; region/worker and build-cache readback differ. The endpoints are 114 commits apart, not a first-bad range attributed to code.

    Nov 25, analyzer 5000e3d6, repeats the observation at 41.865 s warm and 40.334 s edited save with 131 findings on Nov 23's region/class/image. Still below the heavy workload's 60 s bound; this is not attribution of the separate red scoreboard result or proof of byte-identical output.

    Keep the existing same-host interleaved endpoint test as the next step. Compare uninstrumented wall/peak RSS and normalized report equality first. If the gap survives, collect a separate paired trace that retains the phase rows after diff_main_index; do not use instrumented wall time as the performance verdict. No run was dispatched.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions