Repository navigation
fix(relay): chunk fs.changed notifications to fit the client frame capacity - #11917
Conversation
…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.
📝 WalkthroughWalkthrough
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/relay/relay-watcher-event-emitter.ts (1)
24-28: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten 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
📒 Files selected for processing (6)
src/relay/dispatcher.tssrc/relay/relay-filesystem-watch-registry.test.tssrc/relay/relay-watcher-event-emitter.tssrc/relay/relay-watcher-frame-chunking.test.tssrc/relay/relay-watcher-parent-removal.test.tssrc/relay/relay-watcher-pending-setup-waiters.test.ts
Greptile SummaryFixes a deterministic connection kill introduced in #11005:
Confidence Score: 5/5Safe 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.
|
| 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
Reviews (2): Last reviewed commit: "Merge origin/main into nwparker/relay-di..." | Re-trigger Greptile
…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
Problem
emitRelayWatcherEventspublished an entire filesystem watcher batch as a singlefs.changedJSON-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 callscloseClient(...)withRelay 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-charnode_modulespaths fit ~270 and ~67.MAX_BATCHED_WATCHER_EVENTSis 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.
emitRelayWatcherEventsasks 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.JSON.stringifyof 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.broadcastProducerFrameCapacity()(minimum across active clients,undefinedwhennotify()would reach nobody) andnotificationFrameBytes(method, params). The capacity ranges over exactly the client setnotify()iterates.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.tshas no timeout and settles only on end/error ormux.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.replaywith the full retained buffer, losslessly.agent.hook— no resync contract at all.workspace.changed— an older desktop'snormalizeSnapshotcoerces a missing snapshot into arevision: 0session 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 nonotify()call at all with no client attached.The byte budget is pinned from both directions.
expectMaximallyPackedChunksasserts 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: swappingBuffer.byteLength(...)for.lengthfails 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 RelayDispatcherfakes were updated with the two new methods.Validation
src/relay/— 98 files, 1101 passed, exit 0npx oxlint src/relay— exit 0npx oxfmt --check— cleannpx tsc --noEmit -p config/tsconfig.node.json— exit 0, 0 TS errorsWhat this does not fix
fs.changednotification count 1:1 into desktop IPC and renderer work.routeSshFilesystemWatchNotificationrebuilds its path matcher per registration per notification;doInstallRemoteWatcher's callback does onesend('fs:changed', ...)per notification per window with no batching (thequeueWatcherEventsdebounce exists only on the local watcher path);processFileExplorerFsPayloadbuildsdirsToRefreshper payload, so an expanded directory can take one forced remotereaddirper 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 consecutivefs.changednotifications atrouteSshFilesystemWatchNotificationbefore the registration fan-out — that belongs in a different process and has to become asynchronous, which changes ordering relative tofs.watchFailedand needs flush-on-teardown handling.admit()refusesfixed-bulkwhileproducerBytes > 0, so a draining watcher batch can delayfs.streamChunkadmission. That is added latency on a connection that stays up, replacing one that was unconditionally killed — and a killed connection terminated every in-flightfs.streamChunkviamux.onDisposeanyway. Admission and ledger logic untouched.Summary
Chunk relay
fs.changedwatcher batches to the smallest attached client frame capacity while preserving event order and fail-closed behavior.Screenshots
Not applicable — no UI changes.
Testing
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.changedevents 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.