orca icon indicating copy to clipboard operation
orca copied to clipboard

Add daemon stream backpressure contracts and register the reliability gate

Open brennanb2025 opened this issue 5 months ago • 1 comments

Stacked on #7295 (retargets to main when it merges). First of two perf slices from the reliability stack — the deterministic regression net around the daemon output hot path, prioritized for in-flight terminal perf work.

What this does

Product hardening (daemon-stream-data-batcher.ts): daemon stream writes now respect socket backpressure — write(false) pauses further stream writes until drain, queued lines stay bounded (8MB default, newest tail preserved, priority lines protected), interactive session output is re-queued ahead of unrelated backpressured backlog on drain, and global cleanup clears clients that only have backpressured writes. Previously a slow/wedged stream socket could accumulate unbounded queued output or starve interactive output behind a hidden-output flood.

Module split (max-lines): the backpressured write queue and NDJSON frame helpers are extracted into daemon-stream-backpressure-queue.ts and daemon-stream-ndjson-frames.ts; the batcher keeps only batching/flush policy. Behavior-preserving — the contracts are the proof.

Tests: 5 new deterministic fake-socket contracts (pause, queue-until-drain, drain priority, bounded bytes, backpressure-only cleanup) plus the byte-exact 512KB mobile initial-snapshot budget test.

Manifest: re-promotes terminal-performance.daemon-stream-backpressure from registered gap to partial with fresh evidence; extends terminal-runtime.mobile-stream-budget refs and evidence.

Reliability proof

  • Reliability invariant: terminal-performance.daemon-stream-backpressure — daemon socket writes must respect backpressure under output floods and must not starve active input or grow unbounded queues.
  • Material impact: protects the freeze/input-lag/memory-growth class where background terminal floods harm the active terminal, at the daemon seam; gives concurrent perf work a regression net on exactly these paths.
  • Product change type: perf hardening + test-only gate registration.
  • Performance risk inventory: touches PTY output and hidden-output paths (daemon socket writes). No typing, focus, resize, startup, provider listing, polling, or store paths.
  • No-regression evidence: no new timers/polling; queue work is O(lines) on the existing write path with constant-time byte accounting; typecheck:node clean; oxlint clean; the 10 batcher contracts + 29 runtime stream tests pass. Full src/main/{daemon,ipc,runtime} sweep: 3,541/3,544 relevant tests pass; the only failure is the known pre-existing pty-subprocess WSL assertion (fails identically on the untouched base; same known failure noted in #7192).
  • Found and fixed by that sweep: the first cut deferred on any falsy socket.write() return, which broke two daemon-server.test.ts integration tests whose fake sockets return undefined. The queue now defers only on Node's explicit false backpressure signal — duck-typed sockets keep the legacy direct-write path. This is exactly the failure mode focused unit contracts miss and cross-module sweeps catch. Before/after terminal perf artifact (tests/e2e/terminal-typing-latency.spec.ts, electron-headless, same machine, back-to-back): before (v2 base) test body 9.0s, suite 45.5s, passed; after (this PR) test body 9.0s, suite 45.2s, passed. The spec's internal echo-latency thresholds held on both runs — no regression signal.
  • Correctness evidence: pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-stream-data-batcher.test.ts — 10 tests; each backpressure guard was developed red-first on the reliability stack.
  • Provider/platform coverage: daemon provider path, local macOS evidence; SSH/remote-runtime stream paths unaffected (separate transports). Windows/Linux: no platform-specific code touched.
  • Residual gaps: live hidden-output flood and key-latency metric artifacts; the renderer/main ACK + pending-cap extensions arrive in perf slice B (pty.ts/pty-connection.ts hunks reconciled with #7133/#7173).
  • Promotion status: partial/experimental; not blocking. Promotion requires aggregated CI history.
  • Rollback/demotion rule: if the batcher contracts flake or the bounded-queue trim is observed dropping non-flood interactive output, demote the gate and revert the queue bound while keeping the pause/drain contracts.

Adversarial review round

Per the reliability plan's review discipline, this PR got a deep adversarial pass before merge: a baseline review plus three independent Codex reviewers (gpt-5.5, xhigh reasoning, read-only sandbox) with distinct lenses — correctness/lifecycle, environment/consumer matrix, and adversarial scenarios.

Found and fixed (High, 4/4 independent detections): exit frames were written directly to the stream socket (daemon-server.ts real + synthetic exit sites) and could overtake output held in the backpressure queue, so under socket backpressure the wire order became data-prefix → exit → data-tail. The client tears down session state on exit (daemon-pty-adapter.ts, pty-transport.ts unregister handlers), so the final output tail could be silently lost — the exact class the original "flush final output first" comment was written to prevent. Both exit sites now route through writeEventLine on the same ordered path; the priority splice places the exit after the session's own queued output, ahead of unrelated sessions' backlog, and protects it from bounded-queue trimming. The regression test at the daemon-server seam was proven red against the pre-fix branch.

Found and documented (Medium): the queue byte bound is soft by one frame — the sole remaining line is never dropped (dropping it would lose data for no benefit), so the effective cap is maxQueuedBytes plus at most one frame (frames are capped at the NDJSON line limit). Now documented in the code and the gate's coverage notes.

Clean across all lenses: drain/close/error listener pairing over repeated defer cycles, re-entrant drain writes, socket replacement while deferred, byte-accounting drift, same-session ordering under the priority splice, NDJSON wire-format compatibility (old daemon binaries persist across updates — no wire change), and SSH/remote stream paths.

Post-review validation: 32 daemon-server + batcher tests green (including the new red-proven exit-ordering test), full src/main/{daemon,ipc,runtime} sweep 3,530 passed with only the known pre-existing WSL failure, checker green for 27 gates, typecheck clean.

Second (Fable) review round

A single Fable 5 reviewer then attacked the post-fix state with fresh eyes. It verified the exit-ordering fix's priority-splice compositions safe (session-id reuse after a queued exit, drain re-defer ordering, multiple exits FIFO) and the manifest honest (re-ran both gate commands, checked every assertionRef against a real test) — and found three real issues, now fixed:

  • Medium (fixed, red-proven): the onExit closure holds the ConnectedClient captured at createOrAttach, which goes stale when a same-clientId reconnect replaces it (a supported, tested path). Routing exit through the queue with that stale destroyed socket tripped the queue's clear-on-mismatch and wiped the live socket's queued output for every session of the client, then wrote the exit to the dead socket. onExit now resolves the current client; regression test simulates the reconnect. This also fixes the pre-existing sibling bug on main where post-reconnect exit frames were silently written to the dead socket.
  • Low (fixed, red-proven): writes aimed at an already-destroyed socket deferred into a pending entry whose drain/close can never fire (bounded leak + swallowed frame). The queue now drops destroyed-socket writes without touching the live queue.
  • Low (fixed, docs): the "priority protects exit from trimming" comment overclaimed — trimming prefers non-priority lines, but an all-priority overflow (>8MB of priority-only frames) can still drop the oldest. Comment corrected; the regime is unreachable in practice (interactive frames are ≤1024 chars).

Post-round validation: 34/34 tests in the touched files (both new tests proven red first), full src/main/{daemon,ipc,runtime} sweep green except the known pre-existing WSL failure, checker green for 27 gates, typecheck clean.

Made with Orca 🐋

brennanb2025 avatar Jul 04 '26 02:07 brennanb2025

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
📝 Walkthrough

Walkthrough

This PR adds NDJSON framing helpers and a bounded per-client backpressure queue for daemon stream output. DaemonStreamDataBatcher now writes through the queue, supports prioritized session flushing, and clears queued state on cleanup. Exit events are routed through the batcher so ordering follows the same backpressure path. Tests cover drain behavior, queue bounds, exit ordering, mobile snapshot downgrading to a 512KB budget, and per-frame payload size limits. Reliability gate metadata is updated for daemon backpressure and mobile stream budget coverage.

Changes

Cohort / File(s) Summary
NDJSON framing New encoding, sizing, and surrogate-aware splitting helpers for stream-data NDJSON lines.
Backpressure queue New per-client queued socket write class with drain-based flushing and byte-budget enforcement.
Batcher integration Batcher now writes through the queue, supports prioritized session output, and clears queued state.
Exit routing Exit events now flow through stream-data batching, with backpressure-aware ordering coverage.
Batcher tests New coverage for pause/resume on drain, listener cleanup, ordering, and bounded queue behavior.
Live socket tests New end-to-end coverage for bounded queues, trimming, exit ordering, foreground priority, and reconnect routing.
Mobile/runtime tests New mobile snapshot downgrade test and an added per-frame payload size assertion.
Reliability gates Updated protection, coverage notes, assertion refs, evidence runs, and known gaps.

Sequence Diagram(s)

sequenceDiagram
  participant DaemonStreamDataBatcher
  participant BackpressuredStreamWriteQueue
  participant Socket

  DaemonStreamDataBatcher->>BackpressuredStreamWriteQueue: write(clientId, streamSocket, lines)
  BackpressuredStreamWriteQueue->>Socket: socket.write(line)
  Socket-->>BackpressuredStreamWriteQueue: false
  BackpressuredStreamWriteQueue->>BackpressuredStreamWriteQueue: defer remaining lines
  Socket-->>BackpressuredStreamWriteQueue: drain
  BackpressuredStreamWriteQueue->>Socket: flush queued lines

Compact metadata

  • Related issues: None specified.
  • Related PRs: None specified.
  • Suggested labels: terminal, reliability, performance
  • Suggested reviewers: None specified.

Poem A queue holds streams until the drain, NDJSON lines are trimmed by byte and grain, mobile snapshots step down to fit the frame, and gates record the bounds by name.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is on-topic but does not follow the required template sections for Summary, Screenshots, Testing, AI Review Report, Security Audit, or Notes. Reformat the PR description to include all required headings and fill in testing, screenshots or no visual change, AI review, security, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: daemon stream backpressure work plus reliability-gate registration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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[bot] avatar Jul 04 '26 03:07 coderabbitai[bot]

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-06T23:56:08Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

OrcaWin avatar Oct 27 '26 09:10 OrcaWin

Superseded: daemon stream backpressure is on main.

brennanb2025 avatar Nov 16 '26 09:11 brennanb2025