Skip to content

ADR-053 daemon multi-database: registry scaffold + build_services split (#1532) - #1572

Merged
mstomar125 merged 2 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-daemon-db-manager-scaffold
Jul 9, 2026
Merged

mstomar125 merged 2 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-daemon-db-manager-scaffold

Conversation

@mstomar125

@mstomar125 mstomar125 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Foundation for ADR-053 (One Daemon, Multiple Local Databases). Two incremental, low-risk stages of #1532; the multi-database routing that consumes them lands next.

Stage 1–2 — proto + registry (dormant scaffold)

  • New packages/proto/proto/database_service.proto: DatabaseService { List, Create(name, path?), Register(path), Remove (unregister-only, never deletes files), SetDefault, Rename } + a DatabaseStatus enum (Open/Closed/Missing). Wired into build.rs and re-exported from packages/proto/src/lib.rs.
  • New packages/daemon/src/services/database_manager.rs: DatabaseId (ULID) + DatabaseEntry + a Registry persisted to a dedicated ~/.nodespace/databases.toml (kept separate from SettingsService's daemon.toml), and a DatabaseManager holding the registry plus an open-databases map. Registry mutations (create/register/remove/set_default/rename) are implemented and persist; get_or_open returns a clear "not yet wired" error (no todo!()), since the per-database service set it hands back is assembled in Stage 3+.

The scaffold compiles and is not yet wired into service assembly or routing — intentional, to keep the sync lock-step green until Stage 5.

Stage 3 — split build_services() into shared + per-database

The seam the routing needs. build_services() becomes:

  • build_shared_services() → process-global (PtySessionManager, daemon settings) plus the embedding model loaded once for the whole process and published over a tokio::watch channel.
  • build_database_services(db_path, &shared) → per-database SqliteStore, NodeService (+seeding), gRPC handlers, GraphContextAssembler, import, local-agent watcher, and per-database embedding state — consuming the shared PTY manager rather than making its own.
  • The embedding model is decoupled from stores (ADR-053: one model backs all databases): the old per-store load task splits into load_shared_embedding_model_bg (loads the raw model once, publishes over watch) and wire_database_embeddings_bg (each database awaits the shared model, then wires its own NodeEmbeddingService + EmbeddingProcessor + waker).
  • All four serve loops (headless/tray × unix/windows) call build_shared_services then build_database_services; settings now comes from the shared set.

Behavior-preserving for the single default database served today.

Verification

  • cargo build/fmt/clippy -p nodespace-daemon --all-targets -- -D warnings clean.
  • cargo test -p nodespace-daemon 71/71 — including grpc_round_trip and agent_session end-to-end suites that exercise the assembled services.
  • Rebased on current main.

Not in this PR (follow-on, tracked under #1532)

  • Hoist the chat CompositeModelManager to shared (it's built inside LocalAgentServiceImpl::new, per-database — needs a constructor change; behaviorally identical for one database).
  • Stage 4: x-ns-database-id interceptor + storing DatabaseServices in DatabaseManager.open.
  • Stage 5: DatabaseService handler + DatabaseServiceServer on BaseServices (needs the nodespace-sync lock-step). Stages 6–7: database_id on event envelopes; drop active_database_path/NODESPACED_DB_PATH + Windows pipe parity.

Part of #1532.

Mayank Tomar and others added 2 commits July 9, 2026 10:07
Foundation scaffold for the daemon-side of ADR-053 ("One Daemon, Multiple
Local Databases"). Adds the DatabaseService gRPC surface and the database
registry/manager types without touching service assembly, routing, or the
Pro daemon lock-step — those land in later stages.

## Completed in This Session
- [x] Stage 1 (proto): new packages/proto/proto/database_service.proto with
      DatabaseService { List, Create(name, path?), Register(path), Remove
      (unregister-only, never deletes files), SetDefault, Rename } and a
      DatabaseStatus enum (Open/Closed/Missing) surfaced in List/DatabaseInfo.
      Added to the compile list in build.rs and re-exported the generated
      client/server + messages from packages/proto/src/lib.rs, mirroring the
      SettingsService re-exports. node_service.proto / settings_service.proto
      untouched.
- [x] Stage 2 (registry + manager types): new
      packages/daemon/src/services/database_manager.rs with a DatabaseId ULID
      newtype, serde DatabaseEntry{id,name,path,created_at,last_opened_at}, a
      Registry{databases, default_database} that loads/saves a dedicated
      ~/.nodespace/databases.toml (kept separate from SettingsService's
      daemon.toml so the [capture] section is never clobbered), and a
      DatabaseManager { registry: RwLock<Registry>, open: RwLock<HashMap<
      DatabaseId, ()>> }. Method stubs list/create/register/remove/set_default/
      rename mutate and persist the registry; get_or_open returns a clear
      "not yet wired" anyhow error (no todo!()/unimplemented!()). Registered in
      services/mod.rs.

## Remaining Work
- [ ] Stage 3: split build_services() into build_shared_services()
      (process-global: embedding model, chat CompositeModelManager,
      PtySessionManager, settings, tray) and build_database_services(db_path,
      shared) (per-database: SqliteStore, NodeService + seeding,
      NodeEmbeddingService, EmbeddingProcessor, agent watcher,
      GraphContextAssembler, import handler). Coordinate with the god-object
      split so the refactor is not done twice.
- [ ] Stage 4: tonic interceptor reading x-ns-database-id metadata, resolving
      via DatabaseManager::get_or_open (lazy open), injecting the per-database
      service set as a request extension. Absent header routes to the default
      database so existing single-database clients keep working.
- [ ] Stage 5: implement the DatabaseService gRPC handler over DatabaseManager
      and add DatabaseServiceServer to BaseServices in router.rs. This extends
      ADR-043's compile-time completeness to the Pro daemon, so land it in
      lock-step with nodespace-sync's nodespaced-pro.
- [ ] Stage 6: add database_id to every server-streamed event envelope and make
      the streams filterable per database.
- [ ] Stage 7: greenfield deletions — drop active_database_path from
      DaemonConfig and its UpdateDaemonConfig handling; delete the
      NODESPACED_DB_PATH injection from the plist/systemd/Windows writers in
      daemon_setup.rs (keep the env var only as a test override mapping to a
      synthetic single-entry registry); give the Windows Named Pipe path the
      same routing coverage as the UDS path.

## Current State
- Files added: packages/proto/proto/database_service.proto,
  packages/daemon/src/services/database_manager.rs
- Files modified: packages/proto/build.rs, packages/proto/src/lib.rs,
  packages/daemon/src/services/mod.rs, packages/daemon/Cargo.toml (ulid dep),
  Cargo.lock
- Build: cargo build -p nodespace-proto -p nodespace-daemon — clean
- Lint: cargo clippy -p nodespace-daemon --all-targets -- -D warnings — clean
- Format: cargo fmt --all --check — clean
- Known issues: none. The scaffold compiles and is not yet wired into main.rs
  service assembly, the router, or the interceptor — intentionally, to keep
  compilation and the sync lock-step green.
- Dependencies: added ulid = "1" for ULID DatabaseId generation.

## Context for Next Session
The registry/manager and proto surface are the low-risk foundation of ADR-053.
The manager persists to its own databases.toml and never touches daemon.toml.
get_or_open is the seam for the per-database service split (Stage 3) and the
routing interceptor (Stage 4); wiring DatabaseServiceServer into BaseServices
(Stage 5) is the point that requires a coordinated nodespace-sync change.

## Acceptance Criteria Status
- [ ] Two databases served concurrently by one daemon (Stages 3-5)
- [ ] Header-less requests route to the default database (Stage 4)
- [ ] DatabaseService RPCs work end-to-end (Stage 5; proto + manager scaffolded)
- [ ] Event streams carry database_id (Stage 6)
- [ ] active_database_path and the plist NODESPACED_DB_PATH injection removed
      (Stage 7)
- [ ] Named Pipe path gets the same routing coverage as UDS (Stage 7)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Splits the daemon's single build_services() into build_shared_services()
(process-global) and build_database_services(db_path, &shared) (per-database),
the seam the multi-database routing needs. Behavior-preserving for the single
default database served today.

## Completed in This Session
- [x] SharedServices { pty_manager, settings, model, has_model } +
      build_shared_services(): PTY manager and daemon settings are now
      process-global, and the embedding model is loaded ONCE for the whole
      process and published over a tokio watch channel.
- [x] DatabaseServices + build_database_services(db_path, &shared): per-database
      SqliteStore, NodeService (+ seeding), gRPC handlers, GraphContextAssembler,
      import, local-agent event watcher, and the per-database embedding state.
      Consumes the shared PtySessionManager instead of constructing its own.
- [x] Embedding model decoupled from stores (ADR-053 "one model backs all
      databases"): load_embedding_model_bg split into
      load_shared_embedding_model_bg (loads the raw model once, publishes over
      watch) and wire_database_embeddings_bg (awaits the shared model, then wires
      that database's NodeEmbeddingService + EmbeddingProcessor and the waker).
- [x] All four serve loops (headless/tray x unix/windows) call
      build_shared_services then build_database_services; settings now comes from
      the shared set. cargo fmt/clippy (-D warnings) clean; daemon tests 71/71
      (incl. grpc_round_trip + agent_session end-to-end).

## Remaining Work
- [ ] Hoist the chat CompositeModelManager to shared: it is currently built
      inside LocalAgentServiceImpl::new (per-database), not in build_services,
      so sharing it needs a LocalAgentServiceImpl constructor change — deferred
      to keep this a focused split. Per-database is behaviorally identical for
      the single database served today.
- [ ] Stage 4: tonic interceptor reading x-ns-database-id, resolving via
      DatabaseManager::get_or_open (store the DatabaseServices in the manager's
      open-map, replacing the () placeholder), injecting the per-database set as
      a request extension; absent header routes to the default database.
- [ ] Stage 5: DatabaseService gRPC handler + DatabaseServiceServer on
      BaseServices (needs the nodespace-sync lock-step).
- [ ] Stage 6: database_id on event envelopes. Stage 7: drop active_database_path
      / NODESPACED_DB_PATH; Windows Named Pipe routing parity.

## Current State
- Files modified: packages/daemon/src/main.rs (+139/-58).
- Build/tests: cargo build -p nodespace-daemon clean; fmt + clippy -D warnings
  clean; cargo test -p nodespace-daemon 71/71 pass.
- Known issues: none. The split is behavior-preserving for one database; the
  DatabaseManager open-map still holds () (wired in Stage 4).

## Context for Next Session
build_shared_services / build_database_services are the seam Stage 4 routes
through. The shared model handoff uses a watch::Receiver<Option<Arc<EmbeddingService>>>
so each database's wiring task awaits the one model. Next: store DatabaseServices
in DatabaseManager.open and add the x-ns-database-id interceptor.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mstomar125
mstomar125 marked this pull request as ready for review July 9, 2026 08:24
@mstomar125 mstomar125 changed the title WIP: ADR-053 daemon database manager — proto + registry scaffold (part of #1532) ADR-053 daemon multi-database: registry scaffold + build_services split (#1532) Jul 9, 2026
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE

Reviewed the full diff at b2a434f. This is well-staged foundational work — a genuinely dormant scaffold plus a behavior-preserving refactor, with the cross-repo-coupled parts correctly deferred.

Stage 1–2 scaffold — dormant + data-safe:

  • DatabaseManager/Registry are referenced only in database_manager.rs and the services/mod.rs re-export — never wired into main.rs's serve path, so this can't change current runtime behavior. Good.
  • remove() is unregister-only — it retains the registry, saves, clears default_database if it pointed at the removed id, and drops the open-map entry; there is no fs::remove_file, so no database file is ever deleted. It also releases the registry write lock (block scope) before taking the open-map lock — no two-lock overlap.
  • get_or_open() returns clear anyhow errors (registered-but-not-wired / not-registered) — no todo!()/panic, so a premature call fails gracefully.
  • Registry persists to a dedicated ~/.nodespace/databases.toml, deliberately separate from daemon.toml, so the two writers can't clobber each other. Load treats NotFound as an empty default.

Stage 3 build_services split — behavior-preserving:

  • The embedding-model decoupling is correct: build_shared_services loads the model once and publishes over a tokio::watch; wire_database_embeddings_bg consumes it with the canonical pattern — loop { if let Some = borrow_and_update() → break; if changed().await.is_err() → return }. watch retains the latest value, so there's no missed-update race even if the model is published before a database wires, and the task exits cleanly on sender-drop (no model file) rather than leaking a forever-await.
  • All four serve loops (headless/tray × unix/windows) call build_shared_services then build_database_services(&db_path, &shared), consuming the shared PTY manager — for the single default database served today this is equivalent to the old assembly.

Staging discipline (healthy): Stage 5 (the DatabaseService handler + server that needs the nodespace-sync lock-step) and the x-ns-database-id routing are explicitly not here — so nothing half-wired lands, and there's no cross-repo deploy-order trap yet. The deferred CompositeModelManager hoist is documented as behaviorally identical for one database.

CI green — test:all + test:e2e, and the PR's 71/71 daemon suite includes grpc_round_trip + agent_session, which exercise the reassembled services end-to-end. No 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