Skip to content

perf: avoid rescanning partial notebook output frames - #23138

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-notebook-frame-scanning
Sep 27, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-notebook-frame-scanning

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​176 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​168
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​19 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2

ELI5

Large notebook outputs, such as images, arrive in pieces. Orca repeatedly reread all earlier pieces while waiting for the last one. Keep the pieces and assemble the record once, using the existing shared parser.

What Changed

The notebook reader now passes incoming text through the shared incremental JSON parser, collects completed records for this incoming chunk, then applies the same notebook frame validation and delivers them. The partial tail is preserved before a consumer can throw or feed another chunk. It preserves incomplete records, malformed-line recovery, Unicode, output ordering and the current unrestricted notebook record size. Kernel startup, execution and shutdown are unchanged.

Actual reader, synthetic input Before After
512 KiB image, 4 KiB chunks, median 3.96 ms 0.31 ms
2 MiB image, 4 KiB chunks, median 49.60 ms 1.16 ms
8 KiB image, 4 KiB chunks, median 0.0103 ms 0.0160 ms
10,000 complete tiny records, median 1.33 ms 2.09 ms
JSON records parsed before first callback in one 10,000-record chunk 1 10,000
Delimiter-search work for a 512 KiB record 34,340,924 characters Within the 1,048,696-character regression budget

Timing uses seven sequential local Node runs per shape; input creation and output assertions are outside the timer. These are parser measurements, not Python execution or UI frame-latency measurements.

Why

The shared parser already collects segments until a delimiter, avoiding repeated work on the pending prefix. Reusing it avoids another framing implementation. Its normal transport limit is explicitly disabled for notebooks so existing large image outputs are not silently dropped.

Linked Issue

Fixes #23137

Visual Proof

N/A

No rendered-content or layout change; this changes how the same notebook output frames are assembled before delivery.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

44 related cases in five suites pass; two opt-in real-Python cases remain skipped. Eight new cases cover the delimiter-work budget, every Unicode split boundary, malformed/unsupported/CRLF lines, outputs larger than 16 MiB, incomplete suffixes and consumer exceptions, suffix retention after an exception and recursive input. The original fails the work budget and passes the other seven. Node typecheck, focused lint, formatting and the changed-code gate across 149 working files pass.

Tests run on macOS in Node with optional interpreter variables blank. No kernel, package install, native window, process termination or live SSH operation ran.

Review

Independent review approved the exact source/test hashes. Eleven additional probes pass on both the original and revised code, covering the actual kernel with fake child streams, callback-error continuation, recursive input, lifecycle behavior and batch delivery. Merge risk: low to moderate; the notebook framing algorithm changes to an existing parser, with frame-parity and work-budget regressions. Shared parser code is unchanged from the base commit.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Negative user-facing trade-off: Tiny output records incur extra parser bookkeeping. The measured batch of 10,000 ready records took about 0.76 ms longer; the 8 KiB input about 5.7 microseconds longer. The wrapper also parses all complete records in a chunk before delivering its first callback (1 → 10,000 parses in the measured 10,000-record chunk), holding a temporary decoded-record array. This can delay the first output in a large batch. First-output latency, real user latency and heap costs are unmeasured. This performance trade-off is isolated in its own PR.

The existing unlimited frame size remains unlimited; this does not bound a stream that never ends a record. Existing startup deadlines, process ownership and output backpressure are outside scope. Local folder/worktree notebooks use the same path. The existing UI rejects remote cell execution; no process-host boundary, wire format, Git command, platform path or keyboard behavior changes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Focused checks above passed. Full build/lint and native platform validation remain CI coverage.

@coderabbitai

coderabbitai Bot commented Sep 26, 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: 314c0c8a-a4c8-493a-afdd-429460c8be8d

📥 Commits

Reviewing files that changed from the base of the PR and between 1344597 and 9e8f4b1.

📒 Files selected for processing (3)
  • src/main/notebook/notebook-kernel.test.ts
  • src/main/notebook/notebook-kernel.ts
  • src/shared/main-process-ndjson-framer.ts

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


📝 Walkthrough

Walkthrough

The notebook frame reader now uses the shared incremental NDJSON parser and processes completed records immediately. It warns about unreadable records and passes valid parsed values through frame validation. The shared framer skips UTF-8 byte measurement when the line limit is unbounded. Tests cover chunk boundaries, buffering, malformed and unsupported records, large display data, scan limits, and consumer exception propagation.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 9e8f4

The notebook frame reader appears mergeable after normal checks; no specific behavior change requiring a fix was identified.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 13445

The new reader preserves frame validation and does not appear to expose a new entrypoint. It does, however, parse and hold every complete record in an incoming chunk before delivering the first frame, which could increase memory use when notebook output is unusually dense.

Retained concerns

  • Low · security · inferred: A chunk containing many notebook records is fully JSON-parsed into an unbounded completed-record array before any frame callback runs. Compared with the prior parse-and-deliver loop, this can increase peak main-process memory use and delay delivery of the first frame. The production impact is unmeasured.
Security review details

Security Blast Radius

  • inferred — The added buffering cost is incurred in the desktop main process when its notebook child produces a dense stdout chunk. The evidence does not establish remote reachability or cross-tenant exposure.

Security Findings and Attack Paths

  • inferred — Notebook output with many complete JSON records in one chunk can cause the main process to retain decoded values before delivery. This is an availability exposure; no production exhaustion or attacker route beyond notebook output has been demonstrated.

Trust Boundaries and Controls

  • observed — Records cross from Python subprocess stdout into the main-process reader. The shared parser skips invalid JSON, and parseFrame continues to reject unsupported or invalid frame shapes before delivery.

Resilience and Maintainability Implications

  • observed — A callback exception stops delivery of the current completed batch, while a previously incomplete suffix can be completed on a later read. The exception and reentrant-read tests exercise these transitions.

Hardening Proposals

  • proposed — Consider limiting decoded-record batching or delivering records incrementally, while preserving large single-record support and the existing callback-exception and reentrant-read behavior.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 4 files. 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 clearly identifies the main performance change: avoiding repeated scanning of partial notebook output frames.
Description check ✅ Passed The description is complete and focused. It explains the change, reason, measured impact, trade-offs, linked issue, testing, review status, visual proof, and platform considerations. It also states th…
Linked Issues check ✅ Passed Issue #23137 is closed and supplies historical context only. No active directly linked issue supplies coding requirements for this pull request. The reported changes remain consistent with that histor…
Out of Scope Changes check ✅ Passed The changes stay within notebook frame parsing and its shared incremental NDJSON framer. The tests cover parsing, limits, malformed records, ordering, Unicode, and error propagation. These changes sup…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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 — the notebook kernel reader's output framing was rewritten to reuse the shared incremental NDJSON parser instead of re-splitting a growing buffer on every chunk.

  • Shared parser replaces hand-rolled framing: createFrameReader now feeds chunks through createNdjsonParser, which keeps the pending partial record in segments and only revisits the new chunk — removing the quadratic rescan that dominated large image outputs.
  • parseFrame de-parses: parsing moved into the shared parser, so parseFrame now takes an already-parsed unknown and only validates/normalizes the record shape.
  • Unrestricted size preserved: maxLineBytes: Number.POSITIVE_INFINITY is passed so the shared parser's 16 MiB transport cap does not start dropping existing notebook display frames.
  • New focused suite: notebook-frame-reader.test.ts adds 8 cases covering the delimiter-work budget, split-boundary Unicode, malformed/unsupported/CRLF lines, >16 MiB records, incomplete suffixes, consumer exceptions and reentrancy.

I read the shared framer in full and confirmed frame parity with the previous reader: same \n-only framing, whitespace-only lines skipped, malformed JSON swallowed, non-record JSON dropped, CRLF tolerated by JSON.parse, ordering preserved, and the partial suffix retained before delivery. The framer's pause/pendingInput machinery stays inert without a shouldPause, so records are delivered synchronously within the same feed, matching the old semantics. Both test files pass locally (9 passed / 2 skipped) and pnpm tc:node is clean.

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

@nwparker nwparker added the perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging. label Sep 27, 2026
The reader buffered every record of a chunk before delivering the first one, and
asked the framer for byte accounting it can never use. An unbounded line limit
cannot reject, so the per-segment `Buffer.byteLength` and the rejection-prefix
retention were pure overhead for the notebook and Codex readers; both are now
skipped once, behind a hoisted check. Frames are handed to the consumer as each
line completes, so the first output of a chunk paints without waiting for the
last.

The dropped buffer only ever preserved a trailing partial record across a
consumer throw, which cannot help: that throw leaves the stdout 'data' listener
and takes main down with it. Rejections are no longer discarded either — the
bridge keeps fd 1 to itself, so an unreadable line means the frame channel is
damaged and now says so.

Tests move into notebook-kernel.test.ts beside the reader's existing coverage,
and add the never-terminated record and a guard that no record bytes are
measured when no limit applies.

Co-authored-by: Claude <[email protected]>

@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 — the notebook frame reader was simplified to stream bridge records directly through the shared parser, and the shared framer picked up an unbounded-limit fast path.

  • Direct streaming replaces the pending buffer: createFrameReader now hands child.stdout chunks straight to createNdjsonParser; parseFrame still validates/normalizes each parsed value. The intermediate pending array (and its reentrancy-dependent semantics) is gone.
  • Unreadable records now warn: onError maps to console.warn('[notebook-kernel] …'), so malformed bridge lines are surfaced instead of silently dropped; non-record JSON shapes remain silent.
  • Unbounded fast path in the shared framer: when maxLineBytes === Infinity, segment byte measurement and rejection-prefix retention are skipped, since no line can exceed the limit. This also activates for the codex reader, which likewise passes Infinity.
  • Test consolidation: the standalone notebook-frame-reader.test.ts was folded into notebook-kernel.test.ts.

I read the shared framer in full and traced the unbounded path: with maxLineBytes = Infinity, the derived maxPendingInputBytes/queue caps are Infinity too, so the skipped rememberPrefix and line-length rejection are statically unreachable, and the unterminated-record suffix is still retained in lineSegments. The parseFrame value-shape matrix, \n-only framing, CRLF tolerance, ordering, and skip-on-malformed parity are unchanged from the prior review. Consumer throws still escape onRecord (it sits outside the parse try), and non-EPIPE/EIO uncaught exceptions are fatal in main, so the removed tail-preservation guard has no production reach. Ran the notebook and daemon framing suites: 30 passed / 2 skipped.

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

@nwparker
nwparker merged commit fed613b into main Sep 27, 2026
65 of 67 checks passed
@nwparker
nwparker deleted the nwparker/perf-09-25-notebook-frame-scanning branch September 27, 2026 03:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Large notebook output records repeatedly scan their pending prefix

1 participant