Skip to content

oom(01/29): bound shared file/stream/buffer readers - #10294

Merged
nwparker merged 1 commit into
mainfrom
oom/01-a1-shared-readers
Jul 25, 2026
Merged

nwparker merged 1 commit into
mainfrom
oom/01-a1-shared-readers

Conversation

@nwparker

@nwparker nwparker commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

OOM hardening slice 01/29 — bound shared file/stream/buffer readers

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 01/29 (base: main). 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

Adds 10 new additive src/shared bounded-reader modules (+8 test files) for file/stream/buffer/text/JSON: growing-byte-buffer, node-readable-text, fetch-response-body, string-chunk-compaction, node-file-content-equality, node-source-copy-content-equality, search-subprocess-lines, nul-delimited-fields, bounded-secure-json-file, persisted-state-file-bounds. No existing file changed; no in-slice consumers. Imported deps (node-bounded-json-stringify, secure-file, json-text-structure-limit, node-bounded-file-reader) exist at BASE with the exact exports used, so the slice compiles standalone. Verified: node typecheck clean, 29/29 vitest pass, oxlint clean.

ELI5

These are new tape-measure tools that read files/streams/network bodies a little at a time and stop once the data gets too big, instead of swallowing an entire giant blob into memory. This slice just adds the tools to the toolbox and tests them; nothing in the app uses them yet, so nothing behaves differently for users.

Proof of OOM fix

  • search-subprocess-lines/growing-byte-buffer cap a single subprocess (e.g. ripgrep) output line at 64MB in one growable buffer instead of unbounded per-line accumulation
  • fetch-response-body caps HTTP response bodies (default 16MB) via content-length pre-check plus streaming length check, rejecting huge/malicious responses instead of buffering them all
  • node-file-content-equality and node-source-copy-content-equality compare files in fixed 64KB chunks with a stat-size short-circuit, so a 256MB sparse file is rejected from metadata without reading its body
  • persisted-state-file-bounds caps the persisted-state JSON file at 64MB, applies structural-token/nesting limits to block JSON structure amplification, chunk-hashes to avoid large intermediate strings, and caps secret plaintext at 4MB
  • nul-delimited-fields iterates NUL-delimited git output lazily instead of split('\0') materializing a full array
  • string-chunk-compaction compacts a string[] once it exceeds 1024 entries, bounding array/per-string overhead
  • node-readable-text caps a Node Readable's decoded text at a byte limit

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:

  • fetch body over limit throws FetchResponseBodyTooLargeError (rejects, does not silently truncate)
  • node-readable-text over limit throws NodeReadableTextTooLargeError
  • search-subprocess line over maxLineBytes: push() returns false and drops the buffered line
  • persisted-state file over cap throws NodeFileReadTooLargeError; secret over 4MB throws PersistedStateSecretCapacityError; JSON exceeding structural-token/depth limits throws JsonTextStructureCapacityError
  • file-content comparisons short-circuit to false on stat-size mismatch without reading the body

Build / CI

  • ✅ Cumulative typecheck is green at this stack position.

Adversarial review

  • 1 skeptic lens(es). Sign-off: yes. Residual risk: low.
  • Materialized target files onto BASE: node typecheck exit 0, 29/29 vitest pass, oxlint clean, then restored tree. Growth/doubling math bounded by max; overlapping Buffer.copy used correctly for discardPrefix/retainSuffix; buffers copied not aliased (source-mutation tests pass). fetch reader cancelled+releaseLock in finally; TextDecoder decodes full buffer so split multibyte is safe. persisted-state replace uses a function replacer (literal $), verifies slot present+unambiguous; hash chunking avoids splitting surrogate pairs; restore validates+parses before writing temp and cleans temp on failure. node-source-copy uses statSync(source)/lstatSync(copy) as documented. Only note: fetch high-level-only adapters intentionally bypass byte bounding via .text()/.json(), but that path has no real-network consumer and no caller in this slice. Additive with zero consumers, so no normal-path regression is reachable from this slice.

Files

18 files changed (+1166 / −0).


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

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ac53e7b-fe57-475c-ab0a-8a9b66278490

📥 Commits

Reviewing files that changed from the base of the PR and between 8eef7fb114110acd78c5328cf60cf6b8b2253e00 and f072935.

📒 Files selected for processing (18)
  • src/shared/bounded-secure-json-file.ts
  • src/shared/fetch-response-body.ts
  • src/shared/growing-byte-buffer.test.ts
  • src/shared/growing-byte-buffer.ts
  • src/shared/node-file-content-equality.test.ts
  • src/shared/node-file-content-equality.ts
  • src/shared/node-readable-text.test.ts
  • src/shared/node-readable-text.ts
  • src/shared/node-source-copy-content-equality.test.ts
  • src/shared/node-source-copy-content-equality.ts
  • src/shared/nul-delimited-fields.test.ts
  • src/shared/nul-delimited-fields.ts
  • src/shared/persisted-state-file-bounds.test.ts
  • src/shared/persisted-state-file-bounds.ts
  • src/shared/search-subprocess-lines.test.ts
  • src/shared/search-subprocess-lines.ts
  • src/shared/string-chunk-compaction.test.ts
  • src/shared/string-chunk-compaction.ts
🚧 Files skipped from review as they are similar to previous changes (17)
  • src/shared/nul-delimited-fields.test.ts
  • src/shared/string-chunk-compaction.test.ts
  • src/shared/growing-byte-buffer.test.ts
  • src/shared/string-chunk-compaction.ts
  • src/shared/bounded-secure-json-file.ts
  • src/shared/node-file-content-equality.test.ts
  • src/shared/nul-delimited-fields.ts
  • src/shared/node-source-copy-content-equality.test.ts
  • src/shared/node-readable-text.ts
  • src/shared/search-subprocess-lines.ts
  • src/shared/node-file-content-equality.ts
  • src/shared/node-source-copy-content-equality.ts
  • src/shared/node-readable-text.test.ts
  • src/shared/fetch-response-body.ts
  • src/shared/search-subprocess-lines.test.ts
  • src/shared/persisted-state-file-bounds.ts
  • src/shared/growing-byte-buffer.ts

📝 Walkthrough

Walkthrough

The change adds shared utilities for enforcing byte and JSON-structure limits across persisted state, secure JSON files, fetch responses, and async readable input. It introduces resizable byte buffering, bounded subprocess line accumulation, string chunk compaction, file-content comparison helpers, and NUL-delimited field iteration. Persisted-state functionality includes bounded parsing and serialization, secret capacity checks, replacement sizing, surrogate-safe hashing, and atomic backup restoration. Comprehensive Vitest coverage exercises boundary, streaming, sparse-file, cleanup, and UTF-8 behaviors.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding bounded shared file, stream, and buffer readers.
Description check ✅ Passed The description is detailed and covers summary, testing, review, security, and notes, but it does not follow the required template sections exactly.
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.
✨ Finishing Touches
📝 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.

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/shared/search-subprocess-lines.ts (1)

5-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate buffer-growth logic — consider reusing GrowingByteBuffer.

The private buffer/append/takeLine trio reimplements the same doubling-growth accumulator already implemented and tested in GrowingByteBuffer (src/shared/growing-byte-buffer.ts). Since push() already enforces the maxLineBytes cap before calling append (Line 21), the internal Math.min(this.maxLineBytes, ...) clamp is redundant, and a GrowingByteBuffer instance (byteLength, append, takeString, clear) could replace this logic entirely.

Note: search-subprocess-lines.test.ts reflects into the private buffer field expecting a raw Buffer | null (Lines 47, 49), so adopting this would also require updating those assertions.

♻️ Sketch of the reuse
+import { GrowingByteBuffer } from './growing-byte-buffer'
+
 export class SearchSubprocessLineAccumulator {
-  private buffer: Buffer | null = null
-  private bytes = 0
+  private readonly buffer = new GrowingByteBuffer()
 
   ...
 
   push(rawChunk: Buffer | string, onLine: (line: string) => void): boolean {
     ...
-      if (this.bytes + segmentBytes > this.maxLineBytes) {
+      if (this.buffer.byteLength + segmentBytes > this.maxLineBytes) {
         this.clear()
         return false
       }
-      if (newline !== -1 && this.bytes === 0) {
+      if (newline !== -1 && this.buffer.byteLength === 0) {

Also applies to: 54-74


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 99b56c57-b508-4135-8cbc-b7a05f131361

📥 Commits

Reviewing files that changed from the base of the PR and between 20ce29a and d56a020.

📒 Files selected for processing (18)
  • src/shared/bounded-secure-json-file.ts
  • src/shared/fetch-response-body.ts
  • src/shared/growing-byte-buffer.test.ts
  • src/shared/growing-byte-buffer.ts
  • src/shared/node-file-content-equality.test.ts
  • src/shared/node-file-content-equality.ts
  • src/shared/node-readable-text.test.ts
  • src/shared/node-readable-text.ts
  • src/shared/node-source-copy-content-equality.test.ts
  • src/shared/node-source-copy-content-equality.ts
  • src/shared/nul-delimited-fields.test.ts
  • src/shared/nul-delimited-fields.ts
  • src/shared/persisted-state-file-bounds.test.ts
  • src/shared/persisted-state-file-bounds.ts
  • src/shared/search-subprocess-lines.test.ts
  • src/shared/search-subprocess-lines.ts
  • src/shared/string-chunk-compaction.test.ts
  • src/shared/string-chunk-compaction.ts

Comment on lines +95 to +115
export async function readFetchResponseTextWithinLimit(
response: Response,
maxBytes = API_RESPONSE_MAX_BYTES
): Promise<string> {
if (isHighLevelOnlyResponse(response)) {
return response.text()
}
return new TextDecoder().decode(await readFetchResponseBytesWithinLimit(response, maxBytes))
}

export async function readFetchResponseJsonWithinLimit<T>(
response: Response,
maxBytes = API_RESPONSE_MAX_BYTES,
structureLimits: JsonTextStructureLimits = API_RESPONSE_JSON_LIMITS
): Promise<T> {
if (isHighLevelOnlyResponse(response)) {
return response.json() as Promise<T>
}
const content = await readFetchResponseTextWithinLimit(response, maxBytes)
assertJsonTextStructureWithinLimits(content, structureLimits)
return JSON.parse(content) as T

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not bypass limits for high-level-only responses.

response.text() is unbounded, and response.json() also skips assertJsonTextStructureWithinLimits. An adapter without headers and body can therefore bypass the API’s byte, depth, and token limits. Require a bounded body-reader contract from adapters, or reject this response shape instead of falling back.

Comment on lines +17 to +33
export function nodeSourceAndCopyContentsEqualSync(sourcePath: string, copyPath: string): boolean {
try {
// Why: source links are intentional, but an owned copy must remain a regular file.
if (!statSync(sourcePath).isFile() || !lstatSync(copyPath).isFile()) {
return false
}
} catch {
return false
}

let sourceDescriptor: number | null = null
let copyDescriptor: number | null = null
let matches = false
let failed = false
try {
sourceDescriptor = openSync(sourcePath, 'r')
copyDescriptor = openSync(copyPath, 'r')

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Bind regular-file validation to the opened descriptor.

copyPath can be swapped for a symlink after Line 20 and before Line 33; openSync follows it, so this may compare an unintended target and return true. Capture the initial lstatSync identity and verify it against fstatSync(copyDescriptor) before comparing bytes, with a race regression test.

Comment thread src/shared/string-chunk-compaction.ts Resolved
@nwparker
nwparker force-pushed the oom/01-a1-shared-readers branch 3 times, most recently from 1be8938 to 8eef7fb Compare July 25, 2026 02:39
Files: 18 applied, 0 deleted (from 6eb70d8)

Co-authored-by: Orca <help@stably.ai>
@nwparker
nwparker force-pushed the oom/01-a1-shared-readers branch from 8eef7fb to f072935 Compare July 25, 2026 03:10
@nwparker
nwparker merged commit c419aad into main Jul 25, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#10294)

Files: 18 applied, 0 deleted (from 925d4a7)

Co-authored-by: Orca <help@stably.ai>
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