Skip to content

oom(16/29): bound Codex session/transport/account memory - #10309

Closed
nwparker wants to merge 1 commit into
oom/15-b-browser-emulatorfrom
oom/16-b-codex
Closed

nwparker wants to merge 1 commit into
oom/15-b-browser-emulatorfrom
oom/16-b-codex

Conversation

@nwparker

@nwparker nwparker commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

OOM hardening slice 16/29 — bound Codex session/transport/account memory

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 16/29 (base: oom/15-b-browser-emulator). 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-introduces explicit count/byte/depth/LRU ceilings across Codex and OpenCode account-management, migration, session-listing, capability-cache, and usage-scan code, plus a 4 MiB per-file read cap (readAgentStateFileSync / node-bounded-file-reader) on agent state files. All bounds are whole-file with dedicated boundary tests; every over-limit path fails closed or LRU-evicts.

ELI5

Orca reads and imports a lot of files that Codex/OpenCode write on disk (login tokens, session logs, config, usage history). Before, some of that reading had no size limit, so a giant or corrupt file could balloon memory and crash the app. This change puts a fixed "you can only hold this much" cap on each of those spots. In everyday use nobody hits the caps. If something is absurdly large (a 4 MB auth file, 200k session files, 100k history threads), Orca now skips or trims that piece instead of trying to swallow it all — occasionally meaning one feature (like usage analytics or OpenCode status integration) quietly steps aside until the oversized data is gone.

Proof of OOM fix

  • Per-file read cap MAX_AGENT_STATE_FILE_BYTES = 4 MiB via readAgentStateFileSync/readNodeFileSyncWithinLimit, applied to auth.json/config.toml/hooks.json/markers across runtime-home-service.ts, service.ts, config-toml-trust.ts, codex-trust-config-rollback.ts (test: codex-trust-config-rollback.test.ts rejects sparse >4MiB config)
  • Codex legacy history migration caps: file 32 MiB, line 1 MiB, input 200k lines, output 32 MiB, 64 KiB streaming chunks (legacy-history-migration.ts; test legacy-history-migration.test.ts asserts each skip reason with no partial output)
  • Codex legacy session migration caps: depth 32, entries 50k, total 4 GiB, path 4 MiB code units, 64 KiB compare chunks (legacy-session-migration.ts; test legacy-session-migration.test.ts preflights each cap before any copy)
  • Legacy managed-state migration caps: 4096 account entries, 256 managed homes, 2048 diagnostic records, 1 MiB diagnostic bytes (legacy-managed-state-migration.ts; test asserts discovery-skip / history-skip / session-skip markers)
  • Codex session listing budget: depth 32, entries 200k, files 100k, path 32 MiB code units (codex-session-listing-budget.ts; tests codex-session-file-listing.test.ts hit each exact boundary)
  • Codex account-home discovery: 4096 entries, 256 homes, 1 MiB path code units, fails closed to [] (codex-account-home-discovery.ts + .test.ts)
  • Codex session index heal: 100k tracked threads, 64 KiB marker file, 1 MiB JSONL line, 64 KiB audit target, 128 recordId, 512 rollout stamp (codex-session-index-heal-state.ts + heal-jsonl.ts; memory + jsonl tests)
  • Codex app-server capability cache + retry deadlines: 64-host LRU, 4 KiB host-key cap (sha256-digested beyond) (codex-app-server-capability-cache.ts, codex-host-retry-deadlines.ts + tests)
  • WSL runtime-home retention & reconciliation generations: 64/256-entry LRU with byte budgets (8 MiB / 1 MiB) (codex-wsl-runtime-home-retention.ts, codex-wsl-reconciliation-generations.ts + tests)
  • WSL canonical-path cache: 256-entry LRU + 2 MiB aggregate byte budget (codex-wsl-hook-install-plan.ts; LRU + byte-budget tests)
  • OpenCode SQLite usage row cap 4 MiB retained text, rejected in-SQL before parse (sqlite-usage-row-stream.ts + .test.ts); OpenCode DB file limit 256 (opencode-database-files.ts + .test.ts); overlay manifest 2 MiB + entry/name budgets (config-overlay-manifest.ts + .test.ts)
  • Grant JSON admission: 1,000,000 structural tokens / depth 128 before JSON.parse; grant-entry stdin cap 16 MiB; app-server stdout/stderr GrowingByteBuffer tail bounded by STDOUT_LINE_MAX_BYTES/STDERR_TAIL_MAX_BYTES (codex-app-server-grant-json.ts, codex-app-server-grant-entry.ts, codex-app-server-session.ts + tests)
  • nvm version discovery: 4096 entries, 1 MiB retained-name bytes, fails closed to [] (nvm-version-directory-discovery.ts + .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:

  • Usage scan aborts wholesale: parseCodexUsageFile/scanCodexUsageFiles and parseOpenCodeUsageDatabase now share a UsageHistoryScanBudget and throw UsageHistoryScanCapacityError (records/ownershipKeys/retainedBytes) which propagates up and resets the usage store to defaults with lastScanError — only when the shared budget or MAX_USAGE_HISTORY_FILES(200k)/previous-file count is exceeded
  • Codex account-home discovery and nvm version discovery fail closed to [] (drop ALL homes / ALL nvm bin dirs) only past 4096 entries / 256 homes / 1 MiB path text / 1 MiB names
  • Legacy history/session migration permanently skips import (still writes one-shot marker) only when a legacy file exceeds 32 MiB / 200k lines / 4 GiB / depth 32
  • OpenCode config overlay is abandoned (falls back to user OPENCODE_CONFIG_DIR without Orca status integration) only when the overlay manifest exceeds 2 MiB or an entry budget is hit
  • WSL runtime-home retention drops a whole distro's cached auth/home when any single field exceeds 4 MiB (forces a re-read, not data loss on disk)
  • 4 MiB agent-state read cap throws NodeFileReadTooLargeError on auth.json/config.toml/ledger only if those files somehow exceed 4 MiB (kilobyte-sized in practice)
  • OpenCode DB discovery silently truncates past 256 .db files (listOpenCodeDatabases ignores the returned truncated flag)
  • A single oversized/corrupt usage record or projection now aborts the ENTIRE Codex/OpenCode usage scan (shared budget throws), resetting the usage store to defaults instead of degrading per-file as the old code did (which swallowed per-home errors). Default budget limits live in usage-history-scan-budget.ts, which is NOT in this slice — the reviewer cannot confirm the ceilings are far above ordinary use from this diff alone. (only when: Usage-history budget (records/ownershipKeys/retainedBytes) or MAX_USAGE_HISTORY_FILES=200k exceeded; must verify default budget in the dependency slice is generous.)
  • One-shot legacy Codex managed-state migration now permanently skips importing history/sessions that exceed the new caps and still writes the completion marker, so an oversized legacy home is never re-imported (diagnostics + console.warn record the skip). (only when: Legacy managed home with history >32 MiB / >200k lines, or sessions tree >50k entries / >4 GiB / depth >32 — one-time upgrade path only.)
  • OpenCode usage analytics silently ignore .db files beyond 256 (truncated flag computed but dropped by listOpenCodeDatabases), and account-home/nvm discovery drop all results on overflow. (only when: >256 OpenCode db files, or >4096 dir entries / >256 account homes during discovery — far above normal.)

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.

Adversarial review

  • 2 skeptic lens(es). Sign-off: yes. Residual risk: medium.
  • Verified every numeric ceiling in the slice against TARGET; all sit far above ordinary use, so I could not confirm a normal-path regression for ordinary users.

Confirmed ceilings:

  • Session listing (codex-session-listing-budget.ts): depth 32, 200k entries, 100k files, 32 MiB path text. Codex sessions are date-partitioned (shallow); overload-only.
  • Usage scan (usage-history-scan-budget.ts, dep slice, read at TARGET): records 100k, ownershipKeys 100k, retainedBytes 256 MiB, files 200k, discoveryEntries 1M.
  • Account-home discovery (codex-account-home-discovery.ts): 4096 entries / 256 homes / 1 MiB paths, fails closed to [] with console.warn.
  • nvm discovery: 4096 entries / 1 MiB names, fails closed to [].
  • Legacy migration (legacy-history-migration.ts): 32 MiB file / 1 MiB line / 200k lines / 32 MiB output — one-shot, still writes completion marker.
  • config-overlay-manifest.ts: 2 MiB + entry budget.
  • agent-state read cap (agent-state-file-reader.ts, dep slice): 4 MiB on auth.json/config.toml/ledger (KB-sized in practice).
  • WSL runtime-home retention: 4 MiB per field.

Refuting/qualifying the prior reviewer:

  • The claim "a SINGLE oversized/corrupt usage record aborts the entire scan" is inaccurate. budget.claimRecord adds only 1024 pipeline bytes + getUsageHistoryRetainedBytes([sessionId,timestamp,eventKey,cwd,model]) (a few hundred bytes) per record; one record cannot trip the 256 MiB / 100k-record ceiling. The abort is strictly cumulative across the whole scan.
  • STDOUT_LINE_MAX_BYTES (1 MiB) and STDERR_TAIL_MAX_BYTES (8 KiB) in codex-app-server-session.ts are PRE-EXISTING (visible on the '-' side of the diff). The change only refactors string concatenation to GrowingByteBuffer with raw bytes, which is more correct for split multibyte UTF-8. No new cap, no normal-path change.
  • Sync listCodexSessionJsonlFiles rethrows CodexSessionListingCapacityError, but the only production caller (syncSystemCodexSessionsIntoManagedHome) is not on the launch path; the launch path uses the incremental variant which catches the error and returns gracefully. No unhandled-throw crash on normal startup.

Residual risk (medium, NOT ordinary-path): the cumulative per-scan usage budget makes a heavy multi-year Codex user (~100k+ lifetime token_count records) permanently lose the usage panel (sticky scan_failed) where base degraded gracefully. This is above ordinary use but worth a human sign-off note, and the actual defaults live in a dependency slice (usage-history-scan-budget.ts) so they must land together.

Files

65 files changed (+4362 / −865).


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

Made with Orca 🐋

@nwparker
nwparker force-pushed the oom/15-b-browser-emulator branch from 1f56455 to 11dc81e Compare July 24, 2026 07:48
@nwparker
nwparker force-pushed the oom/15-b-browser-emulator branch from 11dc81e to d67f955 Compare July 25, 2026 02:21
@nwparker
nwparker force-pushed the oom/15-b-browser-emulator branch from d67f955 to cafefaf Compare July 25, 2026 02:40
@nwparker
nwparker force-pushed the oom/15-b-browser-emulator branch from cafefaf to 16e0218 Compare July 25, 2026 03:11
Files: 65 applied, 0 deleted (from 6eb70d8)

Co-authored-by: Orca <help@stably.ai>
@nwparker
nwparker force-pushed the oom/15-b-browser-emulator branch from 16e0218 to 01bade0 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