Skip to content

perf(check): memoize pure per-source syntax products for one diff run (#5363) - #8396

Merged
EffortlessSteven merged 4 commits into
mainfrom
claude/project-thread-xcs0up
Oct 17, 2026
Merged

EffortlessSteven merged 4 commits into
mainfrom
claude/project-thread-xcs0up

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Requested by Steven · project thread

Before: one ripr check builds six or more overlapping indexes (911–1194 files each), and three consumers re-parsed the same unchanged source text every time: the external-docs scan (includes_external_docs, via UnseenReachNames::build), same-file local test macro expansion (expand_local_test_macros) and helper-oracle extraction (parser_oracles_for_function). Main-thread stack samples put about half of the single-threaded tail in rust-analyzer parsing under those callers (profile on #5363).

After: each of those pure products is computed once per diff or repo analysis run and reused by the other index builds. Output is byte-identical.

Part of #5363 (does not close it; the 2 s target is not met).

How: new analysis/syntax/run_memo.rs, a thread-local memo keyed by (product, discriminator, sha256 of the source text). analyze_diff_for_languages_with_rust_config and analyze_repo_with_rust_config open a scope; the outermost scope's drop clears it. A thread with no scope (rayon workers, other analyses, tests) computes directly, exactly as before, so nothing outlives a run and no product can be served for changed content.

Parse-count tests: unchanged on purpose. They call UnseenReachNames::build and friends outside any scope, so they still observe one real parse per file and the "cached may_reach_unseen must not reparse" contract. The counter increments only when a parse actually runs. The new behaviour is covered by five unit tests in run_memo.rs (no memo outside a scope, once per source inside, product/discriminator in the key, outermost scope clears, type-mismatch recomputes).

Measurements (this container, 4 cores, ripr-swarm HEAD~1, --format json --quiet, warm cache, identical non-LTO profile for both binaries, interleaved, first warm-up run discarded):

wall (s) peak RSS
before (87734f6) 49.3, 50.4, 48.7, 50.0, 49.3, 50.9 639–657 MB
after 45.7, 44.7, 45.8, 44.8, 46.1 638–649 MB

About 4.5 s (9%) faster; peak RSS unchanged; JSON cmp-identical. One earlier "after" run at 58.3 s was the first run after the binary swap and is excluded as a cold outlier (reported here for completeness).

Caveats: unchanged-repeat gain only; no production/test-edit replay (#3794). Absolute times are not comparable to the 7.6 s in #5363 (different host/state). Remaining single-threaded cost is still dominated by building several overlapping indexes; the 2 s and 512 MB targets stay open.

Local proof: cargo xtask precommit exit 0; cargo test -p ripr --lib has 8 failures that are environmental in this container and do not touch this code (six chmod/unwritable-path tests that cannot fail as root, and fallible_literal_full_and_compact_warm_caches_invalidate_changed_inputs, which needs a networked cargo fetch).


Generated by Claude Code

…#5363)

A diff check builds several overlapping indexes and each consumer rescanned
the same unchanged files: the external-docs scan, same-file local test macro
expansion and helper-oracle extraction each re-parse source text. They are
pure functions of their text, so a thread-local run memo (opened by the Rust
diff and repo analyses) stores each product once per run under a digest of
its text and drops it when the run ends. Threads without a scope, including
tests, compute exactly as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EnCBJrx9WKdT9XgmUkKoua
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@EffortlessSteven EffortlessSteven self-assigned this Oct 17, 2026
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 3 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 68 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 94e7cfdb-2b56-49d5-97cf-1b8f4dbd2f81
📥 Commits

Reviewing files that changed from the base of the PR and between 6996073 and 4841e8e.

📒 Files selected for processing: 6
  • crates/ripr/src/analysis/classify/reach.rs
  • crates/ripr/src/analysis/language/rust/mod.rs
  • crates/ripr/src/analysis/syntax/local_test_macros.rs
  • crates/ripr/src/analysis/syntax/mod.rs
  • crates/ripr/src/analysis/syntax/ra.rs
  • crates/ripr/src/analysis/syntax/run_memo.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

Copy link
Copy Markdown
Member Author

In-session proof on head d6ac1b5 (CI is label-gated):

  • cargo xtask precommit: exit 0.
  • cargo test -p ripr --lib: only environmental failures (6 root-chmod/unwritable-path tests and one that needs a networked cargo fetch); run_memo (5), reach and dependent_scope tests pass.
  • A/B and byte-identical JSON are in the description.
  • Independent Sonnet subagent review of the exact head found no correctness bugs: the three products are pure in (text[, start line]); key is a length-prefixed discriminator plus SHA-256 of the text with Product in the tuple; scope depth is decremented in Drop (early returns, ?, unwinding); compute() runs unborrowed; rayon workers have depth 0 so they compute directly; the parse-count tests open no scope so their counts are unchanged. It did not run tests or the architecture gates; the first is covered above, and CI runs the rest once labelled.

Marking ready and adding merge-ready.


Generated by Claude Code

@EffortlessSteven
EffortlessSteven marked this pull request as ready for review October 17, 2026 05:35
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decision

  • Needs reviewer attention before upstream: findings remain.

Confirmed findings

  • Sibling-path calibration: the PR claims three products were re-parsed across overlapping indexes. The repo-wide caller scan is bounded to crates/ripr/src/analysis/{syntax,classify,language/rust}; other crates or future index builders that consume includes_external_docs, expand_local_test_macros, or parser_oracles_for_function from a separate thread without opening a scope will not benefit and will still re-parse. This is acceptable per the PR's "thread with no scope computes directly" contract, but worth flagging for downstream maintainers.
  • crates/ripr/src/analysis/syntax/ra.rs:124 — Wrapper docs: the /// doc comment that was on parser_oracles_for_function is now on the memoizing wrapper, leaving no doc on the _uncached body. If docs are public(crate) they still resolve to the wrapper; flag as cosmetic only.
  • Architecture: _syntax_memo binding is unused; an explicit drop(scope) on early return would be clearer, but RAII via #[must_use] RunMemoScope is equivalent and well-marked. No change required.

Verification questions

  • Confirm ra.rs diff shows pub(crate) fn parser_oracles_for_function(...) -> Option<Vec<OracleFact>> { as the wrapper signature line and the doc comment that previously sat on the function is now attached to the wrapper. This is the same route as before; no public API removed/renamed. No sibling path (e.g., rust_include_directives) is mentioned in the PR claim, and scanning the file shows it has a single in-file caller and is not rescanned across overlapping indexes.

Refuted

  • rayon workers spawned under a RunMemoScope on the parent thread could share the parent's thread_local MEMO and return a stale entry from the worker's compute().; refuted because: thread_local! storage is per-OS-thread, not propagated to spawned rayon tasks. The memoize() guard requires depth>0 on the worker's own MEMO cell, which is freshly default-constructed (depth 0), so compute() runs unborrowed on every worker; matches the five unit tests including the no-scope-equals-three-calls assertion.
  • Lane is out of scope: zero JS, async, GC, detach, or transferable handles in diff. All changes are synchronous Rust + thread_local memoization.
  • Cached Rc could leak a previous type into a current T via downcast_ref at the same key, leaking unrelated product data across types (potential info disclosure).; refuted because: Key includes Product (typed enum), so two memoize sites with the same text but different Products get distinct entries. Where Product matches but T differs, the in-call test a_stored_value_of_another_type_is_recomputed enforces recompute; distinct call sites always emit a single T so cross-T cache reuse at a stable key requires the caller's T to literally match what is stored, in which case serving the stored value is the intended behavior (no disclosure).
  • Box<[u8]>::from(slice) allocation failure will silently return None/empty and poison cache; refuted because: No such allocation introduced; memoize caches Rc from a value, never allocates bytes from a slice. Caller closure owns allocation.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

…8165)

Hosted goldens check fails on main for these eight human.txt goldens, which
still carry the pre-#8165 summary wording; this PR does not change output.
Same content as #8351, so the change is a no-op once that merges.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EnCBJrx9WKdT9XgmUkKoua

Copy link
Copy Markdown
Member Author

CI on d6ac1b5: Ripr Rust Small / Rust gates failed at cargo xtask goldens check only. The eight drifting fixtures (one_hop_field_projection*, rust_map_insert_count_empty, rust_map_overwrite_count, seeded_push_after_early_return, typescript_mock_payload_iife_impl) are human.txt goldens that still carry the pre-#8165 summary wording. This PR does not change output (JSON is byte-identical), so the drift is main's, and #8351 already re-blesses exactly these eight and is open and merge-ready.

Ported #8351's fixture changes (16 files, identical content) into this branch and merged current main; they no-op once #8351 lands. I could not re-run goldens check locally (offline container cannot prepare the fixture dependencies), so the hosted re-run on the new head is the proof.


Generated by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decision

  • Needs reviewer attention before upstream: findings remain.

Confirmed findings

  • No automated regression test pins the ~4.5s speedup or byte-identical JSON invariant; relies on PR-reported A/B measurements and human reviewer inspection of JSON cmp.
  • ripr sensor failed (exit 2) so an independent parse-call trace for includes_external_docs is missing; trust boundary is the PR claim plus the parser-oracle local test count. Mitigation: cargo-test receipt is scheduled-late and run_memo unit tests cover the cache contract for the ExternalDocs product key.
  • Helper shape is correct: thin memoize wrappers plus _uncached bodies across ra.rs, local_test_macros.rs, and reach.rs preserve purity and avoid duplication. RunMemoScope depth semantics + Drop clear-on-zero are RAII-correct and covered by five unit tests. Only residual item is the already-flagged cosmetic doc placement on ra.rs:124.
  • Fixture drift is mechanically carried by this PR but goldens check fails; the author assumes PR #8351 will land first to resolve. If #8351 is rebased/changed, this PR's fixtures drift independently.

Verification questions

  • Confirm run_memo unit tests assert cache counts via a Cell, never invoking parse_clean_source_file; they prove scope/no-scope/key semantics, not that parse counts in real callers actually drop. Parse-count tests for the three wrappers are the real oracle and are unchanged-by-design per PR body.

Refuted

  • Memoize could detach/transfer a buffer/ArrayBuffer/TypedArray into a stale view held by callers across scopes, producing an active-view use-after-free.; refuted because: run_memo only memoizes T: Clone + 'static owned Rust values returned by compute() (Vec, Vec, bool, etc.); no raw slices, no ArrayBuffer, no typed-array views, no Vec::with_raw_parts or Box<[u8]> are stored. The closure takes &str and returns owned data; no aliasing or detach surface exists.
  • Wrapper doc moved off parser_oracles_for_function body makes the public(crate) docs stale or hides behavior.; refuted because: Docs land on the memoize wrapper, which is the function exposed via pub(crate) use; rustdoc resolves to the wrapper for any external(crate) caller. The _uncached body is crate-private and has no doc requirement. The seeded review summary explicitly marked this cosmetic only.

Parked follow-ups

  • Memoized products cover all raw-source re-parse hot paths called from the three diff/repo entry points; downstream consumers operate on syntax nodes not text. Park a follow-up to audit other crates or future index builders that may also re-parse source.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.
  • The eight human.txt rewrites and CHANGELOG.md 'Pending (N)' blocks are documented as ported from #8351 to satisfy goldens check without rerunning; byte-identical JSON claim cannot be locally verified in this offline container per the author.

# Conflicts:
#	fixtures/one_hop_field_projection_discarded/expected/CHANGELOG.md
#	fixtures/one_hop_field_projection_sibling/expected/CHANGELOG.md
#	fixtures/one_hop_field_projection_wrong_sink/expected/CHANGELOG.md
#	fixtures/rust_map_insert_count_empty/expected/CHANGELOG.md
#	fixtures/rust_map_overwrite_count/expected/CHANGELOG.md
@EffortlessSteven
EffortlessSteven marked this pull request as draft October 17, 2026 14:00
@EffortlessSteven
EffortlessSteven marked this pull request as ready for review October 17, 2026 14:00
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed findings

  • Downstream crates or future index builders calling includes_external_docs / expand_local_test_macros / parser_oracles_for_function from a worker thread without enter() will still re-parse the same text; this is the documented contract but worth a code comment in run_memo.rs pointing at the calibration note from the seeded review so future maintainers do not assume scope-wide caching.

Verification questions

  • Confirm fixture drift on goldens check (eight human.txt pre-#8165 wording) is mechanical but unverifiable in offline container; CI on new head is the witness. Demote below blocking; carries from prior review.
  • Confirm run_memo unit tests use only Cell counters and a u8/u16 type-mismatch probe; no test feeds 5+ distinct Product/source shapes that approximate the real call sites to assert cache hits across distinct products, only 4 cells in the discriminator test.
  • Confirm author claim of ~4.5s speedup and byte-identical JSON lacks an automated regression gate.

Refuted

  • Cosmic-ray Box::from(&[u8]) allocation-failure objection is a false premise here: no such allocation is introduced; cache stores Rc<dyn Any> clones only.
  • Sentence accepts the seeded reviewer concern that let _syntax_memo = enter(); shadowing could be missed or dropped early.; refuted because: #[must_use = "the memo is cleared when the scope is dropped"] forces the binding; early-return drops trigger Drop (RAII), and nested scopes share entries per the the_outermost_scope_clears_the_memo test.
  • Wrapper doc drift: parser_oracles_for_function doc moved to the memoizing wrapper and the _uncached body has no doc, risking dropped cargo-doc output.; refuted because: parser_oracles_for_function is pub(crate), not part of the public surface; rustdoc for crate-internal items does not alter public API docs and the contract is captured at the wrapper where external(crate) callers resolve.
  • Box::from(slice) allocation failure does not return None; recoverable fallback claims are dropped.

Evidence gaps

  • No automated test pins the ~4.5s speedup or byte-identical JSON invariant; shipped A/B is human-measured; cargo-test receipt is scheduled-late so the 5 new tests are unverified in this wave.
  • PR description claims JSON byte-identical output and 'one parse per file' for parse-count tests; no in-repo regression test pins this invariant (review summary explicitly flagged absence).
  • PR claim of three overlapping indexes re-parsing the same text per file is not corroborated by an independent parse-call trace: ripr sensor failed (exit 2), so no per-caller parse count exists beyond the EXTERNAL_DOCS_PARSE_COUNT test counter.
  • Model proof intent was rejected by deterministic validation.

@EffortlessSteven
EffortlessSteven merged commit d2936e3 into main Oct 17, 2026
32 checks passed
@EffortlessSteven
EffortlessSteven deleted the claude/project-thread-xcs0up branch October 17, 2026 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants