Skip to content

Gate SSE : connected on the daemon watch bridge actually being attached - #2587

Merged
malibio merged 2 commits into
mainfrom
issue-2584-sse-race
Sep 13, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2584-sse-race

Conversation

@malibio

@malibio malibio commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes #2584 — WatchNodes SSE stream > delivers nodeCreated event when a node is written was failing deterministically under the pre-push gate.

The prior investigation in the issue correctly showed the dev-proxy's own SSE client bookkeeping (sseClients.add() before the : connected flush) has no gap. The actual race is one level up: packages/dev-tools/src/dev-proxy.ts's Bun.serve() starts immediately and does not wait for startWatchBridge()'s async connect() (which does await ready(watchClient) before attaching the gRPC stream's data/error/end listeners). So /health — and /api/events — can be live before the daemon-side relay is actually attached. Under a loaded machine, a client can connect, get registered, and be told : connected inside that window; a write racing it is never delivered because nothing is listening upstream yet to broadcast it.

Changes

  • packages/dev-tools/src/dev-proxy.ts: track watch-bridge attachment with a resolvable promise, resolved once the gRPC stream's listeners are wired and reset on every reconnect (error/end). /api/events now awaits this before registering a client or flushing : connected.
  • packages/desktop-app/src/tests/e2e/watch-nodes.e2e.ts: added a deterministic regression test using the existing DaemonTestHarness.startDeferred() path (proxy healthy, daemon not yet reachable) — this reproduces the race without depending on machine load. Verified it fails reliably against the pre-fix code and passes reliably with the fix.

Test plan

  • bun run test:e2e -- watch-nodes — all 4 tests pass, repeated 4x with no flakes
  • Verified new regression test fails against pre-fix code (AbortError: This operation was aborted after 20s) and passes against the fix
  • bun run test:all — no new failures vs baseline
  • bun run quality:fix — clean
  • git push pre-push gate (test:all + cargo build + test:e2e) passed

🤖 Generated with Claude Code

…ched (closes #2584)

The dev-proxy's HTTP server (and thus /health) comes up before
startWatchBridge()'s async gRPC connect finishes, since Bun.serve()
never waits on it. Under a loaded machine that connect can still be
in flight when a browser client hits /api/events, gets registered in
sseClients, and is told `: connected` — with no upstream listener yet
attached to relay events. A write racing that window is never
delivered, because dev-proxy's own client bookkeeping has no gap (the
prior evidence-driven hypothesis) but the bridge's own readiness does.

Track bridge attachment with a promise resolved once the gRPC stream's
data/error/end listeners are wired, reset on every reconnect, and have
/api/events await it before registering a client or flushing
`: connected`. Add a deterministic regression test using the existing
startDeferred() harness path (proxy healthy, daemon not yet reachable)
that fails reliably against the old code and passes reliably against
the fix — no reliance on an idle machine either way.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sppvEt8PWpk92zQMYjc4W
@malibio

malibio commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a well-targeted, minimal fix for a genuine race condition: the dev-proxy's HTTP server accepted SSE connections and announced : connected before the daemon->dev-proxy gRPC watch bridge had actually attached its listeners, creating a window where a write could be silently dropped. The fix — a resolvable bridgeAttached promise gating client registration, reset on every reconnect — is the right shape for the problem and is correctly synchronized. The new regression test reproduces the race deterministically via the existing startDeferred() harness path rather than depending on machine load, and completes in ~318ms, confirming it's actually exercising the fix rather than passing by exhausting a generous timeout. All three acceptance criteria from issue #2584 are met. This is a net positive and I'd approve it.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/dev-tools/src/dev-proxy.ts:162-166: attachedResolve() fires immediately after the data/error/end listeners are wired, not after any actual event has round-tripped through the stream. That's the correct semantic per the issue (registration/attachment is the contract, not "has relayed at least one event"), but it's worth being explicit in review that this signal means "the pipe is connected," not "the pipe has been proven to carry data." If the daemon's watchNodes() call can itself silently fail to fully establish server-side (e.g., some gRPC implementations lazily open streams and don't surface error until the first write attempt), there could be a theoretical gap where attachedResolve() fires but the daemon-side stream isn't really live yet. Given ready(watchClient) is awaited first and the new e2e test empirically passes against a real daemon, this is a low-probability, hard-to-verify-further concern rather than a blocker — flagging for awareness, not action.

  • packages/dev-tools/src/dev-proxy.ts: bridgeAttached/attachedResolve/resetBridgeAttached are module-level mutable bindings threaded through a closure-based reconnect loop. This is idiomatic for a single-file dev script of this size, but if dev-proxy.ts grows more of this kind of shared mutable state, consider consolidating bridge lifecycle (attached-promise + reconnect timers + client set) into a small object/class to keep the invariants ("reset always precedes the next resolve," "only one connect() in flight") enforced by structure rather than by convention. Not warranted at the current size — noting for future growth only.

Nitpicks

  • Nit: packages/dev-tools/src/dev-proxy.ts:280-285: the comment above await bridgeAttached and the comment above the attachedResolve declaration (lines 86-97) both explain the same rationale in overlapping detail. Could trim one down to a one-line pointer to the other now that both exist, but not worth blocking on.

  • Nit: The new describe block's test name ("still delivers nodeCreated when the client connects before the daemon is reachable") is accurate but the describe title ("WatchNodes SSE stream under a slow-starting daemon") and it title together read slightly redundantly with the file's first describe. Purely cosmetic.

Acceptance Criteria Verification (issue #2584)

  • : connected is now gated on the bridge being genuinely attached (await bridgeAttached before registration and before the flush) — confirmed by reading the control flow.
  • delivers nodeCreated event when a node is written passes — ran bun run test:e2e -- watch-nodes: 4/4 tests pass in 1.75s.
  • A regression test covers the loaded/slow-start case without depending on machine load — startDeferred() deterministically reproduces "proxy healthy, daemon not yet reachable," and the test passed in 318ms (not near its 20s ceiling), indicating it's actually verifying attachment ordering rather than passing incidentally.

Code Quality

  • No lint suppressions, no any types, no #[allow(dead_code)]-equivalent patterns introduced.
  • console.error/console.log usage in the new code matches the pre-existing style throughout dev-proxy.ts (a dev-only tooling script, not application code subject to the createLogger rule) — consistent, not a regression.
  • Diff is atomic: touches exactly the bridge-attachment mechanism and its regression test, no unrelated changes bundled in.
  • Promise-reset race analysis: connect() is invoked exactly once at a time — at startup via void connect(), and thereafter only via setTimeout(connect, …) scheduled synchronously inside the ready() catch block or the error/end handlers, always after resetBridgeAttached() has already run in the same synchronous turn. There is no path for two connect() invocations to be in flight concurrently, so attachedResolve() from a stale closure racing a fresh resetBridgeAttached() cannot happen. A client await-ing an already-resolved bridgeAttached before a reset simply proceeds immediately, which is correct (the bridge genuinely was attached at that instant) — no stuck-forever scenario exists in this code.

Test Coverage

Adequate for the bug being fixed. The new test complements the existing three (create/update/delete) by covering the one dimension they didn't: client connection racing bridge (re)attachment rather than racing client registration alone. No additional coverage is needed for this fix's scope.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: APPROVE

Self-authored PR — verdict recorded via --comment since GitHub rejects self-approval. Full findings posted above. Summary: sound fix for a genuine race, correctly synchronized reconnect/reset logic (verified no overlapping connect() invocations, no stale-closure resolve, no stuck-forever path), all 3 acceptance criteria met, all 4 e2e tests pass, atomic diff, no lint/quality issues. Net positive — approving with only non-blocking nits/suggestions noted in the review comment.

Two non-blocking nits from the pragmatic-code-review of PR #2587:
- The comment above `await bridgeAttached` restated the rationale
  already documented on `bridgeAttached` itself; trimmed to a pointer.
- The new describe/it titles read redundantly against the file's
  existing describe block; renamed for a clearer, non-overlapping name.

Skipped: consolidating bridge-attachment state into an object/class —
reviewer flagged this as "not warranted at current size, noting for
future growth only," not an actionable recommendation.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sppvEt8PWpk92zQMYjc4W
@malibio

malibio commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review Summary

Addressed the two non-blocking nits from the pragmatic-code-review (which returned APPROVE with no critical/important findings):

  • ✅ Trimmed the duplicate rationale comment above await bridgeAttached in dev-proxy.ts down to a pointer at bridgeAttached's own doc comment.
  • ✅ Renamed the new test's describe/it titles (WatchNodes SSE stream reconnection ordering / delivers a write made while the daemon was still starting up) to remove the redundancy with the file's existing describe block.

⏭️ Skipped: consolidating bridgeAttached/resetBridgeAttached state into an object/class — the reviewer explicitly flagged this as "not warranted at the current size, noting for future growth only," not an actionable recommendation for this PR.

Verified after the edits: bun run test:e2e -- watch-nodes — 4/4 pass (748ms), bun run quality:fix clean, pre-push gate passed on push.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: Both changes are cosmetic (comment trimming, test naming) with zero logic changes — no code paths, control flow, or test assertions were touched. The one skipped item was the reviewer's own explicit "not warranted now" note, not a recommendation requiring re-verification. The prior review's correctness analysis (synchronization of bridgeAttached/resetBridgeAttached, no overlapping connect() invocations, all acceptance criteria met) is unaffected.

Ready for merge pending final approval.

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.

WatchNodes SSE: a write racing subscription registration is never delivered, blocking every push under load

1 participant