Skip to content

oom(14/29): bound AI Vault discovery, readers & caches - #10307

Closed
nwparker wants to merge 1 commit into
oom/13-b-daemon-ptyfrom
oom/14-b-ai-vault
Closed

nwparker wants to merge 1 commit into
oom/13-b-daemon-ptyfrom
oom/14-b-ai-vault

Conversation

@nwparker

@nwparker nwparker commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

OOM hardening slice 14/29 — bound AI Vault discovery, readers & caches

Part of a 29-PR stack re-landing #10179 ("bound OOM-prone accumulators across Orca"), which was reverted in #10255 for being too large (~1,600 files). This is slice 14/29 (base: oom/13-b-daemon-pty). Merge in numeric order. The full stack's end-state is byte-for-byte the commit that passed #10179's complete CI matrix (36k+ tests, multi-OS).

Summary

This slice re-lands the AI Vault (agent-session scanner) OOM bounds: it replaces every unbounded readdir/readFile/readline path with streaming/opendir + a shared bounded JSONL reader and a concurrency- and byte-budgeted whole-JSON reader, and adds explicit ceilings on per-session field bytes, aggregate list bytes, discovery depth/entries, parse/title/workdir caches, and the OpenCode SQLite worker queue. It sits on top of foundation slices that provide the shared bounded-IO helpers (node-bounded-json-stringify, node-bounded-file-reader, json-text-structure-limit, opencode-database-files).

ELI5

Orca has a panel that lists your past AI coding-agent chats by scanning files on disk. Before, a corrupt or gigantic chat file could make Orca read the whole thing into memory and crash. This change puts polite size limits everywhere: it reads files in a streaming way, skips absurdly huge lines or files, caps how many sessions/titles it keeps in memory, and shows a small "some entries were omitted" note instead of blowing up. For normal-sized histories nothing looks different; the limits only bite on abusive or enormous inputs.

Proof of OOM fix

  • Per-session field caps in session-list-retention.ts: session id 64KiB, path/cwd/filePath/codexHome 128KiB, display fields (title/branch/model/lastUserPrompt/preview) truncated to 4KiB, per-session JSON 1MiB; tests: session-list-retention.test.ts (exact-limit accept + one-byte-over reject, UTF-8-safe truncation)
  • Aggregate list caps: AI_VAULT_SESSION_LIST_MAX_JSON_BYTES=32MiB, AI_VAULT_SCAN_ISSUE_MAX_ENTRIES=1024, cache-key 256KiB; over-limit yields one 'AI Vault omitted N sessions' issue; tests: session-list-retention.test.ts, session-list-results.test.ts, session-scanner-retention.test.ts, remote-session-scanner.test.ts
  • Discovery budget (session-discovery-budget.ts): MAX_ENTRIES=100_000, MAX_DEPTH=64, MAX_PATH_BYTES=32MiB, issue lists capped 256; tests: session-discovery-budget.test.ts, session-scanner-discovery.test.ts (exact depth/entry capacity + overflow releases the open dir handle)
  • Bounded JSONL reader (session-jsonl-line-reader.ts): AI_VAULT_JSONL_MAX_RECORD_BYTES=8MiB, oversized records dropped and resumed at next newline; test: session-jsonl-line-reader.test.ts (CRLF/UTF-8, oversized drop, no oversized tail materialized)
  • Whole-JSON reader (session-whole-json-reader.ts): AI_VAULT_WHOLE_JSON_MAX_BYTES=64MiB, MAX_ACTIVE=8 concurrent, MAX_WAITERS=256 FIFO queue; test: session-whole-json-reader.test.ts (FIFO admission, single-doc>budget reject, oversized sparse file rejected before read)
  • Parse cache (session-parse-cache-retention.ts): MAX_ENTRIES=4096, key 32KiB, value 256KiB, aggregate 32MiB LRU; persistence payload capped 32MiB (session-parse-cache-payload.ts); tests: session-parse-cache-retention.test.ts, session-parse-cache-payload.test.ts, session-scanner-parse-cache.test.ts
  • Codex title index + Kimi workdir caches: 2048 entries / 512KiB each with exact streaming disk fallback on eviction miss (no correctness loss); tests: session-scanner-codex-title-index.test.ts, session-scanner-kimi-index-cache.test.ts
  • OpenCode SQLite: id 16KiB / model 1MiB / message 1MiB / part 4MiB filtered in SQL, worker MAX_PENDING_CALLS=256; tests: session-scanner-opencode-sqlite-bounds.test.ts, session-scanner-opencode-sqlite-worker-client.test.ts
  • JSON structural guard (session-scanner-values.ts): structuralTokens 1_000_000, nestingDepth 256 rejected before JSON.parse; test: session-scanner-values.test.ts
  • Claude subagent list cap CLAUDE_SUBAGENT_SESSION_MAX=2048 (newest by mtime), issues capped 256; Kimi assistant preview source 512KiB/256 chunks; scope cwd cache 2048 entries/8MiB (session-scope-cwd-cache.ts); tests: session-scanner-claude-subagents.test.ts, session-scanner-kimi-parser.test.ts, session-scope-cwd-cache.test.ts

Regressions

Normal-path (ordinary use, below the new limits): none — behavior is unchanged below the ceilings.

Overload-only (extreme input / sustained backpressure) — intended, documented degradations:

  • Whole-JSON session files >64MiB are rejected before read, so a Devin/Gemini-json/Hermes/Grok/Kimi/OpenCode-json session that large silently drops from the list (64MiB single-file session is far above ordinary)
  • JSON documents/lines with >1,000,000 structural tokens or >256 nesting levels are rejected before JSON.parse, dropping that session or line (very large single-file sessions with tens of thousands of records could theoretically hit the token ceiling)
  • Individual JSONL transcript records >8MiB are dropped and parsing resumes at the next newline; the rest of the session still lists
  • Session list exceeding 32MiB aggregate omits the oldest sessions with a bounded scan issue (default recency limit is 1000 sessions, well under this)
  • Codex/Kimi title & workdir caches evicting beyond 2048 entries or 512KiB cause a per-miss full streaming re-read of the index file (perf-only; default 1000-session scan stays under the cap so no re-reads on the normal path)
  • OpenCode SQLite worker rejects calls beyond 256 pending ('256-request capacity'); whole-JSON reader rejects beyond 256 queued waiters ('reader is busy')
  • A single Claude parent's subagent list is capped to the newest 2048 transcripts by mtime with an 'older entries were omitted' issue
  • Discovery halts at 100k entries / depth 64 / 32MiB of path data; because traversal is directory-order not mtime-order, the retained newest-N under this cap may not be the globally newest files
  • OpenCode SQLite message-count and preview subqueries exclude message/part rows whose JSON blob exceeds 1MiB (message) or 4MiB (part), and model shows null when its JSON exceeds 1MiB. A session with oversized message data will under-count messages and omit those previews. (only when: OpenCode session rows with individual message/part/model JSON blobs over the per-row byte caps; requires unusually large single-message payloads.)
  • Whole-JSON agent sessions (Devin, Gemini-json, Hermes, Grok/Kimi metadata, OpenCode-json) that are >64MiB, deeper than 256 levels, or over 1M structural tokens silently fail to parse and disappear from the AI Vault list rather than showing a degraded row. (only when: An abnormally large or deeply/structurally amplified single-file session document; not reachable with typical session sizes.)
  • Display metadata (title/branch/model/last prompt/preview text) is hard-truncated to 4KiB UTF-8 with a '...' marker. Titles (96 chars) and previews (220 chars) are already far below this, so only pathological values are affected. (only when: A session field longer than 4KiB after existing normalization; essentially only crafted/corrupt data.)
  • OpenCode SQLite parse path (session-scanner-opencode-sqlite.ts) counts and previews only message rows whose data blob is <=1MiB and part rows <=4MiB, and shows model=null when the model JSON exceeds 1MiB. A session containing an individual message/part/model JSON blob over these per-row caps under-counts its messages and omits those previews. Requires a single-message payload >1MiB (roughly a megabyte of text in one message), which is far above ordinary chat messages, so real users almost never hit it. (only when: An OpenCode session with an individual message/part/model JSON blob exceeding the per-row byte cap (1MiB message/model, 4MiB part).)

Build / CI

  • Part of the Main services + CLI group; this group's cumulative tree is interlinked, so it becomes typecheck-green at its checkpoint PR Add dismiss button to update notifications #25 (whole-repo interconnection — see stack README). Content is exact production code.

✅ Inherited defect FIXED in this slice

  • ✅ FIXED [high, reachable in ordinary use] src/main/ai-vault/session-jsonl-line-reader.ts — consumeAiVaultJsonlLines drives the async generator via iterator.next() without iterator.return() in finally; if the onLine consumer throws, the createReadStream fd is not closed. Repeated throwing scans leak descriptors.
    • Fix applied: Wrapped the manual next()-drive loop in try/finally that calls (iterator as AsyncIterator).return?.() so an onLine throw runs the generator teardown and destroys the read stream. Verified: typecheck clean + 41 session-jsonl-line-reader tests pass.

Defects inherited from the original #10179 code (not introduced by slicing; not present in today's unbounded main). Fixed items were patched in-slice and re-verified (typecheck + affected suites); remaining flagged items are overload-only and noted for a fast-follow.

Adversarial review

  • 3 skeptic lens(es) incl. a frontier-model (GPT) cross-check. Sign-off: FLAGGED — see above. Residual risk: high.
  • Verified every headline ceiling against ordinary use and found no normal-path regression. Key checks:\n\n- Whole-JSON reader concurrency (session-whole-json-reader.ts): AI_VAULT_JSON_READ_MAX_ACTIVE=8, AI_VAULT_JSON_READ_MAX_WAITERS=256. The scanner (session-scanner.ts line ~232) parses candidates in batches of SESSION_PARSE_CONCURRENCY=8 via Promise.all, so at most 8 acquire() calls are outstanding at once. The 256-waiter queue and the 'reader is busy' rejection are unreachable on the normal path (would need >264 concurrent whole-JSON reads). OVERLOAD-ONLY confirmed, not a normal-path drop despite default scan of 1000 sessions/agent.\n\n- Session-list aggregate cap AI_VAULT_SESSION_LIST_MAX_JSON_BYTES=32MiB, per-session AI_VAULT_SESSION_MAX_JSON_BYTES=1MiB. Preview is bounded upstream to 5 messages (SESSION_PREVIEW_MESSAGE_LIMIT in session-scanner-accumulator.ts, matching AI_VAULT_SESSION_PREVIEW_MAX_MESSAGES=5 in retention — so the retention preview slice is a no-op on normal data) and 220-char preview text (session-scanner-text-normalization.ts). A normal serialized session is a few KB; 1000 of them is a few MB, far under 32MiB. The tail-drop-oldest behavior is fine because candidates are mtime-descending (canStopParsingSessions).\n\n- Discovery ceilings (session-discovery-budget.ts): 100k entries / depth 64 / 32MiB path bytes vs default 1000-session scan. Fine. The directory-order-not-mtime-order newest-N caveat only matters above 100k entries.\n\n- JSONL record cap AI_VAULT_JSONL_MAX_RECORD_BYTES=8MiB; oversized records skipped, parsing resumes at next newline, rest of session still lists. Individual transcript lines rarely approach 8MiB.\n\n- Caches (parse-cache 4096 entries/256KiB value/32MiB retained; codex title 2048/512KiB; kimi workdir 2048/512KiB; scope cwd 2048/8MiB): all comfortably above a 1000-session scan; cache-miss fallback is perf-only, not a correctness change.\n\n- OpenCode discovery query adds length(CAST(id AS BLOB)) <= 16KiB predicate — session IDs are UUID-sized, so this is overload-only.\n\n- OpenCode worker MAX_PENDING_CALLS=256 vs single-threaded batches of 8: unreachable normally.\n\nThe three low-severity user-facing items (all requiring pathological single-message / single-file / single-field sizes) match the prior reviewer's assessment; I could not refute the 'ordinary users see no change' claim. Recommend sign-off as a draft PR for human review.
  • Correctness notes: /Users/nwparker/orca/workspaces/orca/oom-followup/src/main/ai-vault/session-jsonl-line-reader.ts: CONFIRMED cleanup leak: consumeAiVaultJsonlLines manually drives the async generator with iterator.next(), but does not call iterator.return() in a finally block. If onLine/state.consumeLine throws, the createReadStream remains open rather than receiving async-iterator teardown. I reproduced this against TARGET with a 64 MiB JSONL file and observed the descriptor still open via lsof after the rejection was caught; the equivalent direct for-await loop and an early break from iterateAiVaultJsonlLines both closed it. Repeated scans of a record that makes a production consumer throw can therefore accumulate descriptors until GC.

Files

61 files changed (+3448 / −685).


🤖 Decomposed, reviewed & assembled by Claude Code from the reverted #10179. Draft — do not merge out of order.

@nwparker
nwparker force-pushed the oom/13-b-daemon-pty branch from c2346d5 to ed074fa Compare July 24, 2026 07:48
@nwparker
nwparker force-pushed the oom/14-b-ai-vault branch from 2191157 to ee38326 Compare July 24, 2026 07:48
@nwparker
nwparker force-pushed the oom/13-b-daemon-pty branch from ed074fa to 7f5cd50 Compare July 25, 2026 02:21
@nwparker
nwparker force-pushed the oom/14-b-ai-vault branch from ee38326 to 5b042d9 Compare July 25, 2026 02:21
@nwparker
nwparker force-pushed the oom/13-b-daemon-pty branch from 7f5cd50 to 8714ad3 Compare July 25, 2026 02:40
@nwparker
nwparker force-pushed the oom/14-b-ai-vault branch from 5b042d9 to 901b227 Compare July 25, 2026 02:40
@nwparker
nwparker force-pushed the oom/13-b-daemon-pty branch from 8714ad3 to bf5147e Compare July 25, 2026 03:10
@nwparker
nwparker force-pushed the oom/14-b-ai-vault branch from 901b227 to 0c5e851 Compare July 25, 2026 03:10
Files: 61 applied, 0 deleted (from 6eb70d8)

Co-authored-by: Orca <help@stably.ai>
@nwparker
nwparker force-pushed the oom/13-b-daemon-pty branch from bf5147e to 7ce7037 Compare July 25, 2026 03:34
@nwparker
nwparker force-pushed the oom/14-b-ai-vault branch from 0c5e851 to a640d5b Compare July 25, 2026 03:34
@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #10548, which re-scopes this work to the bound-at-ingress doctrine (see #10533 and src/shared/memory-safety/README.md).

An audit found the original #10179 scope was ~50x the size of the fix for the crash it targeted, and that bounds had landed ahead of their callers. Every file in these slices was re-adjudicated individually: ingress bounds (transport frames, PTY flow control, on-disk transcripts, parsing, enumeration, media decode, user-keyed accumulators) were kept; interior ceilings behind an already-bounded input were dropped. 1,882 files → 1,155, full suite green, and no main feature regressed.

No memory protection was lost — only speculation.

@nwparker nwparker closed this Jul 25, 2026
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