Skip to content

feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) - #24402

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/node-rt-p3-t2-p4a
Oct 1, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/node-rt-p3-t2-p4a

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​112 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​110
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​130 $\color{#cf222e}{\Huge{\mathbf{−}}}$​51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​79

ELI5

The background terminal process (the "daemon") can restart a terminal's shell while the terminal tab stays open. Until now, the output it sent back carried no marker of which run of the shell produced it. This change stamps each output message with that run's id. Nothing reads the stamp yet. It lays the groundwork for later work that needs to tell old output from new.

This is the T2 P4a slice of porting #16741 (daemon stream incarnation ids).

What Changed

Before: a data event on the daemon stream carried the bytes plus seq, rawLength and transformed, but nothing that identified the PTY incarnation (the specific spawn of a session) that wrote them.

After: payload.incarnationId is an optional field on the existing data event.

  • Session gives the id it already has (Session.incarnationId) to its output plane.
  • SessionOutputPlane passes it to stream clients that register the new optional onDataWithIncarnation callback. The daemon's terminal admission does. Clients that only register onData get exactly the old callback shape.
  • The daemon stream batcher carries the id per queued entry. It never merges output from two incarnations into one entry. It counts the field's bytes when splitting an oversized line, so split lines still fit the size limit.
  • The renderer and desktop app don't change. No reader uses the field yet.

Why

The terminal daemon outlives app updates, so an old app and a new daemon (or the reverse) talking to each other is the normal case. A new optional field on an existing NDJSON event is the one change both sides tolerate without negotiation: older readers parse the line with JSON.parse and pick only the fields they know. That follows docs/reference/remote-wire-compatibility.md, Rule 1.

I considered two alternatives, a new event type and a protocol version bump. A new event type would be dropped by older readers. A version bump would strand live terminals across the upgrade.

node config/scripts/check-daemon-protocol-crossing.mjs reports the candidate at daemon protocol 38. That is unchanged from main: this PR doesn't touch daemon-protocol-version.ts. Upgrading from v1.4.218 still adopts live terminals.

Adapted from #16741 (a68b6f3), by hunk:

  • Skipped daemon-pty-event-subscriptions.ts entirely. Its change is idle-daemon retirement (requestIdleRetirement), which is a different slice.
  • Skipped Session.createdAt and its terminal-host test. They belong to a different slice.
  • Skipped the daemon-pty-adapter reader-side tests, because the adapter doesn't read the field yet.
  • Kept main's reworked batcher, entry accounting and per-session flush, and added the field to each. That includes the new flushDaemonStreamSession path, which the branch never had.
  • Took the branch's import type * as SessionProtocol change in session.ts. It keeps the file within the 300-line lint limit.

Linked Issue

Part of the Node runtime plan (Phase 3), porting #16741.

Visual Proof

N/A. This is an internal daemon wire field. Terminal behavior and the UI don't change.

Testing

  • New tests:

    • in daemon-stream-incarnation.test.ts:
      • output from two incarnations is never merged;
      • a per-session flush writes the id, and leaves it out when it is absent;
      • only clients that are aware of the id receive it, and legacy clients keep the old callback.
    • Ported batcher and split tests: the id survives serialization, the single-encode fast path keeps it, and oversized writes count its bytes.
  • Regression:

    • every src/main/daemon/*.test.ts: 203 files, 2282 passed, 15 skipped;
    • check-daemon-protocol-crossing and daemon-protocol-facts tests: 20 passed.
  • macOS locally.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

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.

 T2 P4a)

Each data event the terminal daemon writes now carries an optional
payload.incarnationId naming the PTY incarnation that produced the bytes, so a
later consumer can tell output of a respawned session from its predecessor.

- Session hands its incarnation to the output plane; identity-aware stream
  clients receive it through onDataWithIncarnation, legacy clients keep the
  old callback shape.
- The stream batcher never merges queued output across incarnations and
  budgets the field when splitting oversized lines.
- Optional NDJSON field only: no new event type, no protocol version change
  (check:daemon-protocol-crossing is unchanged), and older readers ignore it.

Ported by hunk from #16741 (a68b6f3).
@coderabbitai

coderabbitai Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered

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: 69b74254-16cf-44b4-9cff-4a8c285cdf3c

📥 Commits

Reviewing files that changed from the base of the PR and between c991893 and 9ff76e3.

📒 Files selected for processing (13)
  • src/main/daemon/daemon-stream-data-batcher.test.ts
  • src/main/daemon/daemon-stream-data-batcher.ts
  • src/main/daemon/daemon-stream-data-entry.ts
  • src/main/daemon/daemon-stream-data-split.test.ts
  • src/main/daemon/daemon-stream-data-split.ts
  • src/main/daemon/daemon-stream-events.ts
  • src/main/daemon/daemon-stream-incarnation.test.ts
  • src/main/daemon/daemon-stream-keep-tail-drop.ts
  • src/main/daemon/daemon-terminal-admission.ts
  • src/main/daemon/session-output-pipeline.ts
  • src/main/daemon/session-output-plane.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host-create-contract.ts

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


📝 Walkthrough

Walkthrough

Session output now carries PTY incarnation IDs through identity-aware callbacks and stream batching. Queued entries retain their IDs and remain separate when adjacent entries have different IDs. Encoded data events include the ID when supplied, and chunk sizing accounts for the added field. The changes also add tests for callback forwarding, queue coalescing, serialized payloads, and oversized writes.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 9ff76

This change adds an optional metadata field to daemon stream data events. Existing clients keep the old callback behavior, and nothing reads the new field yet, so merge risk is minimal.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 9ff76

The new field is optional, and the inspected output path retains existing authentication and session routing. No introduced security vulnerability was established. Some recovery output remains untagged, and compatibility with released versions was not directly verified, so the assessment retains limited uncertainty.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — For the inspected route, process-controlled terminal bytes reach the existing authenticated client stream under client/session routing. The added metadata does not itself introduce a new subscriber, credential authority, or output destination. Broader deployment exposure was not established by the supplied evidence.

Trust Boundaries and Controls

  • observed — Admission requires an authenticated control/stream pair and rechecks connection state after asynchronous host creation. Output remains bound to the requesting client and resolved session; missing or destroyed stream sockets are rejected by batching.

Resilience and Maintainability Implications

  • observed — Backpressure retains queued entries and their metadata for later flushing. Socket loss clears transient delivery state under the documented snapshot-recovery model; keep-tail output is a monitoring feed rather than the complete terminal model. These paths do not make incarnation metadata a complete recovery guarantee.

Hardening Proposals

  • proposed — Before using incarnation identity to reject stale output or enforce a security decision, define handling for absent identity, gap controls, and salvaged query bytes. Validate those semantics across mixed-version peers and repeated drop/recovery transitions.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 13 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 and concisely describes the main change: adding PTY incarnation IDs to daemon stream data.
Description check ✅ Passed The description is detailed and covers the change, rationale, compatibility, testing, and visual proof. The linked issue is referenced as #16741 but is not provided as an actual issue link, and the No…
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.
  • 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

Autopilot is currently an internal CodeRabbit preview.


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.

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Adds PTY incarnation tracking to daemon stream data.

The PR appears safe to merge; no actionable regression was identified.

Summary

The PR adds an optional PTY incarnation ID to daemon data events while preserving legacy callbacks and the existing event format.

  • Passes the Session ID through the output plane and terminal admission to the stream batcher.
  • Keeps queued output from different incarnations separate and includes the ID when serializing and sizing data events.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Session["Session incarnation ID"] --> Plane["SessionOutputPlane"]
  Plane --> Admission["Terminal admission callback"]
  Admission --> Batcher["Per-client stream batcher"]
  Batcher --> Event["data event: optional payload.incarnationId"]
Loading

Reviews (1) · Last reviewed commit: "feat(daemon): tag daemon stream data wit..."

@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 blocking issues — one forward-looking observation on the drop-salvage path.

Reviewed changes

  • Optional incarnationId on the daemon data event — daemon-stream-events.ts gains the optional payload field; daemon-stream-data-split.ts emits it and now encodes it inside the line-size probe, so oversized writes still budget the field and split chunks stay under the byte cap.
  • Session → output plane → admission threading — session.ts passes its incarnationId into the pipeline/plane; session-output-plane.ts routes broadcasts through a new broadcastData helper and offers an optional onDataWithIncarnation; legacy onData clients keep the exact pre-PR argument shape.
  • Batcher entry tagging — entries carry the id and only merge within the same incarnation; the bulk-slice and per-session flush paths forward it (daemon-stream-data-entry.ts, daemon-stream-data-batcher.ts, daemon-stream-keep-tail-drop.ts).
  • Tests — new daemon-stream-incarnation.test.ts plus additions to the split/batcher suites; all 44 pass locally.

ℹ️ The never-merge invariant does not cover the keep-tail salvage path

appendDaemonStreamData correctly refuses to merge entries from different incarnations, and the slice/flush paths never rewrite an entry's id. But dropOldestQueuedForSession concatenates salvaged bytes from every dropped entry of a session into one untagged entry, so a drop span that crosses an incarnation boundary yields a single entry whose data mixes two incarnations and carries no id. It is inert today because no reader consumes the field, but the PR's "never merges output from two incarnations into one entry" claim does not hold end to end, and a future incarnation-aware consumer cannot assume per-entry purity.

Technical details
# Keep-tail salvage crosses incarnation boundaries

## Affected sites
- `src/main/daemon/daemon-stream-keep-tail-drop.ts:106` — `salvageIntoCap` accumulates every dropped entry's bytes, with no `incarnationId` grouping.
- `src/main/daemon/daemon-stream-keep-tail-drop.ts:128` / `:141` — full drops and partial cuts both feed the shared buffer.
- `src/main/daemon/daemon-stream-keep-tail-drop.ts:196` — the single salvaged entry is inserted with no `incarnationId`.
- `src/main/daemon/daemon-stream-data-entry.ts:29` — the append-time guard only covers entries it creates; it never sees the salvage entry's provenance.

## Required outcome
- Either record explicitly (field doc / comment) that a queued entry is not guaranteed to carry output from one incarnation, or preserve the invariant by splitting the salvage buffer at incarnation boundaries and tagging each resulting entry where a single id applies.

## Why it is reachable
A droppable session (backgrounded, or stall-released) can hold incarnation A's entries under a deep socket; on exit `flush` holds rather than writes them, a respawn creates incarnation B for the same session id, and B's backlog then trips `dropOldestQueuedForSession` across both. Bytes from A and B land in one `salvaged` string and one untagged entry.

## Open questions for the human
- Does the eventual T2 P4 consumer treat an absent `incarnationId` as "unknown" (safe) or "current" (misattributes salvaged bytes)? That decides whether this needs fixing in this slice or only documenting.

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

@OrcaWin
OrcaWin merged commit 817af76 into main Oct 1, 2026
45 checks passed
OrcaWin added a commit that referenced this pull request Oct 2, 2026
* Revert "feat(orcad): source-side dormant export of a relay-hosted SSH target (#16741 T6-8) (#24519)"

This reverts commit 783101b.

* Revert "feat(ssh): update, roll back, recover and stop a managed orcad server (#16741 T6-5 follow-up) (#24463)"

This reverts commit 38c2d1d.

* Revert "feat(ssh): deploy and pair an empty managed orcad server over SSH (#16741 T6-5) (#24453)"

This reverts commit 8b76683.

* Revert "fix(ssh): orcad GC honors the activation journal; readiness requires proven daemon coverage (#16741 T6 follow-up) (#24451)"

This reverts commit d3f8c50.

* Revert "feat(ssh): remote orcad stop by request file and journaled decommission (#16741 T6-4) (#24449)"

This reverts commit 43d9b43.

* Revert "feat(orcad): supervisable server: stop requests, managed stop receipts and a lifetime that keeps its lock on failed teardown (#16741 T6-3) (#24433)"

This reverts commit b093d3a.

* Revert "feat(ssh): crash-safe orcad activation, rollback and recovery (#16741 T6-2) (#24423)"

This reverts commit 1a9ac0e.

* Revert "feat(runtime): SSH access links for paired servers in a downgrade-safe sidecar (#16741 T5-1+T5-2) (#24420)"

This reverts commit 99db2bf.

* Revert "feat(relay): capability-gated owner reset with a durable preparation journal (#16741 T3 R1) (#24418)"

This reverts commit 34a582b.

* Revert "feat(ssh): track connection-manager drains, test probes and provider continuations (#16741 T2 P3+P8a) (#24407)"

This reverts commit d53063d.

* Revert "feat(daemon): idle retirement, session census and recovery-only provider (#16741 T2 P4b) (#24409)"

This reverts commit ff212db.

* Revert "feat(ssh): add pty.resumeClient and split SSH PTY process listing (#16741 T2 P5+P6) (#24414)"

This reverts commit 92cb717.

* Revert "feat(relay): await owned watcher and agent children on shutdown (#16741 T2 P1) (#24400)"

This reverts commit 6b36e4f.

* Revert "feat(session): retry failed renderer session writes and verify local folder PTYs (#16741 T2 P9) (#24406)"

This reverts commit d23ecef.

* Revert "feat(ssh): remote orcad primitives on the pinned Node runtime (#16741 T6-1) (#24419)"

This reverts commit dd87ae5.

* Revert "fix(runtime): fence runtime-environment subscriptions and status probes by identity (#16741 T5-3) (#24421)"

This reverts commit ece9e4d.

* Revert "feat(orcad): migration manifest and dormant-state contracts (#16741 T6-7) (#24422)"

This reverts commit 3fbdaba.

* Revert "feat(ssh): wire SshConnection through the work and transport close ledgers (#16741 T2 P2) (#24401)"

This reverts commit 4e8edc8.

* Revert "feat(profiles): carry markdown frontmatter visibility in project transfers (#16741 T2 P7) (#24405)"

This reverts commit 60c9326.

* Revert "fix(runtime): project the PTY incarnation onto mobile session tabs (#24413)"

This reverts commit 99e0303.

* Revert "feat(daemon): tag daemon stream data with the PTY incarnation id (#16741 T2 P4a) (#24402)"

This reverts commit 817af76.

* Revert "feat(ssh): port the SSH connection work ledger and transport close ledger (#16741 T2) (#24210)"

This reverts commit c991893.

* Revert "feat(relay): fence and drain file and git response streams on shutdown (#24185)"

This reverts commit dc08ffe.

* Revert "refactor(runtime-rpc): extract the Node WebSocket lifecycle; opt-in pinned port (#24186)"

This reverts commit a789233.

* Revert "feat(relay): route relay handlers through work admission; producer publication drain (#24181)"

This reverts commit 0b812bd.

* Revert "feat(relay): land the #16741 T1 seam (work drain, publication drain, release gate) (#24156)"

This reverts commit 3aa2d3a.

---------

Co-authored-by: m4air <[email protected]>
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