Skip to content

perf(ai-vault): bound per-row bookkeeping in unlimited session scans - #20291

Merged
nwparker merged 5 commits into
mainfrom
nwparker/perf-vault-unlimited-dedup
Sep 13, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/perf-vault-unlimited-dedup

Conversation

@nwparker

@nwparker nwparker commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​189 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​189
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​69 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​57

Follow-up to #20255, which already routes every session scan (capped and unlimited) through the incremental CodexSessionCollection, so the per-batch quadratic re-deduplication this PR originally targeted is gone on main for both local and SSH scans. What remains here is the memory finding raised in review, plus scanner-level regression coverage for the load-all path.

What changes

  • CodexSessionCollection keys its winner index by the row's own sessionId string instead of a freshly built alias-key string, so an unlimited scan retains no alias key per live row. A per-alias-key map is created only for the rare session id that spans several hosts, WSL namespaces, or rollout names, which keeps admission O(1) with no rescan of same-id rows. Measured over a 50,000-row load-all corpus under --expose-gc: about 301 B/row before, about 115 B/row after.
  • The separate CodexSessionAccumulator from earlier revisions of this PR is folded into that one class. It had reintroduced a linear rival scan per insert (16,004,000 filePath reads and 1.4 s for 4,000 rows sharing one session id).
  • Tests: local and remote load-all scans through the production scanners (10,001 candidates, a late canonical alias wins, dedup visits each row at most once), capped scans still fill the unique-session budget, per-add reference-order equality against dedupeCodexSessionsBySessionId over 2,000 randomized adds, duplicate-heavy scans retain only canonical rows, shared-id admission stays O(1), and the per-row retention bound.

What this does not do

Retention is still O(live rows). The scan returns every live row, and any later candidate can alias any earlier one (candidates arrive in mtime order, not key order), so alias bookkeeping cannot be dropped early, and streaming would change the scanner's return contract. This PR shrinks the constant per live row; it does not change the asymptote.

Validation: pnpm test src/main/ai-vault (130 files, 1,106 tests), tsc -p config/tsconfig.node.json, check-changed-code-quality.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6e28b9bb-a7e8-4f32-8c13-b362f5f4acff

📥 Commits

Reviewing files that changed from the base of the PR and between 2835512 and 67f5b2c.

📒 Files selected for processing (2)
  • src/main/ai-vault/codex-session-root-dedup.ts
  • src/main/ai-vault/session-scanner-unlimited-dedup.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

CodexSessionCollection now tracks deduplication winners by sessionId and supports multiple alias keys for one session. Winner admission and replacement logic are separated into private helpers. New tests cover mocked local and remote scans, unlimited and capped results, canonical winner ordering, duplicate handling, path reads, and heap retention for large inputs.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 67f5b

Unlimited scans retain canonical session results while reducing duplicate bookkeeping, with no identified behavior regression requiring changes before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. 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 is concise and accurately identifies the main performance change: bounded per-row bookkeeping for unlimited AI Vault session scans.
Description check ✅ Passed The description clearly explains the changes, motivation, scope, performance impact, linked issue, and validation. It is substantive and on-topic, but it does not use the repository template headings …
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Guard the in-loop dedup by scan bound (local + remote) — parseSessionCandidates and parseRemoteSessionCandidates now only collapse Codex aliases each batch when Number.isFinite(args.limit), since the running unique count only matters for the capped parse budget that canStopParsingSessions enforces.
  • Unbounded scans fall back to the existing boundary dedup — scanAiVaultSessions (dedupeCodexSessionsBySessionId(parsedSessions).sort(...).slice(0, limit)) and scanRemoteAiVaultSessions already dedupe before sorting/capping, so unbounded results are unchanged while the per-batch work drops from quadratic to linear.
  • New regression test — session-scanner-unlimited-dedup.test.ts drives 10,001 synthetic candidates through both real scanners with discovery/parse mocked, asserting the mocked dedup sees <= candidates.length * 2 rows and that a late, more-canonical alias still wins for both hosts.

I traced both code paths: in-loop dedup ran after parsing, so removing it for unbounded scans does not change how many transcripts are parsed — its only prior effect was shrinking the accumulated sessions array, which the boundary dedup now does once. Capped scans are untouched (Number.isFinite(limit) is true). Capped behavior is also pinned by the new suite's budget test. dedupeCodexSessionsBySessionId selects a canonical row independent of input order, so deferring it to the end yields the same canonical set and, with a stable sort, the same ordering.

Verification: pnpm test src/main/ai-vault/session-scanner-unlimited-dedup.test.ts src/main/ai-vault/codex-session-root-dedup.test.ts → 24 passing (dedupVisits: 10001 for both hosts); oxlint on the three changed files reports no warnings.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This run re-reviewed commit 0156faa, which replaces the prior "defer dedup to the result boundary" approach with an incremental accumulator for unbounded scans.

  • Introduced CodexSessionAccumulator — streams each parsed session through the existing alias key/beat helpers, retains only canonical rows, and deletes a superseded winner's positions when a better alias arrives, releasing discarded aliases per batch instead of holding them until the boundary.
  • Wired it into both scanners behind the unbounded check — parseSessionCandidates and parseRemoteSessionCandidates construct the accumulator only when Number.isFinite(limit) is false; capped scans keep the in-loop dedup and the existing budget behavior unchanged.
  • Exported the two alias helpers — codexSessionAliasKey and codexSessionAliasBeats are now shared from codex-session-root-dedup.ts with the accumulator.
  • Added parity and memory coverage — a 500-checkpoint equivalence test comparing accumulator output to dedupeCodexSessionsBySessionId after every add, a duplicate-heavy size <= 100 retention guard, and the existing linear-visit regression assertion (visits <= candidates.length * 2).

I traced the streaming selection against the batch dedupeCodexSessionsBySessionId: positions are monotonic, so surviving rows stay in occurrence order; first-occurrence wins exact ties; and reference-duplicate winners are retained exactly as the batch filter retains them. I independently fuzzed the two implementations over 200 trials × 60 steps across varied hosts, homes, session ids, timestamps, and alias variants — parity held at every step. The result-boundary dedup still runs, but is idempotent on the accumulator's already-deduped output.

Verification: ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/ai-vault/session-scanner-unlimited-dedup.test.ts src/main/ai-vault/codex-session-root-dedup.test.ts → 26 passing (dedupVisits: 10000 for both hosts); pnpm tc:node clean; oxlint on the five changed files clean.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

- Drop the per-session alias-key string, wrapper object and positions array
  the accumulator retained for every parsed row; index winning positions by
  the row's own sessionId instead (~430 B -> ~45 B per session at 50k rows).
- Add a --expose-gc retention test asserting a 50k mostly-unique load-all
  corpus stays under 128 B of bookkeeping per session while matching
  dedupeCodexSessionsBySessionId exactly.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This run re-reviewed commit bff41f7, which reworks the unlimited-scan accumulator's per-session bookkeeping and adds a heap-retention guard.

  • Reworked CodexSessionAccumulator bookkeeping — replaced the alias-key-keyed Map<key, { session, positions[] }> (which pinned an alias key string plus wrapper object per session) with an append-only rows array plus Map<sessionId, number | number[]>, so an unbounded scan no longer retains an alias key or wrapper per session.
  • Added a heap-retention guard — a --expose-gc test drives 50,000 mostly-unique candidates (every 100th an alias of the previous) and asserts retained bytes stay under count * 128, while output still matches dedupeCodexSessionsBySessionId.

I re-derived the streaming selection against the batch dedupeCodexSessionsBySessionId and fuzzed the new accumulator by reference identity (500 trials × up to ~52 steps across varied agents, execution hosts, codex homes, timestamps, file names, and repeated references): order and element identity matched at every step, and size tracked sessions().length. The Map bucket stays a single number for the common same-key duplicate case and only grows with distinct alias keys sharing a session id, so the new pass stays linear. Result-boundary dedup still runs and remains idempotent on the accumulator's output.

Verification: ORCA_BACKGROUND_LAUNCH=1 vitest run session-scanner-unlimited-dedup.test.ts codex-session-root-dedup.test.ts → 27 passing; check-changed-code-quality.mjs eedd356 → 0 new findings, gate passed; working tree clean.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

# Conflicts:
#	src/main/ai-vault/codex-session-root-dedup.ts
#	src/main/ai-vault/remote-session-scanner.ts
#	src/main/ai-vault/session-scanner.ts
Key winners by the row's own sessionId string so an unlimited scan retains no
alias-key string per live row (301 -> ~115 B/row measured over 50k rows), and
split into a per-alias-key map only for the rare id that spans several hosts,
namespaces, or rollout names, so admission stays O(1). Fold the PR's
CodexSessionAccumulator into the collection main already routes every scan
through, and rerun its scanner-level tests against that single class.
@nwparker nwparker changed the title perf: remove quadratic deduplication from unlimited session scans perf(ai-vault): bound per-row bookkeeping in unlimited session scans Sep 13, 2026

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This run re-reviewed commit 67f5b2c — the only commit since the last pullfrog review (bff41f7) — which reworks CodexSessionCollection's per-row bookkeeping and extends its tests.

  • Reworked the collection's indexing — replaced the alias-key-keyed bestByKey map with a sessionId-keyed map holding either the single alias winner or, for the rare id spanning several hosts, namespaces, or rollout names, a nested per-alias map. A live row no longer pins an alias-key string; the key is computed transiently instead.
  • Preserved batch-equivalent selection — the per-alias contest fold is unchanged: first-occurrence wins ties, a beating row releases its predecessor's rows, and every occurrence of the winning object reference is retained, so order and element identity still match dedupeCodexSessionsBySessionId.
  • Extended the tests — added a same-sessionId-across-4000-rollout-names case bounding filePath reads, expanded the parity loop to 2000 steps with a fork-name/invalid-date variant, and relaxed the heap-retention threshold to count * 160 bytes.

Verification: the repo's own config/scripts/session-dedup-batches-benchmark.mjs --verify-only matched dedupeCodexSessionsBySessionId by reference identity and order across 40,000 randomized differential batches; vitest run --config config/vitest.config.ts on codex-session-collection, session-scanner-unlimited-dedup, and codex-session-root-dedup → 35 passing (dedupVisits: 10000, ~47/64 ms scans for 10,001 candidates); check:code-quality:changed passed with 0 new findings.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit f2b6434 into main Sep 13, 2026
28 checks passed
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.

1 participant