Skip to content

fix(ssh, relay): keep remote sessions alive through reconnects and backpressure - #11999

Merged
AmethystLiang merged 10 commits into
mainfrom
P0
Aug 1, 2026
Merged

AmethystLiang merged 10 commits into
mainfrom
P0

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Separate SSH reconnect delay progression from the failed-handshake budget so repeated post-handshake drops back off correctly without prematurely giving up.
  • Keep relay overload nonfatal: size watcher batches per client, bound overflow resync markers, preserve terminal completion delivery, and return a JSON-RPC error for oversized responses instead of disconnecting the host.
  • Preserve agent-hook state through bounded shedding and retry, with turn and digest validation before restoring omitted fields.

User impact

Remote workspaces and PTYs remain available through watcher floods, large filesystem responses, transient producer congestion, and repeated network flaps. A slow client no longer forces healthy peers to use its smaller frame capacity or resynchronize their file trees.

Agent status remains coherent when payloads must be reduced: active subagent state is restored safely, interactive prompts are compacted for waiting states, and stale shed data is not resurrected.

Implementation details

  • Introduces an SSH reconnect ladder with independent delay and failure counters, capped to remain within the relay grace window.
  • Publishes watcher chunks and agent-hook envelopes per client, using exact encoded-byte budgets and per-client retention checks.
  • Sends one outstanding watcher overflow marker per client and root on a nonfatal control-lane path.
  • Holds filesystem stream capacity until terminal frames settle and substitutes ResponseOverCapacity for responses that cannot fit.
  • Restores shed agent-hook fields only when their digest and turn identity match the current payload.

Screenshots

No visual change.

Testing

  • Focused Vitest coverage for SSH reconnects, relay watcher chunking, capacity degradation, oversized notifications, and watcher lifecycle: 173 tests passed
  • pnpm run typecheck:node
  • Commit hook completed oxlint and oxfmt
  • Full pnpm test
  • pnpm build

AI Review Report

The review examined reconnect accounting, relay frame admission, producer/control-lane failure behavior, overflow-marker lifecycle, per-client isolation, terminal-frame settlement, agent-hook retry and shedding, stale-generation handling, and response-size failure semantics. Follow-up fixes added exact byte sizing, bounded marker suppression, per-client low-water checks, turn/digest validation, and explicit regression coverage.

Cross-platform compatibility was checked for macOS, Linux, and Windows. Runtime path grouping uses the existing cross-platform path resolver; no keyboard shortcuts, labels, UI behavior, or platform-specific shell construction were introduced. SSH-hosted and folder-workspace behavior remain in scope.

Security Audit

Reviewed remote event paths and JSON-RPC payloads as untrusted inputs, ensuring they are encoded within bounded frame budgets and cannot close the connection through an oversized producer frame. Oversized request responses now fail only the request. Shed agent state is restored only after matching the current turn and digest, reducing stale-state injection risk.

The change does not add dependencies, credentials, secret storage, or new command interpolation. No unresolved security follow-up was identified.

Notes

The main residual behavior is intentional fail-soft degradation: when a client cannot accept a watcher batch, it receives a bounded overflow resync marker rather than forcing the entire SSH connection to restart.

AmethystLiang and others added 6 commits July 31, 2026 22:10
…and frame caps

Three independent connection killers found in the SSH/remote freeze audit.

FINDING A - the reconnect ladder never escalated for post-handshake drops.
scheduleReconnect() used the single published state.reconnectAttempt for both
the delay index and the give-up test, and runReconnectAttempt() zeroed it
before connecting (ssh.ts gates the relay redeploy on 0-at-connected). Every
post-handshake drop therefore re-entered at 1000ms forever, ~3600 relay
redeploys/hour, and 'reconnection-failed' was unreachable for a flapping host.
New SshReconnectLadder splits the delay index (advanced by every retry) from
the failure streak (advanced only by a failed handshake), so flaps back off
while give-up semantics stay byte-identical to shipped.

FINDING B - notify() closed the client whenever a frame exceeded the producer
frame capacity, conflating a permanently un-sendable frame with transient
backpressure. A 5000-event fs.changed is 425KB against a 49KB cap, so the
watcher flood killed the link and re-killed on every reattach+replay. notify()
now drops and logs once per generation; fs.changed is chunked to each sink's
capacity with a control-lane overflow marker as the resync fallback; agent-hook
envelopes shed lastAssistantMessage/interactivePrompt/subagents to fit.

FINDING B2 - sendResponse routed >1MB responses to a lane whose admission
ignores the frame cap and closed the client on rejection, so a large
fs.listFiles dropped the SSH host. It now substitutes a JSON-RPC error so the
request fails instead of the connection.

Also moves fs.streamEnd/fs.streamError to the control lane so a terminal frame
cannot be dropped by the producer-lane check.

Co-authored-by: Orca <[email protected]>
…ects

Round-1 review fixes on the P0 freeze work.

The control-lane overflow marker could reinstate the exact failure this P0
removes: dispatcher-client-writer closes the client when control-lane
admission fails, and admitControl is the only lane that returns an error, so
one marker per failing batch accumulated to the 256-frame/1MB bound and
dropped the link. Markers are now deduped to one outstanding per
(client, root), cleared on settle.

Chunking also defeated the renderer's per-payload directory dedupe -- events
are now stable-grouped by parent directory so one directory lands in one
chunk -- and the halving walk overshot the byte minimum ~1.7x while the fast
path paid three JSON encodes; both are fixed by publishing first and sizing
from a measured bytes-per-event estimate.

Agent-hook shedding now surrenders the blocking interactive prompt LAST
rather than first, so a degraded envelope cannot strand a pane at
state=waiting with no answerable question card.

The dropped-notification log now distinguishes over-capacity from producer
queue backpressure and no longer lets the first dropped method silence every
other producer for the life of the connection.
… one freeze for another

Round-2 review fixes.

The round-0 change from close-on-rejection to silent drop removed the only
redelivery path for agent.hook envelopes: they are fire-and-forget and the
per-pane cache only replays on handler install, so a saturated link stranded
a pane on a stale Working spinner until reconnect. Closing used to guarantee
delivery by forcing that replay. Envelopes now publish per client and pend
for bounded latest-wins redelivery when the producer queue rejects them.

Shed fields are now named on the wire. The subagent roster is not cosmetic --
the renderer replaces rather than merges it, and hibernation gates on its
length -- so an unmarked shed could sleep a live pane.

fs.streamEnd rode the control lane because it must not be dropped, but that
lane kills rather than drops. The stream's concurrency slot is now held until
the terminal frame settles rather than until the fd closes, capping queued
terminal frames well under the control budget; overflow costs one refused
read instead of the connection.

The watcher chunk walk now stops while producer retention sits past its
reserve and degrades to a resync, so a 5000-event flood cannot fill the queue
that interactive PTY traffic shares and stall every remote terminal.

The reconnect ladder caps its flap-path delay so delay plus handshake timeout
cannot cross the relay grace floor and let the remote daemon kill live PTYs.

Also: the suppression key no longer embeds a NUL byte, which had made the
file binary to git and grep; producerEnvelopeBudget no longer reports
infinite capacity for a departed client; the drop logger no longer encodes a
frame it will not log; and an over-capacity response substitution no longer
settles as if the result had been delivered.
…re per client

Round 3 + 4 review fixes.

Watcher chunking is now gated on the *client's* retention reserve rather than
the dispatcher-wide one, so one stalled peer no longer forces a healthy client
into a full file-tree resync. The relay-lost redeploy ladder no longer burns its
6-attempt budget while the SSH transport itself is down: it holds at the 15s step
with a non-terminal status and rearms, so a laptop that slept past the ladder
comes back instead of landing on a terminal "give up" banner.

The shedFields wire marker had no consumer, so an agent-hook envelope whose
subagent roster was dropped to fit the frame read as "roster cleared" on the Orca
side: live child rows blanked and a done pane became hibernation-eligible while
its teammates were still running. ingestRemote now restores shed fields from the
cached payload (interactivePrompt deliberately excluded — a stale answerable
question card is worse than none).

Also: stream terminal-frame slots are counted per client, since the control queue
they protect is per client; the chunking fast path no longer logs a drop for a
batch it goes on to deliver in full; -32010 is now RelayErrorCode.ResponseOverCapacity.

Test debt from the review: pending-pane eviction, per-client stream isolation, and
the reconnect budget are now asserted rather than assumed; four fragile exact-byte
pins dropped in favour of the tier comparisons that carry the requirement.
- Oversized relay responses now fail their request instead of closing the connection,
  preventing one frame from killing every pane on the host
- Restore subagent state for correct hibernation; don't resurrect stale prose
  across turns
- Account for relay re-establishment and PTY reattach time in SSH flap delay caps
- Only log drops of final unsendable envelopes, not temporary rejections during
  measurement probes
- Fix watcher overflow marker release race when notification admission rejects
  without settlement; use precise byte counting for event batching
Validate that shed subagent rosters match their wire digest and turn identity before
restoration, preventing stale roster resurrection. Compact interactive prompts for waiting
states instead of dropping them. Demote control-queue overflow to non-fatal rejection so
clients can retry on capacity recovery, keeping the link alive during transient backpressure.
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 435c52cb-a495-4449-98d7-576fa802cbce

📥 Commits

Reviewing files that changed from the base of the PR and between 4ac4eda and 2eff180.

📒 Files selected for processing (6)
  • src/main/ipc/ssh.ts
  • src/relay/dispatcher-capacity-degradation.test.ts
  • src/relay/dispatcher-client-writer.ts
  • src/relay/dispatcher-writer-admission.ts
  • src/relay/dispatcher.ts
  • src/relay/fs-handler-stream.test.ts

📝 Walkthrough

Walkthrough

The changes add bounded relay publication with payload shedding, prompt compaction, redelivery, and per-client capacity handling. Watcher and file-stream delivery now use targeted queues, frame budgeting, and overflow recovery. SSH reconnect logic separates flap delays from handshake failures and coordinates relay retries with transport state. Agent-hook envelopes now carry shed-field metadata and can restore verified cached subagent rosters. The dispatcher distinguishes producer and control overflow, returns structured errors for oversized responses, and allows callers to mark control overflow as non-fatal.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% 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 clearly summarizes the main SSH reconnect and relay backpressure changes.
Description check ✅ Passed The description covers all required sections, testing status, AI review, security audit, and platform compatibility.
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: 1

🧹 Nitpick comments (3)
src/main/ipc/ssh.ts (1)

748-786: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider consuming an attempt when a deferred redeploy actually runs.

The wait path schedules a redeploy without incrementing state.attempts. When the timer fires and the transport is connected, s.reconnect(...) runs a real relay deploy that no attempt accounts for. If the transport alternates between reconnecting and connected, the relay can be redeployed repeatedly without ever reaching RELAY_LOST_MAX_ATTEMPTS, which is the bound this backoff exists to enforce. Incrementing state.attempts immediately before the deferred s.reconnect(...) keeps the budget aligned with executed deploys, while still not charging attempts for pure waiting.

♻️ Proposed adjustment
         const status = connectionManager?.getState(tid)?.status
         if (status === 'connected') {
+          // Why: a deferred redeploy is a real attempt; charge it so the max-attempt bound still applies.
+          state.attempts += 1
+          relayLostBackoff.set(tid, state)
           void s.reconnect(liveConn, relayGracePeriodForTarget(t))
           return
         }
src/relay/fs-handler-stream.test.ts (1)

456-456: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the fixture size from STREAM_CHUNK_SIZE.

The comment states "one chunk per stream", but the size is the literal 64 * 1024. If STREAM_CHUNK_SIZE changes, the comment becomes wrong and each stream emits several chunks. The test still passes, because it counts only terminal frames. The file already imports STREAM_CHUNK_SIZE at line 5.

♻️ Proposed change
-    writeFileSync(filePath, Buffer.alloc(64 * 1024, 0x42)) // one chunk per stream
+    writeFileSync(filePath, Buffer.alloc(STREAM_CHUNK_SIZE, 0x42)) // one chunk per stream
src/relay/dispatcher-writer-admission.ts (1)

30-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Prefer an explicit entry field over encoder identity for the non-fatal flag.

markControlOverflowNonFatal carries the flag out of band, keyed on the encode function identity. Any future code that wraps or replaces encode between enqueueFrame and admitControl loses the mark. Control overflow then closes the client again, which is the failure this PR removes. An explicit field on DispatcherWriterEntry (for example overflowIsNonFatal) makes the contract type-checked and removes the module-level WeakSet.

♻️ Sketch
 export type DispatcherWriterEntry = {
   lane: DispatcherWriterLane
   encode: () => Buffer
   estimatedBytes: number
   onSettled: (result: DispatcherWriterSettlement) => void
   settled: boolean
+  overflowIsNonFatal?: boolean
 }
   private admitControl(entry: DispatcherWriterEntry): AdmissionResult {
-    // Why: best-effort controls may fail soft without weakening protocol-critical admission.
-    const overflowIsNonFatal = nonFatalControlEncodes.delete(entry.encode)
+    // Why: best-effort controls may fail soft without weakening protocol-critical admission.
+    const overflowIsNonFatal = entry.overflowIsNonFatal === true

Also applies to: 152-161


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 277ba578-3fcf-4899-845c-18fb8be1ff8d

📥 Commits

Reviewing files that changed from the base of the PR and between b04c695 and fdb3271.

📒 Files selected for processing (27)
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/ssh.ts
  • src/main/ssh/ssh-connection.test.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ssh/ssh-reconnect-ladder.test.ts
  • src/main/ssh/ssh-reconnect-ladder.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-envelope-publication.test.ts
  • src/relay/agent-hook-envelope-publication.ts
  • src/relay/agent-hook-integration.test.ts
  • src/relay/dispatcher-capacity-degradation.test.ts
  • src/relay/dispatcher-writer-admission.ts
  • src/relay/dispatcher.ts
  • src/relay/fs-handler-file-read.ts
  • src/relay/fs-handler-stream.test.ts
  • src/relay/protocol.ts
  • src/relay/relay-filesystem-watch-registry.test.ts
  • src/relay/relay-filesystem-watch-registry.ts
  • src/relay/relay-oversized-notification-survival.test.ts
  • src/relay/relay-watcher-event-emitter.test.ts
  • src/relay/relay-watcher-event-emitter.ts
  • src/relay/relay.ts
  • src/relay/wsl-agent-hook-relay.ts
  • src/shared/agent-hook-relay.test.ts
  • src/shared/agent-hook-relay.ts

Comment thread src/relay/protocol.ts Resolved
@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds three orthogonal resilience improvements to the SSH + relay stack: (1) a two-counter reconnect ladder that separates delay back-off from handshake-failure budget so repeated post-handshake drops back off without consuming the give-up quota; (2) per-client watcher batch sizing and one-outstanding overflow marker per (client, root) pair, turning relay overload from a connection-killing event into a bounded resync; and (3) capacity-aware agent-hook envelope publication with turn/digest validation before restoring shed fields, preventing stale state injection.

  • SSH reconnect ladder: introduces SshReconnectLadder with independent delayIndex and consecutiveFailedAttempts counters, capped to FLAP_DELAY_CAP_MS and clears relay-lost backoff on fresh-transport reconnects.
  • Relay watcher chunking: publishes fs.changed batches per client against each client's exact frame budget, falls back to a single bounded overflow marker on the control lane.
  • Agent-hook envelope publication: sheds optional payload fields in priority order, retries queue-full rejections up to MAX_REDELIVERY_ATTEMPTS, and restores shed subagents only when wire digest and turn identity match.

Confidence Score: 5/5

Safe to merge; all three subsystems are carefully isolated and the edge cases are explicitly handled and covered by 173 focused tests.

The reconnect ladder correctly separates delay back-off from the handshake-failure budget, the per-client watcher chunking with the one-outstanding overflow marker prevents producer-lane starvation, and the shed-field restoration is gated on both digest and turn identity. No path was found that silently drops state, closes a connection incorrectly, or leaks an outstanding marker slot.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/ssh/ssh-reconnect-ladder.ts New class encapsulating reconnect policy with independent delay/failure counters; FLAP_DELAY_CAP_MS calculation and per-attempt increment logic are correct.
src/main/ssh/ssh-connection.ts Switches from inline reconnect state to SshReconnectLadder; markConnected/markAttemptFailed call sites are correct and reset() is called on fresh connect() success.
src/main/ipc/ssh.ts Adds TRANSPORT_TERMINAL_STATUSES guard and clearRelayLostBackoff on transport reconnect; relay-lost budget correctly preserved across transport outages and reset on a fresh transport generation.
src/relay/relay-watcher-event-emitter.ts Per-client chunking with exact eventsCapacity budget; batchBytes <= eventsCapacity early-overflow correctly handles queue-full; one-outstanding overflow marker per (client, root) prevents marker flooding.
src/relay/agent-hook-envelope-publication.ts New module; shedding loop, MAX_PENDING_PANES eviction, redelivery timer, and runFinalCapacityPass all look correct; MAX_PENDING_PANES is now enforced via the delete-then-set eviction loop at line 245.
src/relay/dispatcher.ts Adds publishProducerNotification, producerRetentionBelowLowWater, ResponseOverCapacity fallback for oversized responses, and per-client notifyBulk targeting; all paths correctly avoid closing the connection on producer overload.
src/relay/fs-handler-file-read.ts Terminal frame slot reservation via pendingTerminalFramesByClient correctly bounds concurrent terminal frames per client; slot released via settlement callback or finally block; no slot-leak path found.
src/shared/agent-hook-relay.ts restoreShedStatusFields validates both digest and turn identity before restoring subagents; interactivePrompt and lastAssistantMessage deliberately not restored to avoid stale prose from an earlier turn.
src/relay/dispatcher-client-writer.ts Minor changes; fixedFrameCapacity getter added for fixed-bulk lane; logic unchanged otherwise.
src/relay/relay-filesystem-watch-registry.ts Trivial one-line fix; no issues.

Reviews (4): Last reviewed commit: "fix(relay): prevent infinite redeploy on..." | Re-trigger Greptile

@AmethystLiang AmethystLiang changed the title P0 fix(ssh, relay): keep remote sessions alive through reconnects and backpressure Aug 1, 2026

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f876ac2a-8a7f-4590-8dc3-6389c39d1feb

📥 Commits

Reviewing files that changed from the base of the PR and between fdb3271 and c2ebd7f.

📒 Files selected for processing (8)
  • src/main/ipc/ssh.test.ts
  • src/main/ssh/ssh-connection.test.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/dispatcher.ts
  • src/relay/relay-watcher-frame-chunking.test.ts
  • src/relay/relay.ts
  • tests/tools/benchmarks/terminal-perf-bench.mjs
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/relay/relay.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ssh/ssh-connection.test.ts

Comment thread src/relay/dispatcher.ts Resolved
ResponseOverCapacity should use -33008 to stay in the -33xxx range
for relay protocol errors, not -32010.
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolved

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang: Acknowledged. The review comment is addressed.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

Replay is never retried, so it uses the control lane where overflow
is fatal — the writer closes the client and reconnect reloads history
rather than stranding a short buffer.
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolved

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang: Acknowledged. The review comment is addressed.

You are interacting with an AI system.

Charge reconnect attempts when connection restores mid-backoff, preventing
infinite loop on transports that flap between states. Refactor control overflow
handling to use entry property instead of WeakSet marker for clarity.
@AmethystLiang
AmethystLiang merged commit a07427e into main Aug 1, 2026
41 checks passed
@OrcaWin OrcaWin mentioned this pull request Oct 11, 2026
3 of 5 tasks
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ckpressure (stablyai#11999)

* fix(ssh,relay): stop remote connections from being killed by backoff and frame caps

Three independent connection killers found in the SSH/remote freeze audit.

FINDING A - the reconnect ladder never escalated for post-handshake drops.
scheduleReconnect() used the single published state.reconnectAttempt for both
the delay index and the give-up test, and runReconnectAttempt() zeroed it
before connecting (ssh.ts gates the relay redeploy on 0-at-connected). Every
post-handshake drop therefore re-entered at 1000ms forever, ~3600 relay
redeploys/hour, and 'reconnection-failed' was unreachable for a flapping host.
New SshReconnectLadder splits the delay index (advanced by every retry) from
the failure streak (advanced only by a failed handshake), so flaps back off
while give-up semantics stay byte-identical to shipped.

FINDING B - notify() closed the client whenever a frame exceeded the producer
frame capacity, conflating a permanently un-sendable frame with transient
backpressure. A 5000-event fs.changed is 425KB against a 49KB cap, so the
watcher flood killed the link and re-killed on every reattach+replay. notify()
now drops and logs once per generation; fs.changed is chunked to each sink's
capacity with a control-lane overflow marker as the resync fallback; agent-hook
envelopes shed lastAssistantMessage/interactivePrompt/subagents to fit.

FINDING B2 - sendResponse routed >1MB responses to a lane whose admission
ignores the frame cap and closed the client on rejection, so a large
fs.listFiles dropped the SSH host. It now substitutes a JSON-RPC error so the
request fails instead of the connection.

Also moves fs.streamEnd/fs.streamError to the control lane so a terminal frame
cannot be dropped by the producer-lane check.

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

* fix(relay): stop the overflow marker from re-killing the link it protects

Round-1 review fixes on the P0 freeze work.

The control-lane overflow marker could reinstate the exact failure this P0
removes: dispatcher-client-writer closes the client when control-lane
admission fails, and admitControl is the only lane that returns an error, so
one marker per failing batch accumulated to the 256-frame/1MB bound and
dropped the link. Markers are now deduped to one outstanding per
(client, root), cleared on settle.

Chunking also defeated the renderer's per-payload directory dedupe -- events
are now stable-grouped by parent directory so one directory lands in one
chunk -- and the halving walk overshot the byte minimum ~1.7x while the fast
path paid three JSON encodes; both are fixed by publishing first and sizing
from a measured bytes-per-event estimate.

Agent-hook shedding now surrenders the blocking interactive prompt LAST
rather than first, so a degraded envelope cannot strand a pane at
state=waiting with no answerable question card.

The dropped-notification log now distinguishes over-capacity from producer
queue backpressure and no longer lets the first dropped method silence every
other producer for the life of the connection.

* fix(relay,ssh): keep status delivery and terminal frames from trading one freeze for another

Round-2 review fixes.

The round-0 change from close-on-rejection to silent drop removed the only
redelivery path for agent.hook envelopes: they are fire-and-forget and the
per-pane cache only replays on handler install, so a saturated link stranded
a pane on a stale Working spinner until reconnect. Closing used to guarantee
delivery by forcing that replay. Envelopes now publish per client and pend
for bounded latest-wins redelivery when the producer queue rejects them.

Shed fields are now named on the wire. The subagent roster is not cosmetic --
the renderer replaces rather than merges it, and hibernation gates on its
length -- so an unmarked shed could sleep a live pane.

fs.streamEnd rode the control lane because it must not be dropped, but that
lane kills rather than drops. The stream's concurrency slot is now held until
the terminal frame settles rather than until the fd closes, capping queued
terminal frames well under the control budget; overflow costs one refused
read instead of the connection.

The watcher chunk walk now stops while producer retention sits past its
reserve and degrades to a resync, so a 5000-event flood cannot fill the queue
that interactive PTY traffic shares and stall every remote terminal.

The reconnect ladder caps its flap-path delay so delay plus handshake timeout
cannot cross the relay grace floor and let the remote daemon kill live PTYs.

Also: the suppression key no longer embeds a NUL byte, which had made the
file binary to git and grep; producerEnvelopeBudget no longer reports
infinite capacity for a departed client; the drop logger no longer encodes a
frame it will not log; and an over-capacity response substitution no longer
settles as if the result had been delivered.

* fix(relay,ssh): restore relay-shed status fields and scope backpressure per client

Round 3 + 4 review fixes.

Watcher chunking is now gated on the *client's* retention reserve rather than
the dispatcher-wide one, so one stalled peer no longer forces a healthy client
into a full file-tree resync. The relay-lost redeploy ladder no longer burns its
6-attempt budget while the SSH transport itself is down: it holds at the 15s step
with a non-terminal status and rearms, so a laptop that slept past the ladder
comes back instead of landing on a terminal "give up" banner.

The shedFields wire marker had no consumer, so an agent-hook envelope whose
subagent roster was dropped to fit the frame read as "roster cleared" on the Orca
side: live child rows blanked and a done pane became hibernation-eligible while
its teammates were still running. ingestRemote now restores shed fields from the
cached payload (interactivePrompt deliberately excluded — a stale answerable
question card is worse than none).

Also: stream terminal-frame slots are counted per client, since the control queue
they protect is per client; the chunking fast path no longer logs a drop for a
batch it goes on to deliver in full; -32010 is now RelayErrorCode.ResponseOverCapacity.

Test debt from the review: pending-pane eviction, per-client stream isolation, and
the reconnect budget are now asserted rather than assumed; four fragile exact-byte
pins dropped in favour of the tier comparisons that carry the requirement.

* fix(relay,ssh): restore relay-shed status fields and scope backpressure

- Oversized relay responses now fail their request instead of closing the connection,
  preventing one frame from killing every pane on the host
- Restore subagent state for correct hibernation; don't resurrect stale prose
  across turns
- Account for relay re-establishment and PTY reattach time in SSH flap delay caps
- Only log drops of final unsendable envelopes, not temporary rejections during
  measurement probes
- Fix watcher overflow marker release race when notification admission rejects
  without settlement; use precise byte counting for event batching

* Restore relay-shed fields with digest validation and scoped backpressure

Validate that shed subagent rosters match their wire digest and turn identity before
restoration, preventing stale roster resurrection. Compact interactive prompts for waiting
states instead of dropping them. Demote control-queue overflow to non-fatal rejection so
clients can retry on capacity recovery, keeping the link alive during transient backpressure.

* fix(relay): correct ResponseOverCapacity error code

ResponseOverCapacity should use -33008 to stay in the -33xxx range
for relay protocol errors, not -32010.

* fix(relay): close client when pty.replay overflows control queue

Replay is never retried, so it uses the control lane where overflow
is fatal — the writer closes the client and reconnect reloads history
rather than stranding a short buffer.

* fix(relay): prevent infinite redeploy on flapping SSH transports

Charge reconnect attempts when connection restores mid-backoff, preventing
infinite loop on transports that flap between states. Refactor control overflow
handling to use entry property instead of WeakSet marker for clarity.

---------

Co-authored-by: Orca <[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