Skip to content

Implement nodespaced binary: gRPC server and NodeService handlers - #1131

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1112-nodespaced-grpc-server
May 17, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1112-nodespaced-grpc-server

Conversation

@malibio

@malibio malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator

Closes #1112. Builds on the proto/build pipeline merged in #1126.

Summary

  • Ship the nodespaced binary: tokio runtime, SurrealStore + NodeService bootstrap, tonic server on [::1]:50051, SIGTERM/SIGINT graceful shutdown that drains in-flight RPCs before releasing the RocksDB lock.
  • NodeServiceImpl wraps nodespace_core::ops and maps OpsError → tonic::Status (NotFound, Aborted on version conflict, FailedPrecondition, InvalidArgument, Internal). CreateNode/GetNode/UpdateNode/DeleteNode/GetChildren are live; SearchNodes returns Unavailable until the embedding service is wired by a follow-up; WatchNodes and Chat return Unimplemented per the issue's non-goals.
  • Five integration tests (tests/grpc_round_trip.rs) spin the server up in-process on an ephemeral port with a tempdir-backed SurrealDB and exercise the full client → server → core round trip.

Acceptance Criteria

  • nodespaced binary builds and starts without error
  • gRPC server listens on localhost:50051 ([::1]:50051, override via NODESPACED_ADDR)
  • All NodeService RPC methods registered and respond correctly (Create / Get / Update / Delete / GetChildren / SearchNodes — last returns Unavailable until embeddings are wired)
  • WatchNodes streaming RPC registered (returns Unimplemented)
  • Chat streaming RPC registered (returns Unimplemented)
  • Graceful shutdown on SIGTERM / SIGINT (verified via manual smoke test — see test plan)
  • cargo build --bin nodespaced succeeds
  • Integration test: start daemon, send GetNode via gRPC client, verify response (create_then_get_round_trip)
  • Code passes bun run quality:fix (cargo fmt, cargo clippy --all-targets -- -D warnings, eslint, svelte-check)

Test plan

  • cargo test -p nodespace-daemon --test grpc_round_trip — 5 / 5 passed
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo fmt --all -- --check — clean
  • bun run test — 128 files / 3918 tests passed (matches pre-change baseline, no regression)
  • bun run --cwd packages/desktop-app quality:fix — 0 errors / 0 warnings
  • Manual smoke test: started nodespaced against /tmp/nodespaced-smoke-test, confirmed gRPC server log, sent SIGTERM, observed SIGTERM received — initiating graceful shutdown and nodespaced shutdown complete

Out of scope (separate issues)

  • Tauri command migration
  • Real WatchNodes streaming implementation
  • CLI binary and system tray
  • Wiring NodeEmbeddingService so SearchNodes becomes live

🤖 Generated with Claude Code

…oses #1112)

Builds on the proto/build pipeline from #1111 to ship the actual daemon:

- packages/daemon/src/main.rs — tokio runtime, SurrealStore + NodeService
  bootstrap, tonic Server bound to [::1]:50051, SIGTERM/SIGINT graceful
  shutdown that drains in-flight RPCs before releasing the RocksDB lock.
  Honors NODESPACED_DB_PATH and NODESPACED_ADDR for testing/alt deployments.

- packages/daemon/src/services/node_service.rs — NodeServiceImpl wrapping
  nodespace_core::ops. Maps OpsError → tonic::Status (NotFound, Aborted on
  version conflict, FailedPrecondition, InvalidArgument, Internal).
  CreateNode/GetNode/UpdateNode/DeleteNode/GetChildren are live; SearchNodes
  returns Unavailable until the embedding service is wired by a follow-up;
  WatchNodes and Chat return Unimplemented per the issue's non-goals.

- packages/daemon/Cargo.toml — adds the [[bin]] target plus tokio,
  tokio-stream, tracing, tracing-subscriber, anyhow, serde_json, async-trait,
  and nodespace-core deps.

- packages/daemon/tests/grpc_round_trip.rs — five integration tests that
  spin the server up in-process on an ephemeral port with a tempdir-backed
  SurrealDB and exercise the full client → server → core round trip
  (create+get, update auto-versioning, get_children, delete, NotFound mapping).

Manual smoke test confirmed clean SIGTERM shutdown.

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

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

Code Review Summary

This PR cleanly delivers the nodespaced daemon binary with gRPC server bootstrap, NodeService handler wiring, graceful shutdown, and a five-test integration suite. The implementation matches ADR-031 and #1112's stated scope, hits every in-scope acceptance criterion, and is a clear net improvement to the codebase. Code is idiomatic Rust, no lint suppression, no #[allow(dead_code)], error mapping is thoughtful, and the in-process test harness with ephemeral ports and tempdir-backed Surreal stores is exactly the right pattern.

Verdict: Approve with one critical correctness issue in shutdown_signal that should be addressed, plus a handful of improvements and nits worth considering before merge or in a quick follow-up.


Acceptance Criteria Validation

Criterion Status Evidence
Binary builds and starts ✅ [[bin]] name = "nodespaced", cargo build --bin nodespaced confirmed; manual smoke test confirmed startup log + graceful shutdown
gRPC server listens on localhost:50051 ✅ DEFAULT_ADDR = "[::1]:50051" with NODESPACED_ADDR override
All NodeService RPCs registered + respond ✅ Create/Get/Update/Delete/GetChildren all live; SearchNodes returns Unavailable (gracefully degraded per design)
WatchNodes registered ✅ Returns Unimplemented as agreed
Chat registered ✅ Returns Unimplemented as agreed
Graceful shutdown on SIGTERM/SIGINT ⚠️ Mostly correct, but serve_with_shutdown will resolve prematurely if signal install fails — see Critical Issue below
cargo build --bin nodespaced succeeds ✅ Reported clean
Integration test: GetNode round trip ✅ create_then_get_round_trip + 4 additional tests
bun run quality:fix clean ✅ 0 errors, 0 warnings; clippy clean with -D warnings -D clippy::unused-async

Findings

Critical Issues

packages/daemon/src/main.rs:101-114 — shutdown_signal() resolves immediately on signal install failure, defeating graceful shutdown.

If signal(SignalKind::terminate()) or signal(SignalKind::interrupt()) fails (rare, but possible in sandboxed/containerized environments or constrained namespaces), the match arm logs the error and returns. Because shutdown_signal() is the future passed to serve_with_shutdown, an early return means the shutdown future resolves immediately, which causes the gRPC server to shut down before accepting any connections — producing a daemon that exits silently after logging an error.

This violates the principle of least surprise (failure to register a signal handler should not silently terminate the server) and breaks the "Graceful shutdown" acceptance criterion in pathological-but-real environments.

Suggested fix: propagate the install failure out of main(), or fall back to std::future::pending() so the server keeps serving until killed by the OS:

let mut sigterm = signal(SignalKind::terminate())
    .context("Failed to install SIGTERM handler")?;
let mut sigint  = signal(SignalKind::interrupt())
    .context("Failed to install SIGINT handler")?;

Returning the error from main() is cleaner: the operator sees the failure and the daemon refuses to start in a broken state, rather than starting + immediately dying. This requires changing shutdown_signal to return Result<(), anyhow::Error> plumbed through main, or installing the signals up-front in main and passing a smaller future to serve_with_shutdown. The latter is more idiomatic.

The non-unix branch has the same issue with ctrl_c().await — if it errors, the server shuts down. Same fix applies.


Suggested Improvements

packages/daemon/src/services/node_service.rs:91-116 — get_node performs two redundant storage round trips.

The handler calls node_ops::get_node(...) (which internally fetches the node, validates existence, and returns a typed JSON value) and then discards the result, immediately calling fetch_node(...) for the canonical Node struct. Two round trips per GetNode RPC.

The reason appears to be that node_ops::get_node returns serde_json::Value (typed view) while you want the canonical Node for node_to_proto. Suggest skipping node_ops::get_node here entirely and calling service.get_node(...) directly with the same NotFound mapping you already have in fetch_node. The ops-layer call adds nothing because there's no additional validation logic the handler benefits from — it's a pure pass-through to service.get_node.

This is purely a perf/clarity win — semantically the current code is correct.

packages/daemon/src/services/node_service.rs:206-289 — search_nodes N+1 re-fetch by node id.

After search_ops::search_semantic returns the typed JSON values, the handler loops and fetches each node individually via service.get_node(id). For a search returning N results this is N additional round trips. Comment on line 267-268 acknowledges the intent ("populate every NodeData field directly from the canonical Node struct rather than re-parsing the typed JSON").

For an MVP that returns Unavailable until embedding service wiring lands this is fine — but please leave a TODO(perf) or follow-up issue link so this doesn't get forgotten when SearchNodes goes live. Once it has real users a 20-result query will be 20 storage hits.

packages/daemon/src/services/node_service.rs:185-189 — get_children error mapping is inconsistent with the rest of the file.

Every other handler maps service errors through ops_error_to_status (which produces NotFound / Aborted / FailedPrecondition / InvalidArgument / Internal based on the variant). get_children calls self.node_service.get_children(...) directly and uniformly returns Status::internal. That's a NodeServiceError, not an OpsError, so the existing ops_error_to_status doesn't apply directly — but it means a NodeNotFound { id } for the parent leaks out as a generic Internal error rather than NotFound.

Two options: (a) introduce a thin nodespace_error_to_status helper mirroring ops_error_to_status, or (b) wrap the call in OpsError::from(err) via the existing From<NodeServiceError> impl and reuse ops_error_to_status. Option (b) is one extra line and gets you proper code mapping for free.

packages/daemon/src/services/node_service.rs:131-153 — update_node discards parent_id.

The handler hard-codes parent_id: String::new() in the response and passes None to node_to_proto. The Node struct doesn't carry parent_id (confirmed via packages/core/src/models/node.rs), so technically correct — but this means update responses lack parent context that clients may rely on for cache invalidation. For an MVP this is acceptable, but consider documenting this gap on the proto or filing a follow-up to populate parent_id from a separate get_parent_edge call. The same pattern applies to get_node (line 112).

Acceptable for now per "MVP, follow-up issues exist" framing, but please surface this in a tracking issue.

packages/daemon/src/main.rs:66-76 — Arc<SurrealStore> mutability dance.

let mut store = Arc::new(SurrealStore::new(...)) and CoreNodeService::new(&mut store) works, but signals that the core API requires &mut Arc<SurrealStore> — which is unusual. Not blocking on this PR (it's a packages/core API shape decision), but worth noting if you're considering a small API cleanup. Could be Arc<SurrealStore> by value if CoreNodeService::new cloned internally. Out of scope here.

packages/daemon/src/services/node_service.rs:218 — let _ = req.semantic; swallows a request field silently.

The proto field semantic: bool is explicitly ignored with a binding suppression. Two improvements:

  1. Either honor the field (return InvalidArgument if semantic == false since structured query mode is not implemented) or
  2. At minimum, tracing::debug!(semantic = req.semantic, "search_nodes: semantic field reserved for future structured-query mode") so callers can observe what's happening.

Silent acceptance of a flag that does nothing is a footgun for future clients.


Test Coverage Assessment

The 5 integration tests are well-constructed: each spins up its own tempdir-backed SurrealStore on an ephemeral port (no shared-state risk), uses oneshot for clean shutdown, and includes a retry loop on the client dial to absorb startup race. Good engineering.

Gaps worth filing (not blocking):

  • No version conflict test. OpsError::VersionConflict → Status::aborted mapping is exercised nowhere. Easy to add: create a node, call update with version: Some(99), assert Code::Aborted.
  • No validation failure test. OpsError::ValidationFailed → Status::failed_precondition is untested. e.g., create with an invalid node_type if validation kicks in there.
  • No malformed JSON properties test. parse_properties returns InvalidArgument — straightforward to verify.
  • No SearchNodes test — even just asserting Code::Unavailable would lock in the "graceful disable" behavior so it doesn't regress when the embedding service gets wired in.
  • No graceful shutdown integration test. Send a request, fire shutdown mid-flight, assert it completes. The current tests only verify that oneshot::Sender<()> shuts the server down between RPCs, not the in-flight drain behavior.

These are all valuable but reasonably belong in a follow-up "expand daemon test coverage" issue rather than blocking this PR.


Nitpicks

  • Nit: packages/daemon/src/main.rs:42 — format!("Invalid NODESPACED_ADDR: {}", raw) would be clearer using inlined formatting: format!("Invalid NODESPACED_ADDR: {raw}"). Same on lines 63 and elsewhere. Clippy uninlined_format_args will surface this if you enable it.
  • Nit: packages/daemon/src/services/node_service.rs:319-325 — empty_to_none is a perfect candidate for Option::Some(s).filter(|s| !s.is_empty()) or (!s.is_empty()).then_some(s). Current form is fine — readability is roughly the same.
  • Nit: packages/daemon/src/services/node_service.rs:65 — req.parent_id.clone() is cloned in the empty_to_none call site even though empty_to_none takes String by value. The clone is unnecessary since req is the owned into_inner() value; just pass req.parent_id directly. Same applies to req.node_type.clone() on line 63 (you immediately drop the clone). Several other handlers have the same pattern.
  • Nit: packages/daemon/src/main.rs:42 and :63 use {:?} for PathBuf formatting — for a user-facing error message, path.display() is more readable (no escaping of separators).
  • Nit: packages/daemon/tests/grpc_round_trip.rs:51 — using tokio_stream::wrappers::TcpListenerStream is fine; Server::builder().add_service(...).serve_with_incoming_shutdown(incoming, ...) would also accept the TcpListener directly via tonic::transport::server::TcpIncoming, which avoids the extra tokio-stream dance. Not worth changing now.
  • Nit: Tests panic with panic!("failed to connect to in-process daemon: {:?}", last_err) after 20 retries with 25ms sleep (500ms total). On a heavily loaded CI runner this could be tight. Consider 50 × 25ms or 20 × 50ms.
  • Nit: packages/daemon/src/services/node_service.rs:189 — error message says "get_children failed" but lacks the node id for debuggability. format!("get_children for parent {} failed: {}", req.node_id, e).

What Was Done Well

  • Idiomatic tokio/tonic plumbing — no spawning issues, no blocking calls in async contexts.
  • OpsError → tonic::Status mapping is precise and follows gRPC conventions (NotFound, Aborted for version conflict, FailedPrecondition for validation, InvalidArgument for bad params).
  • Tracing is wired with sensible defaults (EnvFilter, info-level fallback).
  • Tempdir-backed test harness with ephemeral ports correctly avoids the 50051 port collision problem.
  • Library/binary split lets integration tests run in-process — much better than spawning child processes.
  • Comments explain why (e.g., the parent_id_for_data clone, the semantic field reservation, the re-fetch loop rationale) rather than mechanics.
  • Honors NODESPACED_DB_PATH and NODESPACED_ADDR overrides — good operational ergonomics for testing and alt deployments.
  • No lint suppression, no #[allow(dead_code)], no deprecated/transition code. Matches CLAUDE.md "pre-release, no backwards compat" stance.

Recommendation

Approve. Please address the Critical Issue (shutdown_signal premature resolution on signal install failure) — it's a one-line fix with anyhow context propagation. The Suggested Improvements are good-to-haves; if you take the get_node redundant round trip and the get_children error mapping in this PR they're tiny diffs, otherwise file follow-ups. Test coverage gaps and search_nodes N+1 are best tracked as separate issues.

Solid foundation for ADR-031. Ready to ship after the shutdown fix.

Critical:
- Install signal handlers in main() with `?` so a failure to register
  becomes a startup error rather than a silent shutdown future that
  resolves immediately and kills the server as soon as it begins
  listening. Renamed shutdown_signal → install_shutdown_handler to
  reflect that registration now happens at boot.

Improvements:
- get_node: drop the redundant ops::get_node round-trip; call
  service.get_node directly and map None → NotFound. node_ops::get_node
  added no validation here it just re-fetched the same node.
- get_children: route NodeServiceError through OpsError::from +
  ops_error_to_status so a missing parent surfaces as NotFound instead
  of leaking as a generic Internal.
- search_nodes: log when req.semantic=false rather than silently
  ignoring the field; clients can now observe the discrepancy via
  tracing.

Tests:
- Bump connect retry budget from 20×25ms (500ms) → 50×25ms (1.25s) for
  heavily loaded CI runners.
- Add `search_nodes_returns_unavailable_without_embedding_service` to
  lock in the graceful-disable contract.
- Add `create_node_rejects_malformed_properties` to verify JSON parse
  errors map to InvalidArgument, not Internal.

Nits:
- Inline format strings (`{var}` syntax).
- Use `path.display()` for user-facing path messages instead of `{:?}`.
- Drop redundant clones in create_node now that response reads from
  `output` rather than `req`.

Skipped (filed as follow-ups instead):
- search_nodes N+1 re-fetch: path returns Unavailable today; will be
  fixed when embedding service is wired.
- NodeResponse.parent_id population in get_node/update_node:
  requires packages/core API changes to expose parent context via
  Node or a sibling lookup; out of scope for the daemon shell.
- Test gaps for VersionConflict, FailedPrecondition, in-flight drain:
  non-trivial setup, worth a focused test issue.

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

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review Response

Pushed da3da67e addressing the review.

Addressed

Critical

  • 🔴 shutdown_signal premature resolution (main.rs:101-114 → main.rs:65, 108-131) — signal handlers now installed in main() with ? before the server starts. A registration failure surfaces as a startup error and the daemon refuses to come up, rather than starting and immediately dying. Renamed to install_shutdown_handler so the boot-time contract is obvious.

Important

  • 🟡 get_node double round-trip — dropped the redundant node_ops::get_node call; handler now talks to service.get_node directly with NotFound mapping. GetNodeInput import removed.
  • 🟡 get_children error mapping — now routes through OpsError::from(NodeServiceError) → ops_error_to_status. A missing parent surfaces as NotFound instead of leaking as Internal.
  • 🟡 req.semantic silently ignored — added tracing::debug! when set to false so the discrepancy is observable. Did not flip to InvalidArgument because proto3 can't distinguish unset-false from explicit-false, so rejecting false would break every default-constructed client.

Nits

  • Inlined format strings ({var} syntax) in main.rs.
  • path.display() replaces {:?} in user-facing path messages.
  • Dropped redundant clones in create_node now that the response reads from output rather than req.
  • Bumped connect retry budget from 20×25ms → 50×25ms (1.25s) for slow CI.
  • Added two new tests:
    • search_nodes_returns_unavailable_without_embedding_service — locks in the graceful-disable contract.
    • create_node_rejects_malformed_properties — verifies JSON parse errors map to InvalidArgument.

Test count: 7/7 passing (was 5/5). Manual SIGTERM smoke test re-verified.

Skipped (with reasoning)

  • 🟡 search_nodes N+1 re-fetch — path returns Unavailable today; adding a TODO comment about a code path that doesn't run yet is noise. Will be addressed when the embedding service is wired in a follow-up issue, where the actual perf characteristics can be measured.
  • 🟡 update_node / get_node discard parent_id — requires packages/core API changes to either carry parent_id on Node or expose a fast parent lookup. Out of scope for the daemon shell; worth a focused issue against packages/core.
  • 🟡 Arc<SurrealStore> mutability dance — reviewer flagged as a packages/core API shape issue, not blocking.
  • 🟢 empty_to_none → .then_some() — current form is more explicit; readability tradeoff is a wash.
  • 🟢 Test gaps (VersionConflict, FailedPrecondition, in-flight drain) — non-trivial to set up cleanly; better as a dedicated test-coverage issue. The cheap ones (malformed JSON, SearchNodes Unavailable) were added.

Verification

  • cargo test -p nodespace-daemon --test grpc_round_trip → 7/7 passed
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async → clean
  • cargo fmt --all -- --check → clean
  • bun run test → 128 files / 3918 tests passed (matches baseline)
  • Manual smoke test confirmed clean SIGTERM shutdown with new install_shutdown_handler flow

🤖 Generated with Claude Code

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

Re-Review of da3da67e (delta only)

This is a re-review of the single follow-up commit da3da67e. Original commit 9dc2bad6 was previously reviewed and is not re-evaluated here.

Verdict: Approve (commented, not own-approvable). The critical issue from the previous review is properly resolved, the in-scope Important findings are well-addressed, and the skipped items remain appropriately out of scope. Tests, clippy (-D warnings -D clippy::unused-async), and fmt all pass.


Addressed Correctly

Critical — shutdown_signal premature resolution (FIXED)

  • install_shutdown_handler is now a sync function that installs SIGTERM/SIGINT handlers eagerly with ? and returns Result<impl Future<Output = ()>>. Called in main() at line 65 before Server::builder().serve_with_shutdown(addr, shutdown), so handler-install failure becomes a startup error and the daemon refuses to come up.
  • Future shape is Send + 'static (captures owned Signal handles which are Send) — valid for serve_with_shutdown's F: Future<Output = ()> bound. No Send/'static issues.
  • No race window: tokio::signal::unix::Signal queues signals on the handle once signal() returns, so a signal arriving between handler install (line 65) and server bind (line 92) is delivered to the first recv().
  • The non-unix branch still logs-and-resolves on ctrl_c() error, but that's the platform's only failure mode and effectively infallible on Windows. Acceptable.

Important — get_node double round-trip (FIXED)

  • Redundant node_ops::get_node call removed; handler now calls fetch_node directly which preserves NotFound mapping via Status::not_found(...). GetNodeInput import cleanly dropped from the use group. No behavioral regression.

Important — get_children error mapping (FIXED)

  • Now ops_error_to_status(OpsError::from(e)). Verified impl From<NodeServiceError> for OpsError in packages/core/src/ops/mod.rs:40 maps NodeNotFound { id } → OpsError::NotFound { id }, which ops_error_to_status maps to Status::not_found("Not found: {id}") — so a missing parent now correctly surfaces as NotFound (and the parent id is included in the message, indirectly addressing my earlier debuggability nit).

Important — req.semantic silently swallowed (FIXED)

  • let _ = req.semantic replaced with a tracing::debug! when !req.semantic. The comment about proto3 unset-vs-explicit-false is accurate justification for not flipping to InvalidArgument. One subtle point: proto3 defaults bool to false, so every default-constructed client triggers the debug log — but at debug level this is fine (opt-in observability, no spam at info).

Nits — all applied

  • Format strings inlined ({raw}, etc.).
  • path.display() used for both the startup log and the parent-dir error.
  • req.node_type.clone() / req.parent_id.clone() redundant clones dropped in create_node (the remaining output.parent_id.clone() and output.collection_id.clone() are necessary because each Option<String> is consumed twice).
  • Retry budget bumped 20→50 (1.25s).

New tests — meaningful

  • search_nodes_returns_unavailable_without_embedding_service: locks the graceful-disable contract. SearchRequest::default() works as expected (prost emits Default for proto3 messages).
  • create_node_rejects_malformed_properties: asserts Code::InvalidArgument. Stable expectation. Both tests use the existing spawn_test_daemon harness with tempdir + ephemeral port, no shared state.

Skipped — Appropriately Out of Scope

  • search_nodes N+1 re-fetch — Path returns Unavailable until the embedding service is wired, so optimizing dead code is premature. Reasonable to defer to the embedding-wiring issue where perf can be measured against real data.
  • parent_id population in get_node/update_node — Requires packages/core API change (either carrying parent_id on Node or exposing a fast parent lookup). Correctly framed as cross-package; out of scope for the daemon shell.
  • Arc<SurrealStore> mutability dance — Previously acknowledged as a packages/core API shape issue; not blocking.
  • Remaining test gaps (VersionConflict, FailedPrecondition, in-flight drain) — The cheap ones (malformed JSON, SearchNodes Unavailable) are in. The remainder warrants a focused test-coverage follow-up issue; current 7/7 coverage is solid for the MVP.

New Findings

None. The delta is tight, clippy-clean (-D warnings -D clippy::unused-async), fmt-clean, and all 7 integration tests pass on my local rebuild. No new validation drops, no dropped error mapping, no Send/'static or shutdown-race regressions introduced.


Verification (local)

  • cargo check -p nodespace-daemon --all-targets → clean
  • cargo clippy --workspace --all-targets -- -D warnings → clean
  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings -D clippy::unused-async → clean
  • cargo fmt --all -- --check → clean
  • cargo test -p nodespace-daemon --test grpc_round_trip → 7/7 passed

Ready to merge.

@malibio
malibio merged commit 5e7ef28 into main May 17, 2026
@malibio
malibio deleted the feature/issue-1112-nodespaced-grpc-server branch May 17, 2026 18:48
malibio pushed a commit that referenced this pull request May 17, 2026
## Completed in This Session
- [x] Phase 2: `cargo build -p nodespace-daemon` validates proto compiles
  (proto from prior WIP accepted by tonic-build with no changes)
- [x] Phase 3: Implemented 26 new nodespaced gRPC handlers in
  `packages/daemon/src/services/node_service.rs` (+~900 LOC net)
  - All 28 RPCs declared in the proto are implemented; only WatchNodes/Chat
    remain stubbed (tracked separately)
  - Existing create_node handler rewritten to use create_node_with_parent
    directly so the new `id` and `insert_after_node_id` proto fields flow
    through; collection-path + lifecycle_status applied as before
  - update_node rewritten to call NodeService::update_node directly and
    handle add_to_collection / remove_from_collection out-of-band (the
    node_ops route silently dropped those fields)
  - delete_node auto-fetches version when proto field unset, mirroring the
    ops-layer idempotent behaviour
  - update_task_node parses tri-state OptionalStringClear /
    OptionalTimestampClear wrappers into Option<Option<T>> for the core
    TaskNodeUpdate; converts result via TaskNode::into_node
  - get_schema_definition fetches raw Node and verifies node_type=="schema"
    so the wire shape stays NodeResponse (Tauri reconstructs via
    SchemaNode::from_node)
  - Collection handlers use CollectionService consistently (constructed
    per-call from store + node_service) — including the recursive members
    path which preserves member_ids ordering on a batched fetch
  - service_error_to_status helper bridges NodeServiceError →
    OpsError → tonic::Status so all handlers map errors identically
- [x] Phase 4: Tauri gRPC client scaffolding wired in
  - Added `nodespace-daemon`, `tonic`, `prost` as workspace deps; added
    `chrono` to daemon Cargo.toml (needed for OptionalTimestampClear parsing)
  - New `packages/desktop-app/src-tauri/src/services/grpc_client.rs`:
    spawns an in-process tonic server on `127.0.0.1:0` (OS-chosen port) and
    connects a `NodeServiceClient<Channel>`. Reuses the same
    `Arc<NodeService>` AppServices already owns — no second DB open.
  - `commands/db.rs::init_services()` calls `GrpcClient::start(...)` after
    AppServices is populated and registers it via `app.manage()`
- [x] Both crates build clean: `cargo build -p nodespace-daemon` and
  `cargo build -p nodespace-app` succeed with no warnings

## Remaining Work

### Phase 5: Migrate Tauri command handlers (~2000 LOC churn)

Rewrite the three in-scope command files to proxy through the new
`State<'_, GrpcClient>` instead of calling `packages/core` methods:

- [ ] `packages/desktop-app/src-tauri/src/commands/nodes.rs` — 19 handlers
- [ ] `packages/desktop-app/src-tauri/src/commands/collections.rs` — 12 handlers
- [ ] `packages/desktop-app/src-tauri/src/commands/schemas.rs` — 2 handlers

For each handler:
- Replace `State<'_, AppServices>` with `State<'_, GrpcClient>` (or add
  alongside if the handler still needs AppServices for unrelated reasons —
  none in scope should, but verify)
- Replace direct `services.node_service().await?.X(...)` calls with
  `client.client().X(Request::new(ProtoRequest { ... })).await?`
- Map `tonic::Status` → existing `CommandError` (preserve gRPC status codes
  in the `code` field so the frontend keeps its current error UX)
- Translate proto response back to the existing return type:
  - `NodeData` → reconstruct `Node` (deserialize `properties` JSON, parse
    timestamps) then call `models::node_to_typed_value()` exactly as today
  - `SchemaNode` paths: call `SchemaNode::from_node()` on the reconstructed
    Node
  - `TaskNode` updates: parse properties to rebuild `TaskNode` for the
    frontend (matches the proto design decision baked in earlier)
  - `CollectionInfo` (member_count + parent_collection_ids) maps 1:1 to the
    existing CollectionInfo struct
  - `tree_json` from `get_children_tree` is already a JSON string — parse
    with `serde_json::from_str` and return the Value
- `create_node`: pass `id: node.id` (frontend-supplied UUID) and
  `insert_after_node_id: node.insert_after_node_id` through new proto fields
- `create_root_node`: same as create_node but with parent_id=""; if
  `mentioned_by` is provided, follow with a `CreateMention` RPC
- `update_task_node`: build the tri-state OptionalStringClear /
  OptionalTimestampClear wrappers from `TaskNodeUpdate`'s
  `Option<Option<T>>` fields

### Phase 6: Final validation
- [ ] `cargo build -p nodespace-app` (re-verify after Phase 5)
- [ ] `bun run test:all` — no new failures vs baseline (128 files / 3918 tests)
- [ ] `bun run quality:fix` — commit any fixes
- [ ] Create PR via `bun run gh:pr 1113`

## Current State

### Files modified
- `Cargo.toml` (+3) — added nodespace-daemon, tonic, prost workspace deps
- `Cargo.lock` (+4) — generated
- `packages/daemon/Cargo.toml` (+1) — added chrono
- `packages/daemon/src/services/node_service.rs` (+~900 LOC net) —
  implemented 26 new handlers + rewrote create_node/update_node/delete_node
- `packages/desktop-app/src-tauri/Cargo.toml` (+3) — daemon + tonic + prost
- `packages/desktop-app/src-tauri/src/commands/db.rs` (+15) — start gRPC
  server + register client during init_services
- `packages/desktop-app/src-tauri/src/services/mod.rs` (+2) — export
- `packages/desktop-app/src-tauri/src/services/grpc_client.rs` (new, ~115 LOC) —
  in-process tonic server + client wrapper

### Tests status
- Frontend baseline (from prior session): 128 files, 3918 tests passing
- Rust builds: `cargo build -p nodespace-daemon` and
  `cargo build -p nodespace-app` both clean
- Phase 5 migration still needed before frontend tests can verify
  end-to-end behaviour (commands today still call packages/core directly)

### Known issues
None blocking. The in-process gRPC server uses port 0 (OS-chosen) so it
won't collide with a standalone nodespaced running on `[::1]:50051` in
parallel during dev.

### Dependencies
- Depends on: #1111 (proto pipeline, closed), #1112 (nodespaced, closed),
  #1131 (NodeService gRPC handler, merged in 5e7ef28)
- Tracked alongside: #1114 (WatchNodes streaming)
- Out of scope per 2026-05-17 scope-clarification comment:
  embeddings.rs (#1135), import.rs (#1136), local_agent.rs (#1137),
  settings.rs (#1138), db.rs/diagnostics.rs/chat_models.rs/models.rs

## Context for Next Session

The mechanical work for Phase 5 is now well-defined: every in-scope command
has a matching gRPC RPC and the proto types are wired all the way through.
The biggest design decisions are already baked in from the proto session:

1. Tri-state encoding for TaskNodeUpdate (OptionalStringClear /
   OptionalTimestampClear handle Option<Option<T>>)
2. Schema reads return generic NodeResponse — Tauri side reconstructs the
   typed SchemaNode via from_node()
3. Updated tasks return generic NodeResponse — Tauri side reparses to
   TaskNode for the frontend
4. CollectionInfo is a dedicated proto message (not folded into properties)
5. get_children_tree returns wrapped JSON string

The Tauri command shells (CommandError mapping, validate_node_type, etc.)
can stay — only the inner ops calls flip to gRPC. The
`CreateNodeInput.embedding_vector` field on the Tauri side is unused and
not in the proto; the migration can drop it.

`State<'_, GrpcClient>` provides `client.client()` which returns a fresh
`NodeServiceClient<Channel>` clone per call (cheap — Channel is Arc).

## Acceptance Criteria Status (from #1113 + 2026-05-17 scope-clarification)

In-scope command files (nodes.rs, collections.rs, schemas.rs):
- [ ] All in-scope `#[tauri::command]` handlers proxy via gRPC (0/33)
- [ ] No direct `packages/core` imports remain in those three files (0/3)
- [x] gRPC client initialized on Tauri startup and stored in `tauri::State`
- [ ] All existing Tauri command return types preserved (frontend
  unchanged) — pending Phase 5
- [ ] Commands work end-to-end: Tauri frontend → gRPC proxy →
  in-process nodespaced → response — pending Phase 5
- [ ] Error cases propagate correctly (tonic::Status → CommandError) —
  pending Phase 5
- [x] `cargo build -p nodespace-daemon` succeeds
- [x] `cargo build -p nodespace-app` succeeds
- [ ] All frontend tests pass (`bun run test:all`) — pending Phase 5
- [ ] Code passes `bun run quality:fix` — pending Phase 5

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
)

* Implement nodespaced binary: gRPC server and NodeService handlers (closes #1112)

Builds on the proto/build pipeline from #1111 to ship the actual daemon:

- packages/daemon/src/main.rs — tokio runtime, SurrealStore + NodeService
  bootstrap, tonic Server bound to [::1]:50051, SIGTERM/SIGINT graceful
  shutdown that drains in-flight RPCs before releasing the RocksDB lock.
  Honors NODESPACED_DB_PATH and NODESPACED_ADDR for testing/alt deployments.

- packages/daemon/src/services/node_service.rs — NodeServiceImpl wrapping
  nodespace_core::ops. Maps OpsError → tonic::Status (NotFound, Aborted on
  version conflict, FailedPrecondition, InvalidArgument, Internal).
  CreateNode/GetNode/UpdateNode/DeleteNode/GetChildren are live; SearchNodes
  returns Unavailable until the embedding service is wired by a follow-up;
  WatchNodes and Chat return Unimplemented per the issue's non-goals.

- packages/daemon/Cargo.toml — adds the [[bin]] target plus tokio,
  tokio-stream, tracing, tracing-subscriber, anyhow, serde_json, async-trait,
  and nodespace-core deps.

- packages/daemon/tests/grpc_round_trip.rs — five integration tests that
  spin the server up in-process on an ephemeral port with a tempdir-backed
  SurrealDB and exercise the full client → server → core round trip
  (create+get, update auto-versioning, get_children, delete, NotFound mapping).

Manual smoke test confirmed clean SIGTERM shutdown.

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

* Address review feedback on nodespaced gRPC server

Critical:
- Install signal handlers in main() with `?` so a failure to register
  becomes a startup error rather than a silent shutdown future that
  resolves immediately and kills the server as soon as it begins
  listening. Renamed shutdown_signal → install_shutdown_handler to
  reflect that registration now happens at boot.

Improvements:
- get_node: drop the redundant ops::get_node round-trip; call
  service.get_node directly and map None → NotFound. node_ops::get_node
  added no validation here it just re-fetched the same node.
- get_children: route NodeServiceError through OpsError::from +
  ops_error_to_status so a missing parent surfaces as NotFound instead
  of leaking as a generic Internal.
- search_nodes: log when req.semantic=false rather than silently
  ignoring the field; clients can now observe the discrepancy via
  tracing.

Tests:
- Bump connect retry budget from 20×25ms (500ms) → 50×25ms (1.25s) for
  heavily loaded CI runners.
- Add `search_nodes_returns_unavailable_without_embedding_service` to
  lock in the graceful-disable contract.
- Add `create_node_rejects_malformed_properties` to verify JSON parse
  errors map to InvalidArgument, not Internal.

Nits:
- Inline format strings (`{var}` syntax).
- Use `path.display()` for user-facing path messages instead of `{:?}`.
- Drop redundant clones in create_node now that response reads from
  `output` rather than `req`.

Skipped (filed as follow-ups instead):
- search_nodes N+1 re-fetch: path returns Unavailable today; will be
  fixed when embedding service is wired.
- NodeResponse.parent_id population in get_node/update_node:
  requires packages/core API changes to expose parent context via
  Node or a sibling lookup; out of scope for the daemon shell.
- Test gaps for VersionConflict, FailedPrecondition, in-flight drain:
  non-trivial setup, worth a focused test issue.

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 nodespaced binary: gRPC server startup and NodeService registration

1 participant