Skip to content

Implement WatchNodes gRPC streaming, add Tauri watcher.rs (closes #1114) - #1145

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1114
May 18, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1114

Conversation

@malibio

@malibio malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

Implements the WatchNodes server-streaming gRPC RPC on nodespaced so connected clients receive real-time node change events without polling. Also lands a ready-to-use Tauri-side watcher.rs module that reconnects with exponential backoff and re-emits each proto event as the same node:created / node:updated / node:deleted Tauri events the existing in-process forwarder produces — so the swap will be invisible to Svelte stores once #1113 activates it.

Closes #1114.

What landed

Daemon (live):

  • WatchNodes handler subscribes to NodeService::subscribe_to_events() and translates each DomainEvent::Node{Created,Updated,Deleted} into a proto NodeEvent. Created/Updated events carry the full node payload (re-fetched server-side) so clients don't need a follow-up GetNode.
  • Broadcast lag is logged and skipped; channel closure ends the stream cleanly.
  • 3 new integration tests in packages/daemon/tests/grpc_round_trip.rs:
    • watch_nodes_receives_create_update_delete_events — AC: "mutate via gRPC, watcher receives event"
    • watch_nodes_supports_multiple_concurrent_watchers — AC: "multiple concurrent watchers supported"
    • watch_nodes_closes_when_client_drops_stream — AC: "stream closes gracefully on client disconnect"

Tauri (inert, activation gated on #1113):

  • New packages/desktop-app/src-tauri/src/watcher.rs: opens WatchNodes against nodespaced, re-emits proto events as node:created/updated/deleted Tauri events using the same NodeIdPayload shape as DomainEventForwarder, with exponential backoff (1s start, 30s cap).
  • Module is declared but not spawned because activating it now would double-emit alongside the in-process DomainEventForwarder. Migrate Tauri command handlers to thin gRPC proxy wrappers #1113 will remove the forwarder and call watcher::spawn() in its place.

Scope notes

  • No ops-layer changes: nodespace_core already publishes domain events. The daemon becomes a pure event consumer/translator — no EventBus needed on the daemon side, contrary to the issue body's suggestion.
  • WatchRequest filter fields (node_type, root_id) are accepted but ignored. The issue's Non-Goals list filtering as a future enhancement; a debug log fires when a non-default filter is requested.

Test plan

  • cargo test -p nodespace-daemon — 10/10 tests passing (3 new + 7 existing)
  • cargo test --lib -p nodespace-core -- --test-threads=2 — 1182/1182 passing
  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo clippy -p nodespace-app --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo fmt --all -- --check — clean
  • cargo build -p nodespace-daemon — clean
  • cargo build -p nodespace-app — clean
  • bun run test (frontend) — 3918/3918 passing (matches baseline of 3918/3918)

🤖 Generated with Claude Code

Daemon side (live):
- Replace WatchNodes Unimplemented stub with async_stream handler that
  subscribes to NodeService::subscribe_to_events() and translates each
  DomainEvent::Node{Created,Updated,Deleted} into a proto NodeEvent.
- For Created/Updated, fetch the current node payload so clients get
  full node data inline (no follow-up GetNode round trip).
- Handle broadcast lag as a warn-and-continue rather than a hard error;
  on channel closure, end the stream cleanly.
- Add 3 integration tests: single-watcher round trip (create/update/delete),
  multiple concurrent watchers receiving the same event, and a fresh
  watcher succeeding after a prior client dropped its stream.

Filter fields (WatchRequest.node_type, root_id) are accepted but
ignored — the issue's Non-Goals list filtering as a future enhancement.
A debug log fires when a non-default filter is requested.

No ops-layer changes were needed: nodespace_core already publishes
domain events via NodeService::subscribe_to_events(), so the daemon
becomes a pure event consumer/translator.

Tauri side (inert until #1113):
- New packages/desktop-app/src-tauri/src/watcher.rs module: gRPC client
  that opens a WatchNodes stream against nodespaced, re-emits each
  proto event as a Tauri event (node:created/updated/deleted) using the
  same NodeIdPayload format as the existing in-process
  DomainEventForwarder, and reconnects with exponential backoff
  (1s start, 30s cap).
- Module is declared in lib.rs but not spawned. Activation belongs to
  #1113 (Tauri → thin gRPC client migration), which will remove
  DomainEventForwarder and call watcher::spawn() in its place. Running
  both simultaneously would double-emit every node:* event.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1145 (Initial Review)

Review Type: Initial Review (no prior reviews exist; reviewing full diff vs origin/main).

Scope: ~493 lines across daemon WatchNodes handler, Tauri-side watcher.rs (inert), 3 new integration tests, and Cargo wiring.


Summary

A clean, surgical implementation that satisfies the AC for WatchNodes without introducing the redundant EventBus the issue body sketched. The daemon correctly subscribes to the pre-existing NodeService::subscribe_to_events() broadcast and translates DomainEvent → proto NodeEvent. Re-using core's existing event channel avoids a double source of truth, which is the right call.

The Tauri watcher.rs is deliberately inert (declared in lib.rs as pub mod watcher; only — never spawned), pending the DomainEventForwarder removal in #1113. The rationale is documented in module docs and PR description and aligns with CLAUDE.md's "no dual-mode" rule: shipping it activated would double-emit node:* Tauri events alongside the existing in-process forwarder.

Net-positive change. A few important callouts about contract drift the activation PR (#1113) must reconcile, but nothing blocks merging this scaffold.


Requirements Check (Issue #1114 AC)

  • ✅ WatchNodes RPC fully implemented — packages/daemon/src/services/node_service.rs:286-328; no longer returns Unimplemented.
  • ✅ NodeEvent carries event type + ID + full node data for created/updated — proto uses oneof over NodeData / NodeDeleted (per the merged Define protobuf schema and set up tonic/prost build pipeline for nodespaced #1111 schema, which differs from the issue body's EventType enum sketch — the merged proto is the source of truth and is correctly followed).
  • ✅ Every successful ops-layer mutation publishes to the event bus — already true via core's NodeService broadcast; the daemon is now a faithful consumer.
  • 🟡 Tauri app opens a WatchNodes stream on startup — code exists in watcher.rs::spawn, but never called from lib.rs::run(). Deliberately deferred to Migrate Tauri command handlers to thin gRPC proxy wrappers #1113 (confirmed in issue comment 4472454916). Acceptable scoping per CLAUDE.md's no-dual-mode rule.
  • ✅ Exponential backoff (1s start, 30s cap) — watcher.rs:45-46, watcher.rs:116 (backoff = (backoff * 2).min(BACKOFF_MAX)).
  • 🟡 Frontend reactive state updates from watcher events without polling — not yet activated; same Migrate Tauri command handlers to thin gRPC proxy wrappers #1113 gating.
  • ✅ Multiple concurrent watchers — covered by watch_nodes_supports_multiple_concurrent_watchers (uses tokio::join! over two streams).
  • 🟡 Stream closes gracefully on client disconnect — covered indirectly; see Finding 🟡-3 below.
  • ✅ Integration test: mutate via gRPC, watcher receives event — watch_nodes_receives_create_update_delete_events covers create/update/delete in one test.
  • ✅ bun run test:all — PR body reports 3918/3918 frontend + 10/10 daemon + 1182/1182 core tests passing.
  • ✅ bun run quality:fix — PR body reports clean clippy/fmt.

Non-Goals honored correctly:

  • ✅ WatchRequest { node_type, root_id } filter fields accepted and tracing::debug!-logged but ignored (node_service.rs:291-300).
  • ✅ Relationship events silently dropped in convert_domain_event (node_service.rs:435-437) — matches "Watching relationship changes (separate concern)" in Non-Goals.

Findings

🟢 Strengths

  • Reuses the existing event channel rather than inventing a parallel EventBus. node_service.rs:302 (self.node_service.subscribe_to_events()) keeps a single source of truth for domain events. The issue body suggested a new event_bus.rs module, but core already publishes; introducing a second broadcast channel would have created a synchronization risk. Good judgment in deviating from the issue sketch.
  • Broadcast lag handled correctly. RecvError::Lagged warns and continues rather than terminating the stream (node_service.rs:313-321). Dropping the connection on lag would force a reconnect storm under bursty load; staying connected and missing a few events is the right tradeoff for a UI-reactivity stream.
  • RecvError::Closed breaks the loop cleanly (node_service.rs:322), so the stream ends rather than hanging — important for client-side reconnect semantics.
  • Test infrastructure is solid. next_event_with_timeout (5s) prevents hanging test runs on dropped events, and the helper is reused across all three new tests. The ephemeral-port + retry-connect pattern in spawn_test_daemon correctly avoids 50051 collisions in parallel runs.
  • Backoff implementation is clean. tokio::select! with biased; and a cancel branch in both the stream and the sleep arms (watcher.rs:88-118) means a shutdown signal during the wait still aborts immediately — no 30s shutdown stall.

🟡 Important (worth addressing in #1113, not blocking this PR)

1. node:deleted payload contract diverges from the in-process forwarder. [packages/desktop-app/src-tauri/src/watcher.rs:174-181]

  • Existing DomainEventForwarder::forward_event emits node:deleted with { id, nodeType: Some(...) } (domain_event_forwarder.rs:150-157).
  • The new watcher emits { id } only — node_type: None — because the proto NodeDeleted carries only node_id.
  • The Svelte frontend at tauri-sync-listener.ts:128 types it as <{ id: string }>, so the field is currently unused by frontend code. The contract is not visibly broken, but the comment at lines 132-135 of that file ("We don't know if deleted node was a collection without fetching ... A more robust solution would cache node types or include type in delete events") suggests there was intent to use it later.
  • Recommendation for Migrate Tauri command handlers to thin gRPC proxy wrappers #1113: extend the proto NodeDeleted to carry node_type (it's a single string field, fully backward-compatible per protobuf semantics) so the contract doesn't regress when DomainEventForwarder is removed. Engineering principle: preserve information-rich event payloads at the boundary — once the in-process channel is gone, this information is unrecoverable downstream without a refetch the node no longer permits.

2. source_client_id feedback-loop filtering is not honored by the daemon stream. [packages/daemon/src/services/node_service.rs:286-328]

  • EventEnvelope::metadata.source_client_id exists in core (packages/core/src/db/events.rs:97-101) and is used by DomainEventForwarder to filter out events the Tauri client itself caused (domain_event_forwarder.rs:118-126).
  • The daemon's convert_domain_event discards the envelope's metadata entirely — only envelope.event is consumed.
  • Post-Migrate Tauri command handlers to thin gRPC proxy wrappers #1113, when Tauri stops holding NodeService in-process and talks to the daemon exclusively over gRPC, every mutation will originate from the daemon's perspective regardless of which client issued it. The feedback-loop concern changes shape: the Tauri client will receive events for its own mutations. Whether that's desirable (server-confirmed echo) or harmful (double-applied state in optimistic UIs) depends on store semantics.
  • Recommendation: before flipping the switch in Migrate Tauri command handlers to thin gRPC proxy wrappers #1113, audit SharedNodeStore for idempotency under self-echo. If echoes are undesirable, the watcher's WatchRequest should accept an exclude_client_id filter and the daemon should propagate it. Engineering principle: the existing forwarder's filter encoded a real invariant; removing the filter without verifying idempotency violates the Liskov-style "behavior preserved across implementations" expectation that the activation gating relies on.

3. AC "Stream closes gracefully when the client disconnects" is covered only indirectly. [packages/daemon/tests/grpc_round_trip.rs:443-487]

  • The test drops a stream and verifies a fresh watcher works afterwards. This proves the server didn't deadlock or exhaust resources, but it doesn't directly observe the server-side broadcast::Receiver being dropped or the async_stream task aborting.
  • The practical impact is bounded: tonic aborts the per-stream task on client disconnect, and broadcast::Receiver is Drop-released automatically when the task is. The test author's own comment acknowledges this gap (grpc_round_trip.rs:454-458).
  • Suggestion: a stricter test could spawn N watchers, drop them, and assert via tracing capture or a metric that all N server-side subscription tasks logged their exit. Not required for merge — the current test is a reasonable proxy. Engineering principle: tests should observe the invariant under test directly when feasible; surrogate evidence is acceptable when direct observation requires invasive instrumentation, but should be documented (which the author has done).

4. Per-event get_node() refetch on NodeUpdated adds a database round trip per mutation. [packages/daemon/src/services/node_service.rs:404-429]

  • Each NodeCreated and NodeUpdated event triggers a SurrealDB read inside the stream loop. Under bulk-import workloads (e.g., importing a folder of 10k markdown files), this is 10k extra reads per connected watcher.
  • The alternative — IDs-only, force the client to refetch — is worse for client latency and produces N+1 patterns on the client side. The current design is the right default.
  • Suggestion (future, not this PR): if bulk-import perf becomes an issue, the import path can optionally suppress per-node events and emit a single BatchCompleted event the client consumes as a "refresh everything visible" hint. Worth tracking as a separate issue if perf telemetry surfaces it. Engineering principle: prefer correctness and low client latency by default; optimize the hot path with a measurable signal, not speculatively.

🟢 Nits (optional polish)

  • Nit: node_service.rs:303 clones Arc<CoreNodeService> outside the stream and moves it into the async_stream closure. Fine, but a comment explaining why the clone is needed (the stream outlives the function scope) would aid future readers.
  • Nit: watcher.rs:42 hardcodes http://[::1]:50051 as DEFAULT_ENDPOINT while nodespaced may bind to IPv4 127.0.0.1 depending on platform. The NODESPACED_ADDR env-var override at watcher.rs:62 is the escape hatch, but worth confirming the daemon's default bind matches before Migrate Tauri command handlers to thin gRPC proxy wrappers #1113 activates this. Not a defect in this PR; flagging for the activation PR.
  • Nit: grpc_round_trip.rs:298 uses a hardcoded 5-second timeout. Reasonable for a CI runner under load, but consider extracting it as a const TEST_EVENT_TIMEOUT: Duration near the helper for one-line tuning if CI starts flaking.
  • Nit: node_service.rs:312 — the convert_domain_event call awaits inside the stream loop, which means a slow get_node lookup will block the next rx.recv(). With one slow refetch, lag risk on the broadcast channel rises. Not actionable now (alternative would be per-event spawn, which loses ordering guarantees), but a comment acknowledging the serial-translation tradeoff would clarify intent.

Final Recommendation: APPROVE

The PR is a net-positive change that correctly scopes the daemon side of WatchNodes and lays inert-but-ready scaffolding for the Tauri side. The architectural decision to consume the existing core event channel rather than introducing a second EventBus is the right call. The three integration tests cover all three AC paths reasonably well. Issues 🟡-1 and 🟡-2 are real contract changes that #1113 must reconcile before flipping the switch — they should be tracked as part of that issue's checklist, not blockers for this scaffold.

@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.

Recommendation: APPROVE. Full review posted as a PR comment. (GitHub blocks formal --approve on self-authored PRs, so leaving the recommendation as a review comment.)

…xlate

Addresses reviewer feedback on PR #1145:

🟡 #1 — node:deleted payload contract aligned with DomainEventForwarder
Extend proto `NodeDeleted` with `node_type` (carried from
`DomainEvent::NodeDeleted::node_type` in the core event channel).
Watcher now emits `{ id, nodeType }` for delete events, matching the
in-process forwarder's payload exactly. Test asserts the field is
populated. This unblocks #1113 — when it removes
DomainEventForwarder, the watcher carries the same information.

🟢 Nit-1 — document Arc clone in watch_nodes
Comment explains the stream future outlives `&self` so the Arc must
own its own handle.

🟢 Nit-3 — extract WATCH_EVENT_TIMEOUT constant
5-second per-event timeout in WatchNodes tests is now named, so a CI
flake can be retuned in one line.

🟢 Nit-4 — document serial translation tradeoff
Comment in the WatchNodes stream loop notes that a slow `get_node`
delays the next `rx.recv()` and increases lag risk. Acceptable for
point-reads; documents the parallelization path if telemetry forces it.

Skipped (with reasoning):

🟡 #2 — source_client_id feedback-loop filter not honored:
Reviewer explicitly tagged this as "worth addressing in #1113, not
blocking this PR". The fix requires propagating envelope metadata
through the proto, which is a contract widening best done with a
consumer (which lands in #1113). #1113 already owns the
SharedNodeStore idempotency audit.

🟡 #3 — Stream-close test is indirect:
Reviewer acknowledged the surrogate test (verify a fresh watcher works
after one drops) is acceptable and that direct observation would
require invasive instrumentation. The gap is documented in the test.

🟡 #4 — Per-event get_node refetch:
Reviewer explicitly said "track as separate issue if perf telemetry
surfaces it" — premature without measurement. Documented as a
parallelization path in Nit-4 above.

🟢 Nit-2 — IPv4/IPv6 endpoint mismatch concern:
Verified daemon binds `[::1]:50051` (main.rs:24) and watcher dials the
same address (watcher.rs:42). The reviewer's concern was theoretical;
the existing doc comment at watcher.rs:41 already documents the match.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review — Summary

Pushed 28833f64 addressing reviewer feedback.

✅ Addressed (4)

  • 🟡 Set up Tauri + Svelte project structure #1 — node:deleted payload contract. Extended proto NodeDeleted with node_type field; daemon translation now propagates DomainEvent::NodeDeleted::node_type; watcher emits { id, nodeType } matching the in-process DomainEventForwarder exactly. Integration test asserts the new field. This unblocks Migrate Tauri command handlers to thin gRPC proxy wrappers #1113 — when it removes DomainEventForwarder, the watcher carries equivalent information.
  • 🟢 Nit-1 — Arc clone doc comment. Added a comment explaining the stream future outlives &self, so the Arc<NodeService> must own its own handle.
  • 🟢 Nit-3 — WATCH_EVENT_TIMEOUT constant. Extracted the 5-second per-event timeout so future CI flakes can be retuned in one line.
  • 🟢 Nit-4 — Serial translation tradeoff comment. Documented that a slow get_node lookup delays the next rx.recv() and the parallelization path if telemetry forces it.

⏭️ Skipped (4) with reasoning

Verification

  • ✅ cargo test -p nodespace-daemon — 10/10 passing (including the updated assertion on node_type in delete)
  • ✅ cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async — clean
  • ✅ cargo clippy -p nodespace-app --all-targets -- -D warnings -D clippy::unused-async — clean
  • ✅ cargo fmt --all -- --check — clean
  • ✅ cargo check -p nodespace-app — clean

@malibio
malibio merged commit 77fc9af into main May 18, 2026
@malibio
malibio deleted the worktree-issue-1114 branch May 18, 2026 01:09
malibio added a commit that referenced this pull request Jun 22, 2026
…) (#1145)

* Implement WatchNodes gRPC streaming, add Tauri watcher.rs (closes #1114)

Daemon side (live):
- Replace WatchNodes Unimplemented stub with async_stream handler that
  subscribes to NodeService::subscribe_to_events() and translates each
  DomainEvent::Node{Created,Updated,Deleted} into a proto NodeEvent.
- For Created/Updated, fetch the current node payload so clients get
  full node data inline (no follow-up GetNode round trip).
- Handle broadcast lag as a warn-and-continue rather than a hard error;
  on channel closure, end the stream cleanly.
- Add 3 integration tests: single-watcher round trip (create/update/delete),
  multiple concurrent watchers receiving the same event, and a fresh
  watcher succeeding after a prior client dropped its stream.

Filter fields (WatchRequest.node_type, root_id) are accepted but
ignored — the issue's Non-Goals list filtering as a future enhancement.
A debug log fires when a non-default filter is requested.

No ops-layer changes were needed: nodespace_core already publishes
domain events via NodeService::subscribe_to_events(), so the daemon
becomes a pure event consumer/translator.

Tauri side (inert until #1113):
- New packages/desktop-app/src-tauri/src/watcher.rs module: gRPC client
  that opens a WatchNodes stream against nodespaced, re-emits each
  proto event as a Tauri event (node:created/updated/deleted) using the
  same NodeIdPayload format as the existing in-process
  DomainEventForwarder, and reconnects with exponential backoff
  (1s start, 30s cap).
- Module is declared in lib.rs but not spawned. Activation belongs to
  #1113 (Tauri → thin gRPC client migration), which will remove
  DomainEventForwarder and call watcher::spawn() in its place. Running
  both simultaneously would double-emit every node:* event.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address review: extend NodeDeleted with node_type, doc clones/serial xlate

Addresses reviewer feedback on PR #1145:

🟡 #1 — node:deleted payload contract aligned with DomainEventForwarder
Extend proto `NodeDeleted` with `node_type` (carried from
`DomainEvent::NodeDeleted::node_type` in the core event channel).
Watcher now emits `{ id, nodeType }` for delete events, matching the
in-process forwarder's payload exactly. Test asserts the field is
populated. This unblocks #1113 — when it removes
DomainEventForwarder, the watcher carries the same information.

🟢 Nit-1 — document Arc clone in watch_nodes
Comment explains the stream future outlives `&self` so the Arc must
own its own handle.

🟢 Nit-3 — extract WATCH_EVENT_TIMEOUT constant
5-second per-event timeout in WatchNodes tests is now named, so a CI
flake can be retuned in one line.

🟢 Nit-4 — document serial translation tradeoff
Comment in the WatchNodes stream loop notes that a slow `get_node`
delays the next `rx.recv()` and increases lag risk. Acceptable for
point-reads; documents the parallelization path if telemetry forces it.

Skipped (with reasoning):

🟡 #2 — source_client_id feedback-loop filter not honored:
Reviewer explicitly tagged this as "worth addressing in #1113, not
blocking this PR". The fix requires propagating envelope metadata
through the proto, which is a contract widening best done with a
consumer (which lands in #1113). #1113 already owns the
SharedNodeStore idempotency audit.

🟡 #3 — Stream-close test is indirect:
Reviewer acknowledged the surrogate test (verify a fresh watcher works
after one drops) is acceptable and that direct observation would
require invasive instrumentation. The gap is documented in the test.

🟡 #4 — Per-event get_node refetch:
Reviewer explicitly said "track as separate issue if perf telemetry
surfaces it" — premature without measurement. Documented as a
parallelization path in Nit-4 above.

🟢 Nit-2 — IPv4/IPv6 endpoint mismatch concern:
Verified daemon binds `[::1]:50051` (main.rs:24) and watcher dials the
same address (watcher.rs:42). The reviewer's concern was theoretical;
the existing doc comment at watcher.rs:41 already documents the match.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[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.

Implement WatchNodes gRPC streaming to replace Tauri event system for UI reactivity

1 participant