Skip to content

ADR-053 Stage 4: DatabaseManager lazy open + service-assembly extraction - #1589

Merged
mstomar125 merged 3 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-stage4-db-routing
Jul 9, 2026
Merged

mstomar125 merged 3 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-stage4-db-routing

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

ADR-053 Stage 4 — DatabaseManager lazy open + service-assembly extraction

Part of the ADR-053 epic ("One Daemon, Multiple Local Databases", #1532). Builds on the Stage 1–3 scaffold (registry skeleton + build_shared_services/build_database_services split).

This stage makes the daemon's DatabaseManager a working component: it can register a default, resolve a request's routing header, and lazily open and cache a database's service set. It stays deliberately off the live request path — wiring per-request routing into the serve loops changes the cross-repo BaseServices/build_base_router contract (ADR-043 lock-step with nodespaced-pro) and lands in the following, sync-coordinated stage.

What changed

  • Hoist service assembly into the library (services/assembly.rs). Moves SharedServices, DatabaseServices, build_shared_services, build_database_services (and their private helpers) out of main.rs into a library module so the DatabaseManager can build per-database service sets. main.rs shrinks to boot/serve wiring only. Pure relocation — no behavior change.
  • Split shared services into a router-owned part and a build context. SharedServices { settings, context }, where the cloneable SharedContext { pty_manager, model, has_model } carries exactly the process-global inputs a per-database build needs. build_database_services now takes &SharedContext.
  • DatabaseManager routing resolution. ensure_default_registered(name, path) (idempotent first-boot default registration) and resolve_database_id(header) (x-ns-database-id → id; absent → default; unknown → error).
  • DatabaseManager lazy open + cache. get_or_open(id) resolves the registry entry's path, assembles its DatabaseServices from the SharedContext outside the open lock, then caches and returns a shared Arc<DatabaseServices> (double-checked so concurrent first-opens of the same id converge on one handle). Replaces the prior "not yet wired" placeholder.

Behavior

Single-default-database behavior is unchanged — the serve loops still build the default database directly. Nothing here is on the live request path yet, so community and Pro runtime behavior is identical to before.

Tests

cargo test -p nodespace-daemon green: daemon lib 46 passed (adds a get_or_open build-and-cache test proving first-open assembles + reports Open and a second open returns the same cached Arc, and that an unregistered id errors), plus the existing resolution and integration suites (main / grpc_round_trip / agent_session / import). cargo fmt --check and cargo clippy --all-targets -- -D warnings clean.

Mayank Tomar and others added 3 commits July 9, 2026 10:51
First increment of the x-ns-database-id routing (ADR-053 §3): the resolution
core the tonic interceptor and get_or_open will build on.

## Completed in This Session
- [x] DatabaseManager::ensure_default_registered(name, path): first boot with an
      empty registry registers the default database and marks it default so
      header-less requests always have a route. Idempotent — returns the existing
      default untouched, adopts the first entry when the registry has databases
      but no default, and never re-adds the path or overrides an existing default.
- [x] DatabaseManager::resolve_database_id(header): an explicit x-ns-database-id
      header selects a registered database; an absent header routes to the
      default (so single-database clients keep working); an unregistered id or a
      missing default is an error rather than a silent fallback.
- [x] Unit tests for empty-registry registration + idempotency, header/default
      routing, second-database routing, unknown-id error, and no-default error.
      cargo fmt/clippy(-D warnings) clean; daemon lib tests 45/45.

## Remaining Work (Stage 4)
- [ ] Tonic interceptor: read x-ns-database-id metadata, call resolve_database_id,
      inject the resolved DatabaseId (then the per-database service set) as a
      request extension; absent header routes to the default.
- [ ] Wire get_or_open to build+cache the per-database service set: store
      DatabaseServices in the open-map (replacing the () placeholder). This needs
      build_database_services reachable from the manager — hoist the service
      assembly (SharedServices/DatabaseServices/build_*) from main.rs into the lib.
- [ ] Handlers resolve their per-database services from the request extension.

## Current State
- Files modified: packages/daemon/src/services/database_manager.rs (+ methods
  and a tests module).
- Build/tests: cargo build/fmt/clippy -D warnings clean; daemon lib 45/45.
- Known issues: none. The open-map still holds () and get_or_open still returns
  "not yet wired" — the caching lands with the service-assembly hoist above.

## Context for Next Session
resolve_database_id is the routing key. Next: hoist SharedServices/
DatabaseServices/build_shared_services/build_database_services from main.rs into
the daemon lib so DatabaseManager can build and cache DatabaseServices in its
open-map, then add the interceptor that injects the resolved set.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Moves SharedServices, DatabaseServices, build_shared_services,
build_database_services (and the seed_agent_nodes / resolve_model_path /
load_shared_embedding_model_bg / wire_database_embeddings_bg helpers) out of the
`nodespaced` binary and into a new `services::assembly` library module, so the
DatabaseManager can build and cache per-database service sets in a later
increment. Pure relocation — no behavior change.

## Completed in This Session
- [x] New packages/daemon/src/services/assembly.rs with the structs (fields now
      `pub`) + build functions, re-exported from services/mod.rs and lib.rs.
- [x] main.rs calls `nodespace_daemon::build_shared_services` /
      `build_database_services` and drops the now-unused imports; `drain_gpu`
      and the serve loops are otherwise unchanged.
- [x] cargo fmt/clippy(-D warnings) clean; daemon tests 74/74 (lib 45 + main 1 +
      grpc_round_trip 16 + agent_session 9 + import 3) — the reassembled services
      still pass the end-to-end suites.

## Remaining Work (Stage 4)
- [ ] Give DatabaseManager a shared build-context (pty_manager + model watch +
      has_model; settings stays router-level) and change build_database_services
      to take it; wire get_or_open to build+cache Arc<DatabaseServices> in the
      open-map (replace the () placeholder); ensure_default_registered on boot.
- [ ] Tonic interceptor: read x-ns-database-id, resolve_database_id, inject the
      resolved Arc<DatabaseServices> as a request extension; header-less ->
      default. Handlers read their per-database services from the extension.

## Current State
- Files: new services/assembly.rs; edits to services/mod.rs, lib.rs, main.rs.
- Build/tests: cargo build/fmt/clippy -D warnings clean; daemon 74/74.
- Known issues: none. DatabaseManager.open still holds (); get_or_open still
  returns "not yet wired" — next increment.

## Context for Next Session
The assembly now lives in the lib. Next: split SharedServices into a
router-owned `settings` and a cloneable build-context, hand the context to
DatabaseManager so get_or_open can call build_database_services and cache the
result, then add the x-ns-database-id interceptor.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Completed in This Session (increment 4b(b))
- [x] Split SharedServices into a router-owned `settings` plus a cloneable
      `SharedContext { pty_manager, model, has_model }`; build_shared_services
      returns SharedServices { settings, context }.
- [x] build_database_services now takes `&SharedContext` (the shared build
      inputs) rather than the whole SharedServices.
- [x] DatabaseManager holds the SharedContext and an
      `open: HashMap<DatabaseId, Arc<DatabaseServices>>`; get_or_open resolves
      the registry path, assembles DatabaseServices from the context outside the
      open lock, then caches and returns the shared handle (double-checked so
      concurrent first-opens converge on one handle). Retired the placeholder
      unit map and the "not yet wired" error.
- [x] Serve loops pass `&shared.context`; single-default-DB behavior unchanged.

## Remaining Work
- [ ] 4c: tonic interceptor reads `x-ns-database-id`, calls resolve_database_id,
      routes through get_or_open, injects the Arc<DatabaseServices> as a request
      extension; header-less routes to the default. Then open the Stage-4 PR.
- [ ] Stage 5 (DatabaseService handler) — needs nodespace-sync lock-step; do not
      start without checking in.

## Current State
- Files: daemon assembly.rs, database_manager.rs, services/mod.rs, lib.rs, main.rs
- Tests: cargo test -p nodespace-daemon green (lib 46, +get_or_open build/cache
  test); cargo fmt + clippy --all-targets -D warnings clean.
- DatabaseManager is exercised by unit tests only; not yet on the live request
  path (that lands in 4c).

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

Copy link
Copy Markdown
Contributor Author

Stage-4 boundary note: this PR delivers the DatabaseManager foundation (register-default / resolve-header / lazy-open-and-cache) and hoists service assembly into the daemon library. It is intentionally not on the live request path — wiring per-request routing into the serve loops changes the cross-repo BaseServices / build_base_router contract (ADR-043 lock-step with nodespaced-pro), so that lands in the next, sync-coordinated stage.

@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE

Reviewed the full diff at 409bd19. Stage 4 correctly activates the #1572 scaffold while staying off the live path.

get_or_open — concurrency is right. Fast-path reads the open map; on a miss it resolves the path (read lock), then assembles DatabaseServices outside the open lock so opening database A never serializes behind B, then takes the write lock and double-checks — if a concurrent caller inserted first, it returns theirs and drops its own set, so every request converges on one shared Arc. This is the correct standard pattern, and the new test asserts exactly it (first open builds + Open, second returns the same cached Arc, unregistered id errors).

resolve_database_id fails closed. An x-ns-database-id naming an unregistered database → Err (never a silent fall-through to the default, which would be a cross-database leak); absent header → the default, so single-database clients keep working. ensure_default_registered uses proper double-checked locking (read fast-path → write-lock re-check → adopt-first-or-register) and is idempotent — no duplicate default.

Dormant + behavior-preserving. The serve loops still build the default database directly; resolve_database_id/get_or_open aren't wired into request handling yet, and the BaseServices/build_base_router change + x-ns-database-id interception (ADR-043 sync lock-step) are explicitly deferred to the next stage — so nothing half-wired or cross-repo-coupled lands here. The SharedServices → { settings, SharedContext { pty_manager, model, has_model } } split is a mechanical threading refactor; the 46/46 daemon suite (incl. grpc_round_trip/agent_session/import, which exercise the assembled services end-to-end) plus green test:all/test:e2e corroborate the assembly move preserved behavior.

One thing to watch when this goes live (not a change request now, since it's dormant): two concurrent first-opens of the same id will each run build_database_services before the double-check discards one — i.e. two SqliteStore opens + idempotent schema seeds on the same file momentarily. Benign in-process (multiple SQLite connections, IF NOT EXISTS seeding), but if the open path ever takes an exclusive lock or runs a non-concurrency-safe migration, a per-id "loading" guard would avoid the transient. Fine as-is for Stage 4.

@mstomar125
mstomar125 merged commit f07a6fc into NodeSpaceAI:main Jul 9, 2026
2 checks passed
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