Skip to content

ADR-053 Stage 5 (part 1): per-request database routing — middleware + NodeService - #1590

Merged
mstomar125 merged 2 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-stage5-request-routing
Jul 9, 2026
Merged

mstomar125 merged 2 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-stage5-request-routing

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

ADR-053 Stage 5 (part 1) — per-request database routing: middleware + NodeService

Part of the ADR-053 epic ("One Daemon, Multiple Local Databases", #1532). Builds on Stage 4's DatabaseManager (register-default / resolve-header / lazy-open-and-cache). This stage puts the manager on the live request path and routes the primary data-plane service (NodeService) per request.

Design — core-only, BaseServices untouched

A request carries its target database in an x-ns-database-id metadata header (absent → the default database, so single-database clients are unchanged). Rather than change what's registered on the router (which would touch the cross-repo BaseServices / build_base_router contract that nodespaced-pro also builds, per ADR-043), routing is done inside the handlers:

  • DbManagerLayer (db_routing.rs) — a thin synchronous tower layer that injects the process-global Arc<DatabaseManager> into each request's extensions. It is installed only by the community/core serve loops. The Pro daemon does not install it, so its handlers find no manager and fall back to the default database — behavior identical to before, and no coordinated nodespace-sync change is required.
  • NodeServiceImpl::route(&request) — reads the injected manager, resolves the header (absent → default; unregistered → rejected, never silently served from the default), and returns that database's cached NodeServiceImpl. With no manager present it returns self.
  • Every NodeService handler now resolves its target database via route and operates on that database's node service (and embedding state for search). chat (Unimplemented) is untouched.

The default database is now opened through the manager at boot (open_default_database) and its per-database impls are cloned into BaseServices, so the same cached service set backs both header-less requests and requests naming the default id — the file is never opened twice. The five per-database impls gained #[derive(Clone)] (all hold only Arc/PathBuf) to make that cloning cheap.

Behavior

Unchanged for existing (single-database) clients and for the Pro daemon. No impl constructor, BaseServices field, or build_base_router signature changed.

Tests

cargo test -p nodespace-daemon green: daemon lib 47 including routes_requests_by_database_header — a node created against a second database lands there and is invisible to the default (routing isolates databases), an absent header routes to the default, and an unregistered id is rejected (NotFound). The existing 26 NodeService handler tests pass unchanged (they construct the impl with no manager → route returns self), corroborating that the transform preserved behavior. cargo fmt --check and cargo clippy --all-targets -- -D warnings clean.

Follow-up (next in this epic)

Apply the same route pattern to the other per-database services — import, embeddings, agent_session, local_agent. Settings is process-global and stays un-routed. (agent_session's PtySessionManager is process-global; only its per-database assembler/node-service follow the target database.) Landing NodeService first gets the routing pattern reviewed before it is replicated.

Mayank Tomar and others added 2 commits July 9, 2026 12:58
…ive path

## Completed in This Session (increment 5a)
- [x] `DbManagerLayer` (packages/daemon/src/db_routing.rs): a sync tower layer
      that injects the process-global `Arc<DatabaseManager>` into every request's
      extensions so per-database handlers can resolve the `x-ns-database-id`
      routing header. Installed only by the community/core serve loops; the Pro
      daemon does not install it, so its handlers find no manager and fall back
      to the default database — behavior identical to before.
- [x] Serve loops now open the default database *through* the manager
      (`open_default_database`): register the default, `get_or_open` it once, and
      clone the per-database impls into `BaseServices` from the cached
      `Arc<DatabaseServices>`. The same cached set backs both header-less requests
      and requests naming the default id — the file is never opened twice.
- [x] Made the five per-database service impls `Clone` (all hold only `Arc`/
      `PathBuf`) so they can be cloned out of the cached set into `BaseServices`.

## Behavior
Unchanged: the layer only injects an Arc; handlers do not yet read it, so every
request still serves the default database. `BaseServices`/`build_base_router`/all
impl constructors are untouched, so `nodespaced-pro` is unaffected (no cross-repo
change).

## Remaining Work
- [ ] 5b: wire the NodeService handlers to read the manager from the request
      extension, resolve `x-ns-database-id`, and delegate to the target database's
      service (fall back to `self` when no manager present). Integration test:
      two registered databases, route a request between them by header.
- [ ] 5c+: the other per-database services (agent_session, import, local_agent,
      embeddings). Settings is process-global and stays un-routed.

## Current State
- Files: db_routing.rs (new), lib.rs, main.rs, {node,agent_session,import,embeddings}_service.rs
- Tests: cargo test -p nodespace-daemon green (lib 46, grpc_round_trip 16,
  agent_session 9, import 3); cargo fmt + clippy --all-targets -D warnings clean.
- Windows serve loops converted symmetrically (unsupported target, not compiled
  on this host).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Completed in This Session (increment 5b)
- [x] `NodeServiceImpl::route(&request)`: reads the `DatabaseManager` injected by
      the routing layer, resolves the `x-ns-database-id` header (absent → default;
      unregistered → rejected), and returns that database's `NodeServiceImpl`.
      When no manager is present (Pro daemon, unit tests), returns `self` — so
      behavior is unchanged there.
- [x] Every NodeService handler now resolves its target database via `route` and
      operates on that database's node service (and embedding state for search),
      instead of the fixed `self`. `chat` is untouched (returns Unimplemented).
- [x] Test `routes_requests_by_database_header`: a node created against a second
      database lands there and is invisible to the default; an absent header
      routes to the default; an unregistered id is rejected (NotFound), never
      silently served from the default.

## Behavior
No manager present → `route` returns `self`, so the existing 26 NodeService
handler tests pass unchanged. `BaseServices`/`build_base_router`/all constructors
remain untouched — no cross-repo change; `nodespaced-pro` is unaffected.

## Remaining Work
- [ ] Apply the same routing to the other per-database services: import,
      embeddings, agent_session, local_agent. (Settings is process-global — not
      routed.) Note: agent_session's PtySessionManager is process-global; only its
      per-database assembler/node-service should follow the target database.

## Current State
- File: packages/daemon/src/services/node_service.rs
- Tests: cargo test -p nodespace-daemon green (lib 47, incl the routing test);
  cargo fmt + clippy --all-targets -D warnings clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE (code); merge gate below.

Reviewed the full diff at aebd16c. This is a well-staged live-path change that deliberately — and correctly — avoids the cross-repo lock-step.

The cross-repo contract stays untouched (the key design win). DbManagerLayer is composed onto Server::builder() before it's handed to build_base_router(...), so build_base_router's signature and the BaseServices shape are unchanged — the very contract nodespaced-pro also builds (ADR-043). The Pro daemon simply doesn't install the layer, so its handlers hit route()'s let Some(manager) = … else { return Ok(self.clone()) } fallback and operate on the default database exactly as before. No coordinated nodespace-sync change is required — which is the concern I'd flagged for Stage 5, resolved by construction.

route() is fail-safe. No injected manager → self (Pro + single-DB unchanged); non-ASCII header → invalid_argument; resolve_database_id error (unregistered id, or absent with no default) → not_found — never a silent fall-through to the default, so a request can't be misrouted into the wrong database.

Boot wiring is right. Every community serve loop (headless/tray × unix/windows) calls open_default_database(&db_path, shared.context.clone()) — the default opens through the manager and its per-database impls are cloned into BaseServices, so header-less requests and requests naming the default id share one cached handle and the file is never opened twice. The five per-database impls get a cheap #[derive(Clone)] (Arc/PathBuf only).

Behavior preservation is evidenced, not just claimed: the 26 existing NodeService handler tests pass unchanged (constructed with no manager → route returns self), and the new routes_requests_by_database_header proves a node written to a second database is invisible to the default (isolation), absent header → default, unregistered id → NotFound.

Partial routing is safe today. Only NodeService routes; import/embeddings/agent_session are deferred. That can't cause a live cross-service inconsistency because there's no reachable path to register a second database yet (the DatabaseService server is still unwired), so production always resolves to the single default — the routing is exercised only in tests. Landing NodeService first to review the pattern is the right call.

Merge gate: test:all / test:e2e are IN_PROGRESS — hold the merge until both are green (this is a live-request-path change). No code changes requested.

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.

1 participant