Skip to content

perf(index): release builder slack when an index is finalized (#5363) - #9576

Merged
EffortlessSteven merged 6 commits into
mainfrom
perf/index-shrink
Oct 22, 2026
Merged

EffortlessSteven merged 6 commits into
mainfrom
perf/index-shrink

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Summary

  • The parse producers push facts one at a time, so fact vectors and strings in a finished index carry spare capacity. RustIndex::finalize now shrinks the arenas, each fact's vectors and strings, and the per-file vectors once the index is complete (a finished index never grows).
  • Measured with a counting allocator on this repository's cold index (2,062 files, 48,051 functions, 19,301 tests, 817,975 probe shapes): live heap 427.6 MB before, 374.3 MB after, one build. The same index measured by exact-capacity clone() is 254.8 MB plus 57.8 MB of source, so most of the remaining difference is Arc-shared call text (about 30 MB, 530k allocations) and non-cloned state, not slack.
  • Cold pilot --mode ready peak RSS was 1,237 MB on this build against 1,202 to 1,292 MB on earlier main runs, so one run does not show a peak change. The peak is inside evidence_for_seams (see the cold-pilot-memory findings); this change lowers what the index holds during it.

Swarm / Source Boundary

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

Source-of-truth Links

Proposal: none
Spec: none (no behavior change)
ADR: none
Plan item: none
Governing issue or accepted claim: #5363, #7220
Acceptance delta (one sentence): A finalized index holds no spare vector or string capacity.

Scope Classification

  • One production behavior

Production delta: analysis/facts/index.rs (RustIndex::finalize calls release_build_slack).

Evidence/support delta: test finishing_an_index_releases_the_spare_capacity_the_builders_left; changelog fragment.

Single acceptance criterion: after finalize, no counted fact vector or string has capacity above its length.

Non-goals: call-text sharing (about 30 MB), probe-shape field widths (88 B each, 72 MB), the evidence-phase peak.

Support-tier Impact

  • none

Policy Impact

  • none

Proof

cargo test -p ripr --lib -- finishing_an_index moved_large_payload union_mutation   # 3 passed
cargo xtask precommit                                                                  # exit 0

Mutation check: with the release_build_slack call commented out, the new test fails. The existing pointer-identity tests (moved_large_payload_has_one_backing_through_both_ordered_views) still pass.

Claim Boundary

May claim: the finished cold index holds about 53 MB less live heap on this repository. Must not claim: a peak-RSS reduction, or a change in index build time (not separately measured; the added work is one pass of shrink_to_fit over the facts).

Rollback

Revert the squash; no format or schema change.

Spec-Test-Code Traceability

  • Tests: the test above plus the existing index tests
  • Code: analysis/facts/index.rs

Static Language Check

  • Static output avoids killed, survived, untested, proven, and adequate.

CI Economics

n/a

Engineering Check

  • No new panic, unwrap, expect, todo, or unimplemented in production code.
  • No new panic, unwrap, expect, todo, or unimplemented in tests.
  • Errors are reported with actionable context.

Generated by Claude Code

@EffortlessSteven
EffortlessSteven marked this pull request as ready for review October 22, 2026 07:58
@coderabbitai

coderabbitai Bot commented Oct 22, 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 58 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 103 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
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 7f6039e9-f0b7-434f-bea2-824c3aedbc3c
📥 Commits

Reviewing files that changed from the base of the PR and between dc7c36f and 6f25b54.

📒 Files selected for processing: 3
  • changelog.d/9518-release-index-build-slack.md
  • crates/ripr/src/analysis/facts/index.rs
  • crates/ripr/src/analysis/facts/index_tests.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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 introduces a memory optimization to release spare capacity in the Rust fact index once building is finished. It implements a release_build_slack method that calls shrink_to_fit() on various vectors and strings within the index, and adds a corresponding test suite to verify the capacity reduction. The review feedback suggests expanding the spare_capacity test helper to include all the fields that are shrunk in release_build_slack, ensuring the test is fully robust and covers all optimized collections.

@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 found 3 potential issues.

Devin Review

Comment thread crates/ripr/src/analysis/facts/index.rs Resolved
Comment thread crates/ripr/src/analysis/facts/index.rs Resolved
…vectors, cover every shrunk field in the test (#5363)

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

Copy link
Copy Markdown
Member Author

Review of record, head 9f9932b

Angles: (1) correctness and edge cases, (2) tests and regressions, (3) spec/contract and cancellation.

An independent reviewer inspected 667fe9d. Its findings, plus the Gemini and Devin threads, were applied in 9f9932b:

  • The slack pass now covers the membership and role-provenance vectors and the inner strings of calls, returns, literals and assertions. The spare_capacity test helper counts every shrunk field, and the test fails if any is left with spare capacity.
  • The slack pass checkpoints every 4096 facts and files, so deadline cancellation still holds. The new test finalization_observes_deadline_while_releasing_build_slack is mutation-checked. The existing finalize-deadline test still passes.
  • The allocator-dependence thread: the test asserts on requested capacity after shrink_to_fit, which is the contract Rust documents for the slack-free case in these tests. I left it as is and replied with the reasoning.

Measured: cold index live memory 427.6 → 374.3 MB. Peak RSS on the cold pilot is unchanged within noise (about 1.2 GB), because the peak sits in evidence_for_seams, which the memory thread owns. This PR does not claim a peak-RSS gain.

cargo xtask precommit is green locally on this head. CodeRabbit and Gemini rate-limit comments count as missing review from those providers, not clean review. The required check is requested next.


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 one verification check before upstream.

Verification questions

  • Confirm checkpoint stride 4096 with if visited % N == 0 still observes cancellation at index 0, so a one-fact index aborts on first check.

Refuted

  • Box::from(slice) allocation-failure path in this PR; refuted because: PR diff does not touch Box::from or any slice-to-box conversion; this objection is out of scope and not raised by diff or seeded thread.
  • Exact zero capacity is allocator-sensitive, but the project explicitly accepts this as a regression signal for the crate's std global allocator.
  • Exact-capacity assertions could produce allocator-dependent failures unrelated to the release behavior.; refuted because: This limitation is acknowledged in the seeded review; with the crate's std global allocator, shrink_to_fit is intended to yield the requested exact length, and the test is designed to flag any platform contract violation.
  • The exact-capacity assertion is an invalid test because allocator behavior can retain capacity.; refuted because: The repository uses the standard global allocator; the test intentionally treats retained capacity as a failure of the documented shrink contract.

Parked follow-ups

  • The test helper is intentionally coupled to the production shrink inventory, making omission detection effective but requiring future buffer additions to update both sites.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Verification answer for the github-actions review: yes. Each of the three loops checks visited % SLACK_CHECKPOINT_STRIDE == 0 with visited starting at 0 (enumerate()), so the first fact, test or file always hits a checkpoint and a one-fact index aborts on the first check. An index with no facts has nothing to iterate, and finalize ends with its own checkpoint() after the slack pass. finalization_observes_deadline_while_releasing_build_slack exercises the in-pass path.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Ripr Rust Small Result failed on 9f9932b, but not because of this PR. The failing test is reports::verdict_corpus::known_false::tests::wiring_accepts_the_committed_ledger_against_blessed_rows in xtask, and its output names three Rust ledger entries that are no longer false verdicts (shape-op-add-impl, shape-drop-impl-side-effect, shape-dyn-trait-method-exact). Those entries are on main already. This PR only touches facts/index.rs, its tests and a changelog fragment. Every other gate on this head passed (fmt, precommit, clippy, workspace check, all-features check). The ledger drift is being fixed in #9588, which is merge-ready and in flight. Once it lands I'll re-apply merge-ready here to re-run the check on the same head, then merge on green.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Independent static review of current 9f9932b found two regression-proof gaps, not a demonstrated production failure. Please keep repairs with this existing owner.

  1. The cancellation test expires on checkpoint invocation13 and asserts DeadlineExceeded/count13. Removing interior checks can shift that same expiration to the final checkpoint after the pass and still satisfy both assertions. The fixture also remains below stride4096. Use a deterministic phase-local trigger plus an observable untouched-work/slack assertion, including a later stride boundary; removal of the interior check must fail for doing work past the allowed boundary, not just alter a global count.

  2. Capacity accounting covers the shrink inventory, but the fixture does not populate every inner field: plain functions lack impl attributes/nested functions, and provenance edges/declaration strings are not explicitly populated/reserved. A reported impl_attrs-vector mutant proves one site, not any shrink call. Populate representative nested fields and bind each claimed mutation to a field-specific observation, or narrow the claim. Avoid exact allocator-capacity assumptions; distinguish dispatch/traversal proof from actual reclamation.

Retain existing hosted qualification while preparing the bounded repair; review the successor independently and requalify only applicable changed scope. Keep the measured claim at one-build live heap427.6->374.3MB, not peak RSS or speed. No duplicate writer or benchmark campaign requested.

… each checkpoint and field (#5363)

The cancellation test now drives the pass with a small stride and expires each interior checkpoint in turn, asserting later work stays untouched. The capacity test populates every nested collection and names the field that was not released.

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

Copy link
Copy Markdown
Member Author

Both regression-proof gaps from the static review are repaired on the same branch (test commit 9f9827e, merged with current main as 4b68ace). cargo xtask precommit is green on the test commit. Production change: only a release_build_slack_in_strides(stride) seam that release_build_slack calls with the existing 4096 stride.

  1. Cancellation. The old test expired a global checkpoint count that the final finalize checkpoint could also satisfy. The new test calls the pass directly with stride 2 over 8 functions, 4 tests and 1 file, expires each of its checkpoints in turn, and asserts the pass returns DeadlineExceeded at exactly that checkpoint, with earlier facts released and later ones untouched. Removing the interior check from the test loop fails it ("test work at checkpoint 4"). The original finalize ordering test is kept.
  2. Capacity. The fixture now populates and reserves room on every nested field the pass shrinks (impl attrs, nested fn names, let bindings, literals, observed tokens, provenance edges and their declarations). spare_by_field reports spare per labelled field. The test asserts every field has room before and strictly less after, so it names the field whose shrink stopped running and does not assume exact capacity. Deleting the impl_attrs, edge declaration, observed-token or file.functions shrink each fails it.

An independent review of this head is running. Once it returns I'll re-apply merge-ready; the required check failure on the earlier head was the known_false ledger drift, now fixed on main by #9588. The measured claim stays at one-build live heap 427.6 → 374.3 MB, not peak RSS or speed.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Independent source review at4b68ace7911f158a8ef21a726d4ffbc1b7eb2feb materially closes the two proof gaps raised in6337517394. The successor adds a direct-pass phase-sensitive cancellation oracle and populated, per-label capacity fixtures; the owner's four site-specific mutation receipts remain four-site evidence, not an exhaustive any-site claim.

The injected stride2 test is legitimate bounded later-boundary coverage: production release_build_slack directly delegates to the same release_build_slack_in_strides algorithm with SLACK_CHECKPOINT_STRIDE=4096, using the same visited % stride checks. A new4096-sized campaign is not required merely to duplicate that algorithm. The remaining capacity==len marker is a portability fragility, not an established production defect or blocker to this bounded repair.

No blocking finding in this delta review. This is source review, not independently executed tests. Current-head ub-review39762274423 and wheel39762274476 were still running; skipped workflows do not establish qualification. Please preserve the existing validation/owner flow and reconcile exact-head required gates before merge.

Copy link
Copy Markdown
Member Author

Next existing-owner gate after source review6338586471: please bind integration validation to current merge head4b68ace7911f158a8ef21a726d4ffbc1b7eb2feb, or document exact-tree equivalence and relevant base coverage from the retained local receipt. The reported precommit receipt names pre-merge9f9827e5; it must not silently stand in for current composition. Wheel39762274476 succeeded while CI/security workflows skipped and ub-review remained running at observation.

Once current integration and independent review prerequisites are satisfied, use the existing required-check admission flow once and retain its actual checkout identity. Reconcile work already running before triggering anything; no duplicate campaign is requested.

@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

  • crates/ripr/src/analysis/facts/index_tests.rs:708 — spare_by_field adds the file's own file_returns/file_literals/spare under file.* and a per-edge declaration, but facts.probe_shapes is reserved yet the membership helper doesn't include self.files.values() entries' own per-file positions — fine, but a deleted membership shrink on the four flat vectors currently shows up only via the before/after strict-less rule, not a field-specific mutation. Add a focused mutation: comment out the membership shrink in the test, expect function_order or function_positions to appear in unreleased.

Refuted

  • The optimization crosses a broader abstraction boundary or requires generalizing all index storage compaction.; refuted because: Rejected: the helper is private to RustIndex and directly enumerates only growable fields on this concrete index; no shared abstraction or unrelated caller is changed.
  • shrink_to_fit exact-capacity assertions depend on allocator behavior and are not a valid test.; refuted because: Refuted: crate forbids unsafe_code so only the std global allocator is in use; the test intentionally treats retained capacity as a contract violation, which is the desired regression signal. Author's stance in seeded thread is consistent with this lane's read.

Parked follow-ups

  • ast-grep structural pass detected no sibling shrink_to_fit/insertion routes outside the changed files within the changed surfaces; this lane did not re-run ast-grep, relying on the cached receipt (ok). Public callers of finalize are not broadened by this diff.
  • The change adds one compaction pass whose reallocation cost is not measured; this is bounded performance risk rather than a demonstrated correctness defect.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Head is now 6f25b54 (test commit plus a merge of current main). merge-ready is applied once for this head; the earlier required-check failure was main's known_false drift, fixed by #9588.

Changes since 4b68ace, test file only: an independent review found that the per-element capacity labels (fn.return.text, file.return.text) only exist if the fixture holds a return fact, and the fixture did not, so those two shrink loops were unchecked. The fixture now pushes a ReturnFact on the function and the file, and the test pins the label count at 47, so a field the fixture stops populating fails there instead of dropping out. Mutation receipts (each fails finishing_an_index_releases_the_spare_capacity_the_builders_left): removing the function and file ret.text shrinks, and, answering the bot's request, removing the function_order, test_positions or function_records shrink. Earlier receipts: impl_attrs, edge declaration, observed token, file.functions, and the test-loop interior checkpoint (stride test). These are per-site receipts, not an any-site proof.

Validation binding: cargo xtask precommit exited 0 on the test-only commit before the main merge. The main merge brings in no change to facts/index.rs or its tests (the PR diff against main is still the changelog fragment, index.rs and index_tests.rs), and the hosted required check runs on the actual merged checkout, which is the integration validation for this head. I'll merge only after that check is green on this exact head.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Independent bounded delta review at6f25b54bd2e92165a0aa34753819e973e3da8274 finds no blocker. Test commit4bf7f4a adds function/file ReturnFact fixtures and pins47 capacity labels; production index source is unchanged, and the subsequent main merge leaves both index files identical to4bf7. This extends the prior source review rather than restarting it.

Required admission is already active:39768558670 admitted expected head6f25b54, with hosted Rust job119790292006 running. Preserve that single campaign, reconcile any current-head ub-review findings and verify its actual checkout plus terminal required result before merge. No additional label reapplication or dispatch is needed. Current local/test claims remain separate from hosted qualification.

@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

  • release_build_slack is private and only called from finalize; the shrink-to-fit guarantee is implicit. A doc comment on RustIndex::finalize stating that a finalized index holds no spare capacity would protect future callers who build an index without going through finalize.

Verification questions

  • Confirm exact-capacity assertions in spare_by_field depend on std::alloc::Global returning len==cap after shrink_to_fit; this is the crate's only allocator (forbid(unsafe_code)) so it is the platform contract, but a future custom alloc would silently fail the test rather than flag the shrink omission.
  • Confirm release_build_slack is not called from any other code path; if a future caller builds a RustIndex without invoking finalize, the new slack-free contract is silently broken. Documented only in PR body, not in a doc comment on finalize or on RustIndex.
  • Confirm checkpoint ordering across the three loops: if a deadline expires between the function-loop's last checkpoint and the test-loop's first checkpoint, work past the boundary is observed only by the final finalize checkpoint (test count=13). The added test pins this to expire_at=12, which is the first interior checkpoint, so the later-boundary path is not independently exercised at production stride.
  • Confirm per-site mutation receipts are documented but not exhaustive across the 47 labelled fields; fixture-pin (47 labels + before-empty check) and per-field strict-less rule give strong but not any-site proof. Not a blocker; surfaced for visibility.

Refuted

  • Box::from(slice) allocation-failure path could regress inside release_build_slack.; refuted because: PR diff does not touch Box::from or any slice-to-box conversion; release_build_slack only invokes Vec/String::shrink_to_fit, which return unit. Out of scope and not raised by diff or seeded thread.
  • A sibling path also releases build slack and was missed by this PR; refuted because: Grep across crates/ripr/src/analysis/facts/ for shrink_to_fit, compact, trim, and capacity()-len shows only the new release_build_slack implementation; no other helper or call site exists in this module.
  • release_build_slack belongs at a higher abstraction (free fn / trait) so other index backends can reuse it; refuted because: Helper is private to RustIndex and enumerates only fields on this concrete index. The PR is bounded to one production behavior; no shared abstraction or unrelated caller is changed. Smaller complete fix stays inside the impl block.
  • Exact-capacity shrink_to_fit assertions are an invalid test because allocators may retain capacity; refuted because: crate forbids unsafe_code and uses only the std global allocator; the test is designed to flag any platform where the documented shrink_to_fit contract stops holding, which is the regression signal the author wants. Devin/gemini concerns were resolved-checked in the seeded thread.

Evidence gaps

  • ripr sensor failed (exit 2) and cargo-test is late; no fresh execution evidence on current head 6f25b54, but seeded owner receipts show passing cargo test -p ripr --lib on the test commit and green precommit (comments 10:20, 11:10).
  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Independent reconciliation of later review5613515752 against current6f25b54bd2e92165a0aa34753819e973e3da8274: the asserted between-loop cancellation hole is not present. Each function/test/file loop checks at visited=0 before processing its first nonempty fact, and the stride2 test iterates checkpoints across all three passes. The earlier count13 test is not the only discriminator. Current per-label capacity checks require decrease rather than universal exact-zero allocation; retain the separate cancellation-marker portability caveat already documented.

The remaining finalize-doc location suggestion is limited documentation: slack release is documented on the private helper but could also be mentioned on finalize. No new production blocker is established by that suggestion or by unexecuted exhaustive per-site mutants. Relevant source: index.rs646-800 and index_tests.rs878-1051 at this exact head.

Current hosted qualification is still separate and must finish. Its eventual success must not erase the separately failed sensor/model-proof attempt; retain each outcome on its own subject. Source clearance6339501271 remains applicable.

@EffortlessSteven
EffortlessSteven merged commit afcfbf8 into main Oct 22, 2026
48 checks passed
@EffortlessSteven
EffortlessSteven deleted the perf/index-shrink branch October 22, 2026 12:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants