Skip to content

perf(check): store module item scopes in file facts; memo helper oracles (#5363) - #6993

Merged
EffortlessSteven merged 1 commit into
mainfrom
claude/memory-efficiency-p9g94v
Oct 7, 2026
Merged

EffortlessSteven merged 1 commit into
mainfrom
claude/memory-efficiency-p9g94v

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Requested by Steven · memory efficiency thread

Summary

Before: on every warm ripr check, same-file helper crediting reparsed each test file to find module scopes, and reparsed a helper body's assertions once per test that called it. On ripr-swarm (pin 7c64b9c, 4 cores) that phase took about 1.4 s of a 6 s warm check.

After: the parser producer stores each file's compact module item scopes in the file facts, the file-fact cache keeps them (schema 1.31 to 1.32), and helper oracles are parsed once per run. The helper phase drops to about 0.4 s, the warm check to about 4.4 s, and the JSON output is byte-identical to main's.

How:

  • ModuleItemScopes gets a row-form serde wire (one row per fn) because its tuple-keyed maps cannot serialize as JSON object keys. retain_names trims the stored call and binding sets to names that crediting can ask about (the file's function names plus their call names).
  • FileFacts.item_scopes: Option<Box<ModuleItemScopes>> (boxed to keep FileFacts small). It is None from the lexical fallback and from hand-built facts, and in that case crediting parses source itself as before.
  • A per-run memo is keyed by (file, helper start line, helper name). unique_assertion_helper already requires one definition per name in the file, so the key names one body.

Swarm / Source Boundary

  • ordinary feature, analyzer, editor, docs, spec, fixture, badge, dependency, or repo-ops development for ripr-swarm

Source-of-truth Links

Governing issue or accepted claim: #5363 (warm check on ripr-swarm), after #6977.
Acceptance delta (one sentence): a warm check skips the per-test-file reparse in helper crediting and keeps identical output.

Candidate Relationships

Candidate branch: claude/memory-efficiency-p9g94v, restarted from main 4233a0a.
Stack parent or prerequisite PR: none. #6969 caches macro sites and does not touch this pass.

Scope Classification

  • One production behavior (helper-crediting performance, with a file-fact cache schema bump)

Production delta: stored scopes in file facts plus the file-fact cache, and a helper-oracle memo.

Single acceptance criterion: helper crediting gives the same answers from stored scopes as from a fresh parse.

Non-goals: the cached_parse integrity digest (about 0.9 s) and test_styles (about 0.5 s). #5363's 2 s bar is not reached yet.

Support-tier Impact

  • none

Policy Impact

  • none

Proof

cargo test -p ripr --lib -- test_helpers seam_cache file_fact   # 169 passed on dfffd5d4
cargo clippy -p ripr --all-targets -- -D warnings                # pass
cargo xtask precommit                                           # pass on dfffd5d4

Measurement: ripr check --root . --base HEAD~1 --format json on ripr-swarm pin 7c64b9c, with RIPR_REPO_EXPOSURE_LATENCY_TRACE=1.

run wall helper_credit cached_parse
main + #6977, warm 5.7 to 6.2 s 1.24 to 1.49 s about 1.0 s
this PR, warm 4.3 to 4.5 s 0.37 to 0.52 s about 0.9 s
this PR, first run after the schema bump 11.1 s n/a 7.2 s (cache rebuild)

The JSON is byte-identical (cmp) to a main build's output on the same pin. Peak RSS is unchanged at about 456 MB.

New test the_parser_stores_the_scopes_crediting_would_parse_and_the_cache_keeps_them checks four things:

  • the stored scopes equal a fresh module_item_scopes parse on every map crediting reads;
  • every name crediting asks about agrees between the two;
  • retain_names drops an unrelated binding;
  • the scopes survive a JSON round trip.

Claim Boundary

May claim: a warm check is faster on ripr-swarm by about 1.5 s with identical output.
Must not claim: #5363's 2 s target or any cold-run improvement. The first run after upgrade is slower once, because the file-fact cache is rebuilt.

Rollback

Revert the squash commit. The cache schema goes back to 1.31, and 1.32 entries are rebuilt.

Engineering Check

  • No new panic, unwrap, expect, todo, or unimplemented in production code.
  • No new panic, unwrap, expect, todo, or unimplemented in tests.

CI Economics

n/a

🤖 Generated with Claude Code

https://claude.ai/code/session_01Y7KT6sUzaJXqPAehHnLJQC


Generated by Claude Code

Parser-backed file facts now carry the compact module item scopes that
same-file helper crediting reads, so a warm run no longer reparses every
test file, and each helper body's assertions are parsed once per run
instead of once per calling test. File-fact cache schema 1.31 -> 1.32.

On ripr-swarm (pin 7c64b9c) the warm check drops from about 6 s to about
4.4 s with byte-identical JSON (#5363).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y7KT6sUzaJXqPAehHnLJQC
@EffortlessSteven
EffortlessSteven marked this pull request as ready for review October 7, 2026 09:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-07T09:23:37.315876Z dfffd5d Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 0bb60928-90f7-4db9-975e-65815f788ea5
📥 Commits

Reviewing files that changed from the base of the PR and between d506aa5 and dfffd5d.

📒 Files selected for processing (13)
  • changelog.d/5363-stored-helper-scopes.md
  • crates/ripr/src/analysis/classify/transitive_reach.rs
  • crates/ripr/src/analysis/facts/index.rs
  • crates/ripr/src/analysis/facts/model.rs
  • crates/ripr/src/analysis/facts/test_helpers.rs
  • crates/ripr/src/analysis/facts/test_helpers/tests.rs
  • crates/ripr/src/analysis/language/rust/lexical_test_grip.rs
  • crates/ripr/src/analysis/probes/classify/declarations.rs
  • crates/ripr/src/analysis/seam_cache.rs
  • crates/ripr/src/analysis/syntax/lexical.rs
  • crates/ripr/src/analysis/syntax/ra.rs
  • crates/ripr/src/analysis/test_grip_evidence/tests.rs
  • docs/OUTPUT_SCHEMA.md
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.


Summary by CodeRabbit

  • Performance

    • Warm checks now complete faster by reusing cached analysis and avoiding repeated parsing of test helpers.
  • Compatibility

    • The cache format has been updated. Existing cached data will be rebuilt the first time you run checks after upgrading; subsequent runs can use the updated cache.
  • Reliability

    • Cached analysis retains the same results as a fresh run.

Walkthrough

The parser now stores compact module item scopes in file facts. Same-file assertion helper crediting reuses those scopes and caches parser-backed helper results. The file-fact cache schema advances to 1.32.

Changes

Stored module item scopes

Layer / File(s) Summary
Collect and filter module item scopes
crates/ripr/src/analysis/syntax/ra.rs, crates/ripr/src/analysis/facts/model.rs
ModuleItemScopes gains a row-based serialization format. The parser collects scopes from its existing parse and stores filtered scopes in FileFacts.
Propagate scopes through file facts and cache
crates/ripr/src/analysis/facts/model.rs, crates/ripr/src/analysis/facts/index.rs, crates/ripr/src/analysis/syntax/lexical.rs, crates/ripr/src/analysis/seam_cache.rs, crates/ripr/src/analysis/classify/*, crates/ripr/src/analysis/language/rust/lexical_test_grip.rs, crates/ripr/src/analysis/probes/classify/declarations.rs, crates/ripr/src/analysis/test_grip_evidence/tests.rs, docs/OUTPUT_SCHEMA.md
File facts and the index serialize, store, and reconstruct optional scopes. Fallback and fixture facts initialize or preserve the field. The file-fact cache schema changes from 1.31 to 1.32.
Reuse scopes for helper crediting
crates/ripr/src/analysis/facts/test_helpers.rs, crates/ripr/src/analysis/facts/test_helpers/tests.rs, changelog.d/5363-stored-helper-scopes.md
Helper crediting uses stored scopes when available and caches parser-backed helper results. A regression test checks parsed scope data and serialization. The changelog reports warm-check timing and JSON comparison results.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Merge Risk: ⚪ Minimal · up to dfffd

The scope cache preserves the checked fallback behavior, and no issue remains that would prevent merging after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to dfffd

The change is limited to cached analysis metadata and per-run memoization. Existing helper eligibility checks and cache invalidation remain in place. No introduced security issue was established, but correctness still relies on trusted cache writers.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected path affects analysis results for indexed repository files. Repository text supplies parser input; manipulating accepted cache payloads additionally requires write access to the cache. The traced consumers classify evidence rather than execute credited helpers or grant runtime privileges.

Security Findings and Attack Paths

  • inferred — An inconsistent accepted scope payload could alter helper-crediting decisions because Some(item_scopes) is not cross-checked against source. This inherits the existing trusted-writer cache model: the base already accepted semantically rewritten source with a recomputed unsigned digest. No introduced expansion of that writer’s effective authority was established.

Trust Boundaries and Controls

  • observed — Existing helper controls remain before memoized oracle consumption: unique same-file definition, evidence-only source role, matching module scope, direct call, no shadowing or bound-name collision, plain helper body, and non-overlapping spans. The memo does not persist across runs.

Resilience and Maintainability Implications

  • inferred — Normal rebuilds begin from cached raw file facts and apply helper crediting once after role authorities, so credited assertions are not accumulated in the file-fact cache across runs. Repeating crediting on an already widened index is not inherently idempotent, but that append behavior predates the PR and no new repeat caller was identified.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 10 files. (3 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: storing module item scopes in file facts and memoizing helper-oracle parsing to improve performance.
Description check ✅ Passed The description covers the change, scope, acceptance criterion, measurements, proof, claim boundary, rollback, and CI impact. It does not complete the Spec-Test-Code Traceability, Static Language Chec…
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 10 files. (3 skipped: 2 unsupported, 1 too large.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit found scopes tucked away,
So helpers need parse once, not each day.
The cache now keeps what the parser has seen,
And tests check each row stays true and clean.
Schema numbers hop to one point three two,
Then the rabbit leaves a small carrot for you.

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

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes the performance of ripr check on large workspaces by storing each file's compact module item scopes in the parser-backed file facts, eliminating the need to reparse test files on cache hits during same-file helper crediting. Additionally, helper bodies are now parsed once per run rather than once per calling test. These changes require bumping the file-fact cache schema version to 1.32. There are no review comments, and the implementation is clean and well-tested.

@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 verification checks before upstream.

Verification questions

  • Confirm helper_oracles memo key omits a body digest, so two files with same (name, start_line) could collide.
  • Confirm the serialize_struct field-count literal was bumped to 11 but the struct has 12 named fields (path, functions, tests, module_declarations, unresolved_property_macros, role_provenance, source, item_scopes, plus tests, functions). The count is a hint to serde_json and not validated, so it is not a bug, but it is a lying comment-magnet: future field additions will silently keep the wrong hint.

Refuted

  • Boxed Option<Box> on FileFacts is an unbounded memory bloat on large files because the cache keeps every parsed scopes struct resident.; refuted because: retain_names trims direct_calls and bound_names to function-names-plus-call-names; FnItemScope is one enum row per fn. On ripr-swarm peak RSS is unchanged at ~456 MB per the PR body measurement; Box keeps the None case zero-cost and the Some case a single heap allocation shared via Arc-style reuse across the FileFacts field.
  • FileFactsView serializer declares 11 fields but tests in transitive_reach/ra/lexical_test_grip construct FileFacts via fields; serde counts struct fields, not wire tuple, so the literal is unused but harmless.
  • The helper_oracles memo key (file, helper.start_line, helper.name) is not unique when a file contains a nested fn and a top-level fn with the same name and same start line, or when a name is duplicated across modules with same start line — memo could serve the wrong assertions.; refuted because: unique_assertion_helper already requires exactly one definition per name in the file, and the diff comment states this. The triple key plus the unique-per-name precondition makes the key a singleton in practice; even if two distinct helpers shared the key, the OR insertion would still produce the same oracle set since both helpers would have parsed the same body.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Review of record

Head: dfffd5d4648fe2e1c0a4fa6f6819c59bdbc2e78d. CI is green: Ripr Rust Small Result and Rust gates passed, and the merge state is clean with no open review threads.

Angles reviewed:

  1. Correctness: an independent read-only reviewer agent checked this.
    • Stored scopes against a fresh module_item_scopes: the producer and parse_clean_source_file apply the same nesting refusal and edition-fallback parse, and both require zero errors.
    • Every name crediting looks up survives retain_names. It only asks about names that unique_assertion_helper accepted, or names from helper.calls.
    • Lexical-fallback files and hand-built facts store None and use the fresh parse, as before.
  2. Cache and schema: the row-form wire round-trips without loss, the integrity digest covers the new field, and the bump to 1.32 is pinned in the test and in OUTPUT_SCHEMA.md.
  3. Memo key: unique_assertion_helper allows one definition per name in the file, so (file, start line, name) identifies a single body.
  4. Tests and parity:
    • The new test compares stored scopes with a fresh parse, field by field and name by name.
    • The warm-check JSON on ripr-swarm pin 7c64b9c is byte-identical to main's.
  5. Bots: CodeRabbit, Devin, Gemini and Codex reported no findings.
    • ub-review raised two verification questions. Both are refuted from source:
      • The memo key is unique by the precondition above.
      • The serialize_struct("FileFacts", 11) count matches the 11 fields serialized in index.rs.

Findings: nothing blocking. Two optional notes from the reviewer agent stay as they are:

  • The oracle .clone() is needed because the assertions are moved into the credited test.
  • Scopes are stored for every parser-backed file. The cache size on ripr-swarm did not move measurably, so I kept it simple.

Merging.


Generated by Claude Code

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