Skip to content

Make daemon NodeService RPCs thin: delegate collection/lifecycle/version logic to core node_ops (B3 + B4) #1241

Closed

Description

@malibio

Spun off from the architectural-audit tracking issue #1228 (findings B3 and B4). These two findings are merged because they touch the same edit sites in packages/daemon/src/services/node_service.rs — every CollectionService::new(...) call (B4) sits inside the inline business logic B3 wants removed.

Background — the thin-adapter principle (ADR-031)

ADR-031 is explicit: core business logic lives in NodeService (in packages/core); the daemon's gRPC layer is a thin gateway that parses proto → calls core → maps the result back to proto. The module header of packages/daemon/src/services/node_service.rs (lines 1–7) restates this contract.

Today three RPCs violate that:

  • create_node (≈ lines 75–146): does collection-path resolution inline (lines 106–117), then lifecycle-status defaulting with a manual version re-fetch (lines 119–133).
  • update_node (≈ lines 166–227): auto-fetches the OCC version when the client omits it (lines 185–189), and performs add_to_collection / remove_from_collection out-of-band (lines 201–217).
  • Both build a throwaway CollectionService::new(store, &self.node_service) per call (lines 109, 203, 212 — plus 11 more across other RPCs in this file: 944, 970, 996, 1030, 1046, 1060, 1076, 1090, 1118, 1146, 1189).

Why this is a real bug, not just untidy layering

This exact logic already exists in core, in packages/core/src/ops/node_ops.rs:

  • node_ops::create_node — collection resolution and lifecycle defaulting — identical to the daemon's inline copy. The daemon comment at line 106 literally says "mirrors node_ops::create_node".
  • node_ops::update_node — version auto-fetch and collection add/remove.
  • node_ops::delete_node — version auto-fetch.

The agent already calls these ops directly: packages/agent/src/local_agent/tools.rs (create_node, update_node, delete_node). So the agent path and the daemon path are two hand-maintained copies of the same logic that can — and will — drift. Tests calling core directly get a third behavior. That is the inconsistent-contract problem B3 describes, made concrete.

Greenfield note: This is pre-release. Do not keep the inline daemon copy "for safety" or add compatibility shims. Delete the duplicated logic outright.

What to do

Single source of truth: the daemon delegates to node_ops

Refactor create_node, update_node, and delete_node in packages/daemon/src/services/node_service.rs so each handler:

  1. Parses the proto request into the corresponding node_ops input struct (CreateNodeInput, UpdateNodeInput, DeleteNodeInput).
  2. Calls nodespace_core::ops::node_ops::{create_node,update_node,delete_node}(&self.node_service, input).
  3. Maps the node_ops output (CreateNodeOutput / UpdateNodeOutput / DeleteNodeOutput) back into the proto NodeResponse / DeleteNodeResponse.
  4. Maps OpsError → Status via the existing ops_error_to_status helper (already used by the search RPC at line 407).

This is the same shape the search_nodes RPC already uses (it delegates to search_ops::search_semantic, line 405) — so there is precedent for the daemon-delegates-to-ops pattern in this very file.

Mapping nuance to handle explicitly

node_ops returns node_data as a serde_json::Value, whereas the current daemon handlers build a proto NodeData via node_to_proto. You must bridge this. Two acceptable options — pick one and apply it consistently:

  • (Preferred) Re-fetch + node_to_proto: after the ops call returns node_id / collection_id, call the existing fetch_node(&self.node_service, &node_id) and build the proto NodeData via node_to_proto, exactly as today. The ops call owns the business logic; the daemon owns only proto serialization. Keeps the wire shape byte-identical.
  • (Alternative) Convert Value → NodeData: only if a converter already exists or is trivial. Do not introduce a lossy or bespoke JSON→proto path just to avoid one re-fetch.

The NodeResponse envelope fields the daemon currently populates by hand (node_id, node_type, parent_id, collection_id) all map directly from the *Output structs.

Stale comment to verify and delete

The comment at node_service.rs lines 197–199 claims routing the update path through node_ops "would silently drop several fields." Cross-check against node_ops::update_node: it builds a NodeUpdate from content, node_type, properties, lifecycle_status and handles add_to_collection / remove_from_collection — i.e. it covers every field the daemon handles today. The claim appears stale. If after delegating you confirm full field parity, delete that comment. If a field genuinely is dropped, fix node_ops::update_node in core (do not re-add a daemon-side workaround).

B4 — CollectionService instantiation

Once create_node and update_node delegate to node_ops, the daemon's three CollectionService::new sites at lines 109, 203, 212 disappear entirely — collection resolution now happens inside node_ops (which already constructs its own CollectionService). That removes 3 of the 14 sites for free.

For the remaining 11 collection-RPC sites (944, 970, 996, 1030, 1046, 1060, 1076, 1090, 1118, 1146, 1189):

  • Do not optimize for allocation cost. Verified: CollectionService<'a> is a borrow-only struct — two references, no allocation, no I/O in new(). Rebuilding it per call is cheap. The B4 concern is architectural (the daemon shouldn't encode collection semantics), not performance.
  • Recommended fix: add the thin collection RPC bodies' logic as methods on core (a collection sub-module of NodeService, or collection_ops functions paralleling node_ops), so the daemon calls one core method instead of orchestrating CollectionService itself.
  • Do NOT inject a single long-lived CollectionService into NodeServiceImpl — its 'a lifetime borrows node_service, so a stored instance fights the borrow checker against the Arc<NodeService> field. Folding the ops into core is strictly cleaner than a stored borrow.

Scope guard for the 11 collection RPCs: if folding all of them into core meaningfully expands this PR, it is acceptable to land the create/update/delete delegation (which kills sites 109/203/212 and is the core of B3) in this issue and file a tight follow-up for the remaining 11 pure-collection RPCs. State clearly in the PR which sites were addressed. The create/update/delete delegation is the non-negotiable deliverable.

Out of scope (do NOT touch)

  • fetch_node (line 1332) and service_error_to_status (line 1472) — finding B6 (lossy error mapping), tracked separately. You may call fetch_node; do not modify it.
  • empty_to_none (line 1313) and the proto-presence question — that's finding B5, the sibling issue (Remove the empty_to_none sentinel in daemon NodeService — proto-presence audit (B5) #1242). See Coordination.
  • Any proto file changes. This issue is pure daemon-↔-core wiring; the wire contract is unchanged.

Coordination with #1242 (B5)

Both this issue and #1242 edit the bodies of create_node / update_node / move_node in packages/daemon/src/services/node_service.rs. They will collide if run blind. Land this issue (B3+B4) FIRST. Rationale: this issue deletes large blocks of those handlers (replacing inline logic with one-line node_ops calls), which removes several empty_to_none call sites outright (e.g. the inline lifecycle/collection blocks). #1242 then operates on the smaller, simplified handlers. If parallelizing, #1242 branches off this branch (not main) and merges after.

Acceptance criteria

  • create_node, update_node, delete_node delegate to nodespace_core::ops::node_ops::{create_node,update_node,delete_node} — no inline collection resolution, lifecycle defaulting, or version auto-fetch remains in the daemon.
  • The inline CollectionService::new sites at daemon lines 109, 203, 212 are gone.
  • Errors map through ops_error_to_status (consistent with the search RPC).
  • The stale comment at daemon lines 197–199 is verified and deleted (or the underlying core gap it describes is fixed in node_ops).
  • Wire contract unchanged: NodeResponse / DeleteNodeResponse fields are populated identically (verified by the parity test below).
  • (If in scope) the 11 remaining collection-RPC CollectionService::new sites are folded into core; otherwise a follow-up issue is filed and referenced.
  • No #[allow(dead_code)], no #[deprecated], no lint suppression. Delete dead helpers exposed by the refactor.
  • cargo test (core + daemon) and cargo clippy pass with no new warnings.

Testing

  • Parity test (the key one): add a daemon-level test asserting that creating/updating a node through the gRPC NodeServiceImpl handler yields the same persisted node and the same collection membership / lifecycle status as calling node_ops::create_node / node_ops::update_node directly on the core NodeService. This is the regression guard for the "agent path == daemon path" consistency win.
    • Create a node with a collection path + non-default lifecycle_status via the RPC; assert the node is in the resolved collection and has the lifecycle status.
    • Update a node without sending version; assert auto-fetch still works (no VersionConflict).
    • Update with add_to_collection then remove_from_collection; assert membership transitions.
  • Run cargo test -p nodespace-core -p nodespaced (or workspace cargo test).
  • Rust-only change; run bun run test once to confirm no incidental frontend breakage.

Standard NodeSpace startup / PR sequence

From the primary checkout: git status + git pull origin main, then EnterWorktree({name: "issue-<N>-thin-daemon-rpcs"}); inside the worktree bun install, capture the test baseline, bun run gh:assign <N> "@me", bun run gh:status <N> "In Progress". Before PR: cargo test + bun run test:all (no new failures vs baseline), bun run quality:fix (note: cargo fmt --all may touch unrelated files — git status and revert any you didn't intend), commit, bun run gh:pr <N>. Run /pragmatic-code-review before merge. Then ExitWorktree({action: "remove", discard_changes: true}) and gh pr merge <PR#> --squash --delete-branch.


Spun off from #1228 (architectural audit), findings B3 + B4.

Activity

  1. malibio commented on May 30, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 131 test files, 3924 tests passed

  2. self-assigned this
    on May 30, 2026
  3. malibio commented on May 30, 2026

    @malibio
    CollaboratorAuthor

    Code Review — Make daemon NodeService RPCs thin (B3 + B4)

    Branch: `worktree-issue-1241-thin-daemon-rpcs`
    Commit: e072e98
    Files changed: 4 (+493 / -148)

    Overall Assessment

    This is a clean, well-executed architectural fix. The daemon's three mutable RPCs now correctly delegate to the single source of truth in node_ops, eliminating the hand-maintained duplicate of collection-resolution, lifecycle-defaulting, and OCC version-fetch logic. The core fix to update_node for the empty-NodeUpdate rejection is correct and non-obvious — good that it was caught here. Test coverage is thorough (6 tests: 3 inline unit + 3 full-stack integration).

    The change is a net positive and should merge. One acceptance criterion gap needs resolution before merge.


    Findings

    [Improvement] Missing follow-up issue for B4's 11 remaining CollectionService::new sites

    The issue AC states: "otherwise a follow-up issue is filed and referenced."

    After this PR there are 12 CollectionService::new calls still in packages/daemon/src/services/node_service.rs (lines 884, 910, 936, 970, 986, 1000, 1016, 1030, 1058, 1086, 1129, plus the test at 1642). The 11 production sites were explicitly deferred as acceptable — but the AC requires a filed, referenced follow-up issue. The commit message mentions #1228 but does not cite a new follow-up. This is the only gap between the implementation and the stated acceptance criteria.

    Action required: File a follow-up issue for the 11 remaining collection-RPC CollectionService::new sites and reference it in the PR description or a comment on this issue.


    Correctness Findings (all verified correct)

    delete_node idempotency is preserved across both code paths:

    • When version=None (auto-fetch): node_ops::delete_node calls get_node → returns OpsError::NotFound if missing → daemon catches this and returns existed=false. Correct.
    • When version is provided and node is missing: core NodeService::delete_node checks existence first (line 1238–1246 of crud.rs) and returns Ok(DeleteResult{existed:false}) → ops returns Ok(DeleteNodeOutput{existed:false}) → daemon returns existed=false. Correct. The old early-return path is faithfully replicated.

    update_node empty-NodeUpdate fix is correct:
    NodeUpdate::is_empty() returns true only when all five fields (node_type, content, properties, title, lifecycle_status) are None. The fix skips the core update_node call in that case and falls through to collection operations. This correctly handles collection-only updates like the update_node_add_then_remove_collection_membership integration test (which sends content=None, node_type=""→None, properties=None, lifecycle_status=""→None).

    create_node double-fetch is intentional and consistent:
    node_ops::create_node is called for business logic; the daemon then calls fetch_node again to get the Node struct for node_to_proto. This matches the issue's explicitly endorsed "Re-fetch + node_to_proto" approach and keeps the wire shape byte-identical. Same pattern is used in update_node.

    Stale comment at daemon lines 197–199 ("would silently drop several fields") is gone:
    The entire update_node inline block was replaced. No stale comments remain.

    content field mapping is type-safe:
    UpdateNodeRequest.content is proto optional string → prost generates Option<String> → passes directly to UpdateNodeInput.content: Option<String> → NodeUpdate.content: Option<String>. Empty-string-to-clear semantics are preserved.


    Nitpicks

    Nit: packages/daemon/src/services/node_service.rs line 25 — NodeAccessor is imported but does not appear to be directly used in the daemon code (it's a trait that CollectionService::new's second parameter does not require). This is a pre-existing import, not introduced by this PR, so it's out of scope — but worth cleaning up in a future pass.

    Nit: The inline unit test update_node_rpc_collection_add_then_remove adds a content change to trigger a non-empty NodeUpdate, but adds a comment explaining why (// Add to collection via update (include a content change so NodeUpdate is non-empty)). After the is_empty() fix in node_ops, collection-only updates work without a content change — the comment and the forced content change are no longer needed. The integration test (update_node_add_then_remove_collection_membership) already uses content: None for both the add and remove operations, which is the correct pattern to exercise the new code path. The inline unit test is slightly misleading. Low priority.


    Acceptance Criteria Status

    • create_node, update_node, delete_node delegate to node_ops — no inline collection/lifecycle/version logic remains in daemon
    • Lines 109, 203, 212 CollectionService::new sites are gone
    • Errors map through ops_error_to_status
    • Stale comment at daemon lines 197–199 deleted
    • Wire contract unchanged (verified via 6 parity tests)
    • Follow-up issue filed for the 11 remaining collection-RPC CollectionService::new sites (gap)
    • No #[allow(dead_code)], no deprecations, no lint suppression
    • 3 inline unit tests + 3 integration tests added
  4. added a commit that references this issue on Jun 22, 2026
    5737c1d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions