Skip to content

Replace patched JSON parser with stream-json - #25202

Merged
nwparker merged 2 commits into
mainfrom
nwparker/stream-json-migration
Oct 4, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/stream-json-migration

Conversation

@nwparker

@nwparker nwparker commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​250 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​232
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​506 $\color{#cf222e}{\Huge{\mathbf{−}}}$​256 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​250

ELI5

Replace our locally patched JSON parser with stream-json. Search filenames and session text keep their Unicode characters without maintaining a dependency patch, and large search/session records parse faster.

What Changed

Both consumers use one synchronous token reader with bounded input batches. Dense ripgrep records retain only the requested ranges while validating the complete record; streamed session documents use the library's configurable assembler to discard unused fields and fold messages as they arrive. The ordinary JSON.parse search path is unchanged.

Install the historical Bun-server compatibility fixture from its own frozen lockfile, so removing a current dependency cannot break the old-source test build.

Remove @streamparser/json and its patch; pin stream-json 3.7.0 and stream-chain 4.2.6. Bundle both for desktop and remote relays. The CLI still emits CommonJS; its TypeScript module model now reflects the synchronous ESM loading supported by our existing Node 24 runtime.

Why

The previous library silently removed U+FEFF inside JSON strings without our patch. This replacement passes the literal/escaped Unicode regressions without modification and improves both real consumer shapes. Staying on the patch avoids a migration but retains maintenance work; older CommonJS versions of stream-json lack the newer prototype-key handling.

There is a measured tradeoff: dense-search peak RSS increases by roughly 5–19 MiB. Smaller 8 Ki-code-unit batches reduce the large-record candidate peak from about 299 to 249 MiB without losing the speedup. Sessions keep 64 Ki batches, which measured better there. Memory still scales with the largest individual string/record and selected metadata; this is not a constant-memory guarantee.

Linked Issue

Follow-up to #25156; no separate issue.

Visual Proof

N/A — internal parsing and dependency changes, with no UI or interaction change.

Testing

  • Manually exercised built CommonJS parsing with Unicode input and orca --help on macOS arm64.
  • Automated tests added/updated for Unicode boundaries, duplicate fields, invalid trailing input, error precedence, source cleanup, and exact existing resource limits.
  • 1,845 tests passed, one test skipped, across the AI Vault, ripgrep, and shared text-search suites. After batch tuning, 41 focused tests passed again.
  • 15,185 dense-record and 6,000 session differential cases passed against the patched baseline; benchmark fixtures also compare projections and untimed SHA256 hashes of all consumed session messages.
  • Node and CLI typechecks, changed-code quality, CLI build, relay build, and Electron/Vite build passed. Built desktop/relay output has no external parser require calls.
  • Actual execution and measurements were on macOS arm64 (Apple M4 Max), Node 24.20.0. Windows/Linux/WSL execution was not repeated for this migration; CI remains required. No native dependency, filesystem, host ownership, or wire-format changes.

Measurements

Patched baseline at f62bd7dc2098 versus final migration, serial runs with three warmups followed by 12 counterbalanced pairs per fixture. Peak RSS is the mean of two fresh-process peaks per arm, with fixture generation outside those processes. Search timing excludes file loading; session timing includes streaming file reads, decoding, and cooperative yields. Both exclude process startup/imports. P95 is descriptive, not a statistical confidence bound.

Fixture Input MiB Median ms, before → after P95 ms, before → after Whole-process peak RSS MiB, before → after
rg-10k 0.5 13.8 → 7.2 14.0 → 9.2 66.7 → 76.3
rg-100k 4.7 139.7 → 67.6 166.0 → 75.7 81.7 → 100.7
rg-100k-cap1 4.7 140.1 → 65.7 143.2 → 71.2 81.7 → 99.7
rg-unicode 0.8 16.6 → 7.3 16.8 → 7.4 68.3 → 73.2
rg-large-dense 51.0 1321.2 → 606.0 1337.2 → 611.7 231.5 → 248.8
rg-fast-path 4.0 1.4 → 1.4 2.0 → 2.1 69.0 → 68.9
session-messages 10.6 95.1 → 53.0 97.2 → 53.6 67.7 → 73.7
session-skipped-objects 21.6 338.2 → 264.8 347.5 → 269.6 83.9 → 91.2
session-skipped-string 20.0 141.9 → 60.3 145.5 → 63.5 110.3 → 106.3
session-selected-string 20.0 143.5 → 60.4 144.6 → 62.0 110.9 → 105.3

Dense parsing is 48–56% faster, streamed sessions 22–58% faster, and the ordinary search fast path is unchanged. The 51 MiB stress record remains synchronous (about 0.6 seconds versus 1.3 seconds); this migration does not introduce asynchronous search ingestion. Candidate session fresh-process maximum event-loop gaps stayed below 4.3 ms in these fixtures. Retained-heap deltas after forced GC stayed below 1.2 MiB except the ordinary fast-path fixture, which intentionally returns its 4 MiB text in full.

Reproduce

Use each revision's installed lockfile dependencies. At the baseline revision, bundle the two consumers into a persistent temporary directory:

pnpm exec esbuild src/shared/ripgrep-dense-match-json.ts --bundle --platform=node --format=esm --outfile=/tmp/orca-parser-bench/baseline-rg.mjs
pnpm exec esbuild src/main/ai-vault/session-document-stream.ts --bundle --platform=node --format=esm --outfile=/tmp/orca-parser-bench/baseline-session.mjs

At this PR revision, bundle the same entry points as candidate-rg.mjs and candidate-session.mjs into that directory, then run:

ORCA_BACKGROUND_LAUNCH=1 node --expose-gc config/scripts/json-parser-migration-benchmark.mjs /tmp/orca-parser-bench

The checked-in harness generates valid synthetic ripgrep records and session fixtures, checks parity, reports raw samples and memory measurements, and removes its generated files. Keep other tests/builds idle while measuring.

Review

Independent adversarial reviews covered both consumers, the shared reader, malformed input, prototype keys, cancellation, resource limits, ESM/CommonJS compatibility, and benchmark validity. Initial benchmark fixture and measurement issues were corrected; final reviews are clean. Rebased on current main before opening; range-diff confirms the reviewed patch is unchanged.

Full dependency audit follow-up

Cloned both dependency repositories and reviewed all 129 runtime modules and 129 paired declarations, plus benchmark/build configuration. Upstream suites passed 1,206 tests and 2,575 assertions; both TypeScript/checkJs checks passed. Additional probes passed 64,000 JSON parser/verifier comparisons, 80 JSONC comparisons, and 20,000 path-matcher comparisons.

The libraries as a whole are not clean: confirmed issues include cancellation/handle cleanup, generic adapter allocation, file short writes, array-index paths, reviver/filter semantics, and declaration mismatches. None is reached by this integration: it uses the synchronous flattened executor, decoded strings, predicate-based projection without numeric array indices, and caller-owned I/O. No dependency patches were added. The chosen executor also measured faster than the two supported synchronous alternatives (44.7 vs 48.6/52.7 ms for token-only dense input); these are an additional microbenchmark, not replacements for the complete-consumer measurements above. A 100,002-token allocation probe created zero per-token promises.

Parser code and the before/after numbers are unchanged. The audit caught the Linux compatibility-build failure from linking historical source to current node_modules; it now installs that historical revision's frozen dependencies independently with scripts disabled. The actual old server build succeeded locally (Bun 1.4.2), 69 workflow contract tests passed, and an independent review found no remaining CI-fix issue. Both previously failing Linux persistence checks now pass on the updated head; remaining CI is running without failures at the audit close.

Agent skill upstream boundary

  • Not applicable; no upstream skill content copied.

Checklist

  • Focused on replacing the parser and measuring/verifying its two consumers
  • Explained behavior, mechanism, alternatives, and measured memory tradeoff
  • Visual proof marked N/A with reason
  • Self-reviewed and independently reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, folder-workspace, and compatibility impact considered
  • Focused tests, Node/CLI typechecks, changed-code lint/quality, and affected builds passed locally; remaining platform/full CI checks run on the PR

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: a897461e-b00a-4d8c-8a5e-794897794671
📥 Commits

Reviewing files that changed from the base of the PR and between 72683e2 and 85e1fda.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • .github/workflows/node-server-tests.yml
  • config/scripts/node-server-change-scope.test.mjs

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


📝 Walkthrough

Walkthrough

The change replaces @streamparser/json with stream-json and stream-chain. It adds a shared token reader and updates the ripgrep match and session-document parsers to use it. New tests cover token-reader behavior and parser contracts. Benchmark scripts generate fixtures and compare baseline and candidate parser results, timing, event-loop gaps, and memory measurements. TypeScript module targets and main-process bundling configuration are also updated.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 85e1f

No merge-blocking issue is established. The change is ready for normal CI validation.

Architecture Summary

Architecture risk: 🔵 Low · up to 85e1f

The change affects 5 systems.

Changed systems: config, src, electron.vite.config.ts, package.json, pnpm-workspace.yaml

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — config (service) was modified; 6 changed files map to changed impact.
  • observed — src (service) was modified; 6 changed files map to changed impact.
  • observed — electron.vite.config.ts (service) was modified; 1 changed file maps to changed impact.
  • observed — package.json (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in config/patches/@[email protected]: The deleted patch added ignoreBOM: true to the UTF-8 decoders in NonBufferedString and BufferedString across the CommonJS, MJS, and TypeScript files, retaining fatal: true.
  • observed — Modified behavior in config/scripts/json-parser-benchmark-fixtures.mjs: Adds filesystem and path imports used to write fixture files.
  • observed — Modified behavior in config/scripts/json-parser-benchmark-fixtures.mjs: Adds exported fixture cases for match counts of 1, 10,000, 100,000, and 900,000, a cap of 1, Unicode content, and four session input shapes.
  • observed — Modified behavior in config/scripts/json-parser-benchmark-fixtures.mjs: Adds writeJsonParserFixtures, which constructs a JSON value for each case and writes it as <name>.json in the supplied directory. Match fixtures use repeated text, byte-based submatch offsets, and a 4 MiB line for the count-1 case; session fixtures generate 20,000 messages, 200,000 ignored objects, a large ignored string, or a large selected message string.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 10 files. (1 skipped:… 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 clearly identifies the main change: replacing the patched JSON parser with stream-json.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issue context, visual proof, testing, review, and checklist. It reports that there is no separate issue and references #25156; the …
Full details: Docstring Coverage

Explanation

Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 10 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

  • Dependency swap — drops the patched @streamparser/[email protected] (and its ignoreBOM patch) for exact-pinned [email protected] / [email protected], bundled into the desktop main process and the esbuild relay.
  • Shared token reader — new createJsonTokenReader drives the library parser synchronously in bounded code-unit batches, preserving caller-owned UTF-8 decoding and surfacing parser failures as SyntaxError while letting consumer errors through.
  • Dense ripgrep parser — reimplemented as a manual frame stack over packed tokens, retaining projections, duplicate-key/field caps, depth and per-element token budgets, and full-record validation past the result cap.
  • Streamed session parser — reimplemented on FlexAssembler custom rules with a discard fallback, preserving the root-array fold, object-field projection/precreate, duplicate-array reset, consumer-failure precedence, and non-object-root null result.
  • Tests — contract, Unicode/BOM, malformed-input, prototype-key, source-cleanup, and exact budget-boundary coverage added or extended.

All automated checks I ran pass locally: focused parser tests (50), the full src/main/ai-vault/ suite (1057), the text-search suites (95), pnpm tc:cli, pnpm tc:node, and the changed-code quality gate. I also confirmed require('stream-json/core/parser.js') resolves under Node 24, which is what the CLI's Node20 module setting relies on.

ℹ️ Deep subpath imports couple the build to library internals

src/shared/json-token-reader.ts imports stream-json/core/parser.js, stream-chain/exec.js, and stream-chain/defs.js, and src/main/ai-vault/session-document-stream.ts imports stream-json/core/utils/flex-assembler.js. These paths resolve only through each package's blanket "./*": "./src/*" export map — stream-json's package index re-exports only the stream parser, so FlexAssembler's custom-rule API and the synchronous exec/none chain primitives have no public entry point. The exact pins make this correct today, but a patch or minor bump could reshape an internal module with no major-version signal.

Technical details
# Internal subpath coupling

## Affected sites
- `src/shared/json-token-reader.ts:1-3` — `stream-json/core/parser.js`, `stream-chain/exec.js`, `stream-chain/defs.js`
- `src/main/ai-vault/session-document-stream.ts:2` — `stream-json/core/utils/flex-assembler.js`

## Context
- `stream-json/src/index.js` exports only `{ parserStream, parser }`; `stream-json/assembler` exports the plain `Assembler`, not `FlexAssembler`, so the custom `objectRules`/`arrayRules` API is reachable only via `core/utils`.
- Both packages are pinned exactly and bundled (desktop via `BUNDLED_MAIN_DEPENDENCIES`, relay via esbuild), so the coupling is contained to the build rather than resolved at a user's runtime.

## Open questions for the human
- Worth a one-line comment at each import noting the pinned-version coupling, so a future dependency bump reviews these call sites?

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

@nwparker
nwparker force-pushed the nwparker/stream-json-migration branch from 72683e2 to 85e1fda Compare October 4, 2026 19:43

@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

  • Isolated the historical Bun build's dependencies — the persistent Linux job now installs the pinned Bun commit's own lockfile (pnpm --dir "$RUNNER_TEMP/bun-orcad-source" install --frozen-lockfile --ignore-scripts) instead of symlinking $GITHUB_WORKSPACE/node_modules. That checkout no longer contains @streamparser/json, which the Bun commit's lockfile still requires, so the isolation is what keeps the cross-runtime build resolvable.
  • Updated the workflow contract test — node-server-change-scope.test.mjs asserts the isolated install runs and that the old $GITHUB_WORKSPACE/node_modules symlink is gone.

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

@nwparker
nwparker merged commit b32462f into main Oct 4, 2026
46 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