Skip to content

fix(relay): chunk fs.changed notifications to fit the client frame capacity - #11917

Merged
nwparker merged 3 commits into
mainfrom
nwparker/relay-dispatcher-oversized-notify
Aug 1, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/relay-dispatcher-oversized-notify

Conversation

@nwparker

@nwparker nwparker commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

emitRelayWatcherEvents published an entire filesystem watcher batch as a single fs.changed JSON-RPC notification on the dispatcher's ordinary lane.

An over-capacity frame on that lane is not queued and not trimmed — notify() fails admission and immediately calls closeClient(...) with Relay ordinary publication capacity exceeded, tearing down every in-flight request on the connection and forcing a reconnect.

The per-frame producer capacity is ~0.75× the remote host's Node stream high-water mark: 12,288 bytes on Node ≤21, 49,152 on Node ≥22. Measured with the repo's own encodeJsonRpcFrame: 56-char paths fit ~378 events per frame at 49,152 and ~94 at 12,288; 108-char node_modules paths fit ~270 and ~67. MAX_BATCHED_WATCHER_EVENTS is 5000.

So an ordinary busy batch — an npm install, a branch switch, a build — is 13× to 75× over capacity and deterministically kills the connection. Regressed in 5f78074 (#11005).

Fix

Chunk the broadcast so each frame fits. Every event still gets delivered, in order.

  • emitRelayWatcherEvents asks the dispatcher for the tightest producer frame capacity across attached clients and splits the batch into ordered chunks that fit, measured in encoded bytes (Buffer.byteLength), not UTF-16 length.
  • Sizing is exact rather than heuristic: JSON.stringify of an array is its elements joined by commas, so a chunk is the empty-array envelope plus each element plus one comma per extra element. The envelope is measured through the dispatcher so it matches what admission measures — a budget computed from an envelope missing "events":[] understates framing overhead, and a chunk filled exactly to that budget would then be refused at precisely the boundary the chunker exists to respect.
  • Two small dispatcher accessors: broadcastProducerFrameCapacity() (minimum across active clients, undefined when notify() would reach nobody) and notificationFrameBytes(method, params). The capacity ranges over exactly the client set notify() iterates.
  • Chunks are packed to the byte, not to a round number, because each chunk costs a full downstream fan-out on the desktop side.

The kill is preserved on purpose. A single event too large for an empty envelope cannot be chunked, so the ordinary-lane close remains its backstop.

Why not "degrade instead of kill"

Design review rejected every variant of turning the kill into a silent drop or an overflow-resync. The ordinary lane also carries:

  • fs.streamEnd / fs.streamError — ssh-filesystem-stream-reader.ts has no timeout and settles only on end/error or mux.onDispose, so a dropped frame hangs the read forever. Today the kill makes it reject and retry.
  • pty.data — a drop punches an unrecoverable hole mid-stream (truncated escape sequences, stuck alt-screen). Today: kill → reconnect → pty.replay with the full retained buffer, losslessly.
  • agent.hook — no resync contract at all.
  • workspace.changed — an older desktop's normalizeSnapshot coerces a missing snapshot into a revision: 0 session and wipes remote workspace state.

The kill is a deliberate fail-closed backstop with a real recovery contract. This PR stops the producer emitting frames that can never fit; it does not weaken the backstop.

ELI5

The relay is the little program on the remote machine that tells your laptop when files change. It used to stuff every change from one burst into a single message.

There is a size limit on a message. Go over it and the relay does not trim the message or send it in pieces — it hangs up the phone. Everything else in flight over that connection dies with it, and the app has to dial back.

Save a file in a big repo and the watcher can report thousands of paths at once. That message blew past the limit easily, so the connection kept dropping.

Now the relay checks how big a message is allowed to be and cuts the list into several that each fit, in the original order. Same information, same sequence, no hang-up.

One case is left alone deliberately: if a single file path is somehow too long to fit by itself, there is nothing to cut, so the old hang-up still happens. Quietly throwing that event away would be worse — the laptop would have no way to notice it missed something and re-sync.

Tests

New src/relay/relay-watcher-frame-chunking.test.ts, 10 tests. 9 of 10 fail against the pre-change emitter (independently verified by reverting the emitter and re-running: Tests 9 failed | 1 passed (10)). The 10th — still closes the client when a single event cannot fit any frame — passes both ways by design, since that is the preserved fail-closed path.

Coverage: 5000-event batches at both capacities; multi-byte and JSON-escaped paths (Japanese, Cyrillic, emoji, " and \); a batch encoding to exactly capacity and one to capacity + 1; smallest-capacity selection across two clients with different high-water marks; an oversized event mid-batch (ordered prefix delivered, then close); producer-queue exhaustion under a sink that accepts but never settles writes; and no notify() call at all with no client attached.

The byte budget is pinned from both directions. expectMaximallyPackedChunks asserts that for every consecutive frame pair, pulling the next frame's first event forward would overshoot — so an overstated envelope (needless splitting) fails. The exactly-at-capacity and capacity + 1 tests catch an understated envelope. Verified by mutation: swapping Buffer.byteLength(...) for .length fails exactly the multi-byte test; dropping "events":[] from the measured envelope fails the overshoot test; padding the envelope by 200 bytes fails 4 tests.

Three existing test files that build as unknown as RelayDispatcher fakes were updated with the two new methods.

Validation

  • src/relay/ — 98 files, 1101 passed, exit 0
  • npx oxlint src/relay — exit 0
  • npx oxfmt --check — clean
  • npx tsc --noEmit -p config/tsconfig.node.json — exit 0, 0 TS errors

What this does not fix

  • Downstream notification fan-out. Chunking multiplies the fs.changed notification count 1:1 into desktop IPC and renderer work. routeSshFilesystemWatchNotification rebuilds its path matcher per registration per notification; doInstallRemoteWatcher's callback does one send('fs:changed', ...) per notification per window with no batching (the queueWatcherEvents debounce exists only on the local watcher path); processFileExplorerFsPayload builds dirsToRefresh per payload, so an expanded directory can take one forced remote readdir per chunk. Mitigation here: chunks are packed to the byte (pinned by test), so chunk count is the minimum possible, and any batch under ~270 events at capacity 49,152 still emits exactly one notification as before. Note the baseline this replaces was a killed connection, which forced a full re-listing anyway. Recommended follow-up: microtask-coalesce consecutive fs.changed notifications at routeSshFilesystemWatchNotification before the registration fan-out — that belongs in a different process and has to become asynchronous, which changes ordering relative to fs.watchFailed and needs flush-on-teardown handling.
  • Producer-queue contention. Chunked frames occupy the producer queue, and admit() refuses fixed-bulk while producerBytes > 0, so a draining watcher batch can delay fs.streamChunk admission. That is added latency on a connection that stays up, replacing one that was unconditionally killed — and a killed connection terminated every in-flight fs.streamChunk via mux.onDispose anyway. Admission and ledger logic untouched.
  • A single event larger than an empty envelope still closes the client. Unchunkable by construction.
  • Local (non-SSH) watchers are unaffected — they never go through the relay dispatcher.

Summary

Chunk relay fs.changed watcher batches to the smallest attached client frame capacity while preserving event order and fail-closed behavior.

Screenshots

Not applicable — no UI changes.

Testing

  • Focused relay and SSH watcher tests
  • Node typecheck
  • Oxfmt and oxlint
  • Max-lines ratchet
  • Relay builds for Linux, macOS, Windows, WSL, x64, and arm64

AI Review Report

Three independent production-readiness audits (one Codex and two Grok) found no proven P0, P1, or P2 issues. Greptile also rated the change safe to merge. The review covered correctness, concurrency, performance, queue admission, SSH/remoting, cross-platform behavior, and old-client compatibility.

Security Audit

The production security scan and whitespace check passed with zero hits. No dependencies, lockfiles, package scripts, install hooks, binaries, signing, updater, persistence, schema, RPC method, protocol-version, credential, or network-sink changes are present.

Notes

No mobile-facing payload shape or persisted state changed; existing clients receive the same ordered fs.changed events in bounded frames. Unit tests cover Node 21/22 capacities, multibyte paths, mixed client capacities, oversized events, queue exhaustion, and no-client cleanup. Runtime packaging was built for all supported relay targets; live Windows and live SSH watcher-flood testing were not performed in this review.

…pacity

emitRelayWatcherEvents published an entire watcher batch as one
fs.changed notification on the ordinary lane. A batch runs routinely
tens of times over the per-frame producer capacity (12,288 bytes against
a Node <=21 socket, 49,152 against Node >=22), and an over-capacity
frame there is not queued or trimmed -- notify() fails admission and
closes the client, tearing down every in-flight request on that
connection. Regressed in 5f78074 (#11005).

The emitter now sizes chunks against the tightest capacity across
attached clients, measured in encoded bytes through the same envelope
admission measures, and preserves event order. A single event too large
for an empty envelope cannot be chunked, so the ordinary-lane close
remains its backstop: a silent drop on this lane has no resync contract.
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

RelayDispatcher now exposes active-client producer capacity and encoded notification size. The watcher uses these values to split fs.changed events into ordered, byte-limited frames. It handles unavailable capacity, oversized events, queue exhaustion, and no-client cases. Tests cover byte boundaries, multibyte paths, multiple client capacities, event ordering, client retention, and updated dispatcher fixtures.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main change: chunking fs.changed notifications to fit client frame capacity.
Description check ✅ Passed The description explains the problem, fix, testing, security review, platform coverage, risks, and follow-up work in the required sections.
✨ 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.

🧹 Nitpick comments (1)
src/relay/relay-watcher-event-emitter.ts (1)

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

Shorten the "Why" comments.

The comment blocks at lines 24-28 and 47-49 explain the chunk-sizing derivation and the mid-batch oversized-event edge case in multiple sentences. Keep the rationale, but state it in one line each. Move algorithm-derivation detail out of inline comments; the logic is verifiable from the code itself.

As per coding guidelines, "Comments must be concise, limited to non-obvious information, and preferably one line; do not explain obvious code or walk through implementation details."

Also applies to: 47-49

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d3dc6240-f4f4-4f2a-94c1-62a286cb0eee

📥 Commits

Reviewing files that changed from the base of the PR and between edb5607 and 0ddee0c.

📒 Files selected for processing (6)
  • src/relay/dispatcher.ts
  • src/relay/relay-filesystem-watch-registry.test.ts
  • src/relay/relay-watcher-event-emitter.ts
  • src/relay/relay-watcher-frame-chunking.test.ts
  • src/relay/relay-watcher-parent-removal.test.ts
  • src/relay/relay-watcher-pending-setup-waiters.test.ts

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

Fixes a deterministic connection kill introduced in #11005: emitRelayWatcherEvents was sending an entire watcher batch as a single fs.changed notification, routinely exceeding the ordinary-lane frame capacity by 13–75× and unconditionally closing the connection.

  • relay-watcher-event-emitter.ts: replaces the single notify() call with a byte-exact chunking loop. Chunk size is tracked incrementally — envelope bytes measured through the dispatcher (so the estimate matches what admission checks), per-element bytes via Buffer.byteLength(JSON.stringify(...)) (correct for multi-byte and JSON-escaped paths), and one comma per non-first element. A chunk is flushed before adding an event that would push it past the minimum producerFrameCapacity across all attached clients.
  • dispatcher.ts: adds two focused public accessors — broadcastProducerFrameCapacity() returning the minimum per-frame capacity across active clients (or undefined when nobody is attached or the dispatcher is disposed), and notificationFrameBytes() wrapping the existing private estimateFrameBytes.
  • Three test files updated to stub the two new methods on fake dispatcher objects; one new test file (relay-watcher-frame-chunking.test.ts) with 10 tests pinning the byte budget from both directions and covering the preserved fail-closed paths.

Confidence Score: 5/5

Safe to merge. The chunking arithmetic is exact (verified analytically and by mutation testing in the PR), the fail-closed backstop is explicitly preserved, and the three existing test fakes are updated with stub implementations that keep prior test behavior unchanged.

The byte-counting logic is provably correct: envelope measured through the same estimateFrameBytes path that admission uses, per-element bytes use Buffer.byteLength(JSON.stringify(...)) rather than .length (catching multi-byte and escape expansion), and commas are counted per non-first element — matching exactly how JSON.stringify serializes an array. The strict > flush threshold aligns with the <= admission check so exactly-at-capacity chunks are admitted without splitting. Tests pin both boundaries, cover the preserved close paths (oversized single event, producer-queue exhaustion), and verify the minimum-capacity selection across two clients with different high-water marks. No logic is removed; the change is strictly additive to the existing capacity-enforcement machinery.

Files Needing Attention: No files require special attention. The two new dispatcher methods are minimal and follow existing patterns; the emitter change is self-contained.

Important Files Changed

Filename Overview
src/relay/relay-watcher-event-emitter.ts Replaces single-notify with a byte-exact chunking loop; arithmetic is provably correct — envelope size measured through the dispatcher, commas accounted per element, Buffer.byteLength used for multi-byte paths.
src/relay/dispatcher.ts Adds two public accessors: broadcastProducerFrameCapacity() (min across active clients, undefined when nobody attached or disposed) and notificationFrameBytes() (delegates to estimateFrameBytes). Both are minimal, follow existing patterns, and are pinned by tests.
src/relay/relay-watcher-frame-chunking.test.ts New test file with 10 focused tests covering both Node≤21 and Node≥22 capacities, multi-byte/escaped paths, exact-boundary and boundary+1 packs, min-capacity selection across two clients, oversized mid-batch, producer-queue exhaustion, and no-client early-exit. expectMaximallyPackedChunks pins both directions of the byte budget.
src/relay/relay-filesystem-watch-registry.test.ts Fake dispatcher updated with the two new methods; broadcastProducerFrameCapacity returns MAX_SAFE_INTEGER and notificationFrameBytes returns 64, making all existing assertions behave as a single-chunk pass-through.
src/relay/relay-watcher-parent-removal.test.ts Three inline fake dispatchers consolidated into a watchDispatcher() factory and updated with the two new methods; no logic changes.
src/relay/relay-watcher-pending-setup-waiters.test.ts Fake dispatcher updated with the two new stub methods; no logic changes to the test scenario.

Sequence Diagram

sequenceDiagram
    participant WR as WatcherRegistry
    participant EE as emitRelayWatcherEvents
    participant D as RelayDispatcher
    participant A as DispatcherWriterAdmission
    participant S as DispatcherWriterSink

    WR->>EE: emitRelayWatcherEvents(dispatcher, closed, events[0..N])
    EE->>D: broadcastProducerFrameCapacity()
    D->>S: min(client.producerFrameCapacity across activeClients)
    S-->>D: "min capacity (e.g. 12288 for Node<=21)"
    D-->>EE: frameCapacity (undefined if no active clients)
    Note over EE: Early-exit if undefined

    EE->>D: "notificationFrameBytes(fs.changed, {events:[]})"
    D-->>EE: envelopeBytes (header + empty-array JSON)

    loop for each event in batch
        EE->>EE: "payloadBytes = Buffer.byteLength(JSON.stringify(payload))"
        alt "chunkBytes + 1 + payloadBytes > frameCapacity"
            EE->>D: "notify(fs.changed, {events: chunk})"
            D->>A: canAdmitProducer(frameBytes, producerFrameCapacity)?
            alt "bytes <= producerFrameCapacity AND queue fits"
                A-->>D: admitted - frame queued
                D-->>EE: chunk delivered
            else oversized single event
                D->>D: closeClient(client, capacity exceeded)
                D-->>EE: client closed (fail-closed backstop)
            end
            EE->>EE: "chunk=[], chunkBytes=envelopeBytes"
        end
        EE->>EE: chunk.push(payload), update chunkBytes
    end

    EE->>D: "notify(fs.changed, {events: final_chunk})"
    D-->>EE: done
Loading

Reviews (2): Last reviewed commit: "Merge origin/main into nwparker/relay-di..." | Re-trigger Greptile

@nwparker
nwparker merged commit e531e79 into main Aug 1, 2026
43 checks passed
@nwparker
nwparker deleted the nwparker/relay-dispatcher-oversized-notify branch August 1, 2026 09:56
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…pacity (stablyai#11917)

* fix(relay): chunk fs.changed notifications to fit the client frame capacity

emitRelayWatcherEvents published an entire watcher batch as one
fs.changed notification on the ordinary lane. A batch runs routinely
tens of times over the per-frame producer capacity (12,288 bytes against
a Node <=21 socket, 49,152 against Node >=22), and an over-capacity
frame there is not queued or trimmed -- notify() fails admission and
closes the client, tearing down every in-flight request on that
connection. Regressed in 63ec0b0 (stablyai#11005).

The emitter now sizes chunks against the tightest capacity across
attached clients, measured in encoded bytes through the same envelope
admission measures, and preserves event order. A single event too large
for an empty envelope cannot be chunked, so the ordinary-lane close
remains its backstop: a silent drop on this lane has no resync contract.

* chore(relay): shorten watcher chunking comments
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