From 6277261df1562fd31164c7a4497ef4037d50e8e6 Mon Sep 17 00:00:00 2001 From: Stefan Steiner Date: Tue, 24 Nov 2026 23:06:22 -0800 Subject: [PATCH 1/4] docs(daemon): design and plan for hyperdb-daemon extraction Design spec and implementation plan for moving the shared-hyperd daemon out of hyperdb-mcp into a hyperdb-daemon crate, in phases: measure, engine and control-channel hardening, internal crate move, and a later public acquire() API. The shared engine runs on TCP loopback with a generated SCRAM password and a strict-SCRAM client. --- .../2026-11-24-hyperdb-daemon-extraction.md | 467 ++++++++++++++++++ ...-11-24-hyperdb-daemon-extraction-design.md | 387 +++++++++++++++ 2 files changed, 854 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md create mode 100644 docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md diff --git a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md new file mode 100644 index 00000000..7ae9f183 --- /dev/null +++ b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md @@ -0,0 +1,467 @@ +# `hyperdb-daemon` extraction — implementation plan + +**Design:** [`../specs/2026-11-24-hyperdb-daemon-extraction-design.md`](../specs/2026-11-24-hyperdb-daemon-extraction-design.md) +**Status:** Not started. Phases 0, S and A are fully specified. Phase B is an +outline only and needs a spec revision first. + +This plan is written for implementation agents, one task per dispatch, with an +independent reviewer between phases. Read the design first; decision numbers +(D1–D9) below refer to it. + +## How to run this plan + +- **One task per engineer dispatch.** Each task lists its files, its steps and + its acceptance check. Do not start the next task until the current one's + check passes with real, captured output. +- **Review at each phase boundary,** by a reviewer who did not write the code. + The phase is done when the reviewer reports no Critical or Important findings. +- **Phase order:** 0 and S are independent and can run in parallel. A can start + any time. B starts only after the maintainer's go decision (design, "Open + decisions"). +- **One PR per phase** from the maintainer's fork to `tableau/hyper-api-rust`. + Commit subjects follow Conventional Commits; see per-phase guidance below. + +## Rules that apply to every task + +These come from `AGENTS.md` and are restated because each has caused a real +failure in this repository. + +1. **Set an absolute `HYPERD_PATH`** for every cargo test run: + `export HYPERD_PATH="$PWD/.hyperd/current"` from the workspace root. The + daemon tests re-exec children with a relocated working directory, and an + unset or relative value makes them fail. +2. **Never claim a pass without output.** Check exit codes. If a command prints + nothing for about 30 seconds, report it as hanging. +3. **Never invent `hyperd` flags or parameters.** Use only what `run.rs` + already sets, plus the ones design D6 verified against the pinned binary: + the `config` and `strict_settings_mode` parameters and the + `authorized_users` setting inside the config file. Nothing else. +4. **No narrowing integer `as` casts.** Use `TryFrom` (AGENTS.md reminder 7). +5. **Never hand-edit a crate version** or the root `CHANGELOG.md`. Per-crate + changelogs are hand-maintained; append to the existing `## [Unreleased]` + subsection rather than adding a duplicate heading. +6. **Wire compatibility is a hard requirement for Phases S and A.** The PONG + reply, `daemon.json` keys, `STATUS` JSON, and file locations must stay + byte-for-byte compatible except where a task says otherwise. + +## The gate + +Run from the workspace root. Every task ends with the subset its acceptance +check names; every phase ends with all of it. + +```bash +export HYPERD_PATH="$PWD/.hyperd/current" +.hyperd/current/hyperd --version # must match hyperdb-bootstrap/hyperd-version.toml +cargo fmt --all --check +cargo clippy --workspace --all-targets --all-features -- -D warnings +cargo test --workspace --exclude hyperdb-api-node +RUSTDOCFLAGS="-D warnings" cargo doc --no-deps -p hyperdb-mcp # plus -p hyperdb-daemon once it exists +npx markdownlint-cli2 +``` + +On macOS, also run Windows-target clippy before pushing, because `control.rs` +and `state_perms.rs` have Windows-only code that only CI otherwise compiles: + +```bash +cargo clippy --target x86_64-pc-windows-msvc -p hyperdb-mcp --all-targets --keep-going -- -D warnings +``` + +This needs the stubbed `cc`/`ar`/`nasm` setup for `ring`; if it is not +available, say so in the report rather than skipping silently. + +--- + +## Phase 0 — Measure + +**Goal:** the numbers that decide whether Phase B is worth building. + +### Task 0.1 — `hyperd` startup and idle-memory measurement + +- **Add** `hyperdb-api/benches/hyperd_startup_cost.rs`, beside + `benchmark_suite.rs`, and register it in `hyperdb-api/Cargo.toml` the same + way `benchmark_suite` is registered, so it runs with `--example`. It runs N iterations + (default 30, from argv) of: `HyperProcess::new(None, None)`, connect, run + `SELECT 1`, drop. Report per-phase wall time (spawn-to-endpoint, connect, + first query, shutdown) as min, median and p95. Separately, start one + `hyperd`, wait 5 seconds idle, and report its resident memory: `ps -o rss=` + on Unix, and on Windows the working set via `tasklist` or skip with a note. + Also report the connect time against an engine that requires SCRAM (design + D6: build the config file as in Task S.4, or reuse its helper if S.4 has + landed) next to the password-less connect time, so the per-connection SCRAM + cost is known. +- **Run** it in release mode for both transports: + + ```bash + cargo run -p hyperdb-api --release --example hyperd_startup_cost -- 30 + BENCH_TRANSPORT=ipc cargo run -p hyperdb-api --release --example hyperd_startup_cost -- 30 + ``` + + `BENCH_TRANSPORT` is the existing switch parsed in + `hyperdb-api/benches/benchmark_suite.rs`; reuse its parsing rather than + adding a new variable. +- **Record** the results, host details and `hyperd --version` in a new section + of `docs/BENCHMARK_GUIDE.md`. +- **Acceptance:** the example compiles under the gate's clippy, the numbers are + pasted into the PR with the raw output, and markdownlint passes. +- **Commit:** `docs(bench): measure hyperd startup cost and idle memory`. + +--- + +## Phase S — Engine and control-channel hardening (no extraction needed) + +**Goal:** D5, D6 and D7. Ships in `hyperdb-mcp` (and, for S.3, in +`hyperdb-api-core` and `hyperdb-api`) today, and moves with the code in Phase A. + +**Order:** S.1 and S.3 are independent. S.4 needs S.3. S.2 goes last, because +it documents what S.4 built. Phase S can ship as two PRs: S.1 alone, then +S.3 + S.4 + S.2. + +### Task S.1 — Capability token for `STOP` and `REPORT_HYPERD_ERROR` + +- **Files:** `hyperdb-mcp/src/daemon/discovery.rs` (record field), + `health.rs` (command dispatch and client helpers), `run.rs` (token + generation at start), `spawn.rs` (takeover sends `STOP`), and callers in + `engine.rs`, `server.rs`, `main.rs`. +- **Steps:** + 1. Generate 32 random bytes per daemon start from the OS RNG. Check + `Cargo.lock` for a crate already in the tree (for example `getrandom`) + before adding a dependency, and prefer an existing one. Hex-encode it. + 2. Add an optional `control_token` field to `DaemonRecord`, written to + `daemon.json`. The file is already owner-only; keep it that way, and add + the field with `#[serde(default)]` so older records still parse. + 3. The command grammar becomes `STOP ` and + `REPORT_HYPERD_ERROR `. `PING`, `HEARTBEAT` and `STATUS` stay + unauthenticated. Compare tokens in constant time. + 4. A wrong or missing token gets a distinct error reply (for example + `ERR unauthorized`) and a `warn`-level log line that does **not** include + either token. + 5. Update every client call site to read the token from the discovery record + it already holds and send it. + 6. **Compatibility.** A newer client meeting an older daemon (record has no + `control_token`) sends the bare command, as today. An older client + meeting a newer daemon gets `ERR unauthorized` on `STOP`; the MCP's + takeover path then treats it like any failed takeover. Document this in + the `hyperdb-mcp` changelog. + 7. Never print the token in `STATUS`, the doctor output or any log. +- **Tests** (unit tests in the touched modules, plus `hyperdb-mcp/tests/daemon_tests.rs`): + `STOP` with the correct token stops the daemon; `STOP` with no token or a + wrong token is rejected and the daemon keeps running; same for + `REPORT_HYPERD_ERROR` (three wrong-token reports must **not** trip + `RESTART_LIMIT`); a record without the field parses; `STATUS` and the doctor + output contain no token. +- **Acceptance:** the full gate. +- **Commit:** `fix(mcp): require a per-daemon token for STOP and REPORT_HYPERD_ERROR`. + +### Task S.3 — Strict SCRAM mode in the client + +- **Files:** `hyperdb-api-core/src/client/config.rs` (new flag), + `connection.rs` and `async_connection.rs` (the authentication loops, around + the `Message::Authentication*` arms), and the builders in + `hyperdb-api/src/connection_builder.rs` and `async_connection_builder.rs`. + Check whether the pool's config (`hyperdb-api/src/pool*`) builds its own + connection config; if so, carry the flag through it too. +- **Steps:** + 1. Add a strict flag to the core `Config`, off by default. Provisional + builder method name: `require_scram_sha256(bool)` on both builders. + Choose the final name to match the builders' existing style, and give it + a `///` doc comment that explains what it rejects. + 2. When the flag is on, the authentication loop must: + - reject `AuthenticationCleartextPassword` and `AuthenticationMd5Password` + with an authentication error, **without** sending anything; + - reject `AuthenticationOk` unless a SASL final message has already been + verified by `scram_verify_server` in this connection; + - reject a SASL mechanism list without `SCRAM-SHA-256` (already the case); + - fail if the flag is on and no password was configured, before + connecting. + 3. Behaviour with the flag off is byte-for-byte unchanged. + 4. The error messages name the method the server asked for, and never + include the password. +- **Tests:** a tiny in-test fake server (a `std::net::TcpListener` on + `127.0.0.1:0` that reads the startup message and replies with one canned + authentication message) is enough. For each of `AuthenticationOk`, + cleartext and MD5, assert that strict mode fails, and that the fake server + received no password message. For cleartext, assert the password bytes never + arrive. Also test the happy path against a real `hyperd` started as in + Task S.4, sync and async. With the flag off, the existing auth tests still + pass unchanged. +- **Changelogs:** `### Added` bullets in `hyperdb-api/CHANGELOG.md` (the builder + methods) and `hyperdb-api-core/CHANGELOG.md`. +- **Acceptance:** the full gate. +- **Commit:** `feat(api): add a strict SCRAM-SHA-256 mode to the connection builders`. + +### Task S.4 — Shared engine on TCP with a generated password + +Design D5 and D6 hold the rationale and the probe results; read them first. + +- **Files:** `hyperdb-mcp/src/daemon/run.rs` (`build_params`, startup, the + supervisor's restart path), a new `hyperdb-mcp/src/daemon/engine_auth.rs` + (password, verifier, config file), `discovery.rs` (record field), + `state_perms.rs` (owner-only file creation, if a helper is missing), and the + code that connects to the engine: `hyperdb-mcp/src/engine.rs` and any + connection the daemon makes itself (health checks in `run.rs` or + `health.rs`). +- **Steps:** + 1. **Password and verifier.** Once per daemon start, generate 32 random + bytes from the OS RNG (reuse whatever S.1 chose) and encode them as + URL-safe text. Compute the PostgreSQL SCRAM-SHA-256 verifier + `SCRAM-SHA-256$4096:$:` with a + 16-byte random salt, reusing the PBKDF2 and HMAC dependencies + `hyperdb-api-core/src/client/auth.rs` already uses (`pbkdf2`, `hmac`, + `sha2`). Unit-test the verifier against a fixed salt and password, and + test that a real `hyperd` accepts it (see Tests). + 2. **Config file.** Write `/engine/hyperd-auth.json` with exactly + the JSON in design D6. Create it owner-only at creation time (Unix: + `OpenOptions::mode(0o600)` plus `create_new` after removing a stale + file; Windows: the existing owner-only helpers in `state_perms.rs`). + Write it before starting `hyperd`. + 3. **Engine parameters.** In `build_params`, replace + `TransportMode::Ipc` with `TransportMode::Tcp`, drop the + `domain_socket_directory` setup, set the listen mode **explicitly** to + PostgreSQL-protocol only (the `ListenMode` variant for libpq; do not rely + on `HyperProcess`'s default), and set `config` to the file path and + `strict_settings_mode` to `""` (it is a valueless flag; `HyperProcess` + emits `--strict-settings-mode` for an empty value). Leave the default + `--no-password` alone: `authorized_users` overrides it, and strict mode + plus step 4 cover the case where it does not. Strict mode applies to + **every** setting the daemon passes (`log_file_max_count`, + `log_file_size_limit` and the rest), not only the config file. The probe + only covered `HyperProcess`'s defaults plus `log_dir`, so confirm the + daemon's full parameter set starts under strict mode before relying on it. + 4. **Self-check.** After `hyperd` reports its endpoint and before + `daemon.json` is written, connect with **no** password. The connection + must fail with an authentication error. If it succeeds, stop `hyperd`, + log an `error`, and fail startup. Then connect with the password and + strict SCRAM on, and run `SELECT 1`. + 5. **Discovery record.** Add `engine_password` to `DaemonRecord` with + `#[serde(default)]`. Never print it in `STATUS`, the doctor, or any log. + The password stays the same for the daemon's lifetime, including + supervisor restarts of `hyperd`, so clients keep working across a + restart; the config file is reused as-is on restart. + 6. **Clients.** Every connection to the shared engine uses the record's + password with strict SCRAM on. A record with a TCP engine endpoint but no + `engine_password` is treated as unusable, never as "connect without a + password". A record from an older daemon (IPC endpoint, no password) + keeps working as today. + 7. **Mixed versions.** An older client meeting a newer daemon fails to + authenticate. Make sure that surfaces as a clear error (and, where the + MCP has a takeover path, that it behaves like any failed attach). Note it + in the `hyperdb-mcp` changelog. + 8. **Fallback, documented only.** In `engine_auth.rs`'s module docs, record + the environment-variable route from design D6 and what switching to it + takes. Do not implement it. +- **Tests** (`hyperdb-mcp/tests/daemon_tests.rs` and unit tests): + - The daemon's engine endpoint is TCP on `127.0.0.1`, and the engine has no + gRPC listener (`HyperProcess::grpc_endpoint()` is `None`). + - A unit test on `build_params` asserts the transport is TCP and the listen + mode is PostgreSQL-protocol only, so a later edit cannot quietly add IPC + or gRPC. + - A connection without a password and one with a wrong password are both + rejected; the record's password connects. + - **Pin-bump guard:** starting `hyperd` with a config file containing a + misspelt setting name (for example `authorized_userz`) and strict mode + fails startup. Name the test so the `update-hyperd-release` run makes it + obvious, for example `hyperd_auth_config_strict_mode_guard`. + - The self-check fails startup when the engine accepts a password-less + connection. Inject that through a test seam (for example a config file + with `"method": "trusted"`), not by changing production code paths. + - The config file and `daemon.json` are owner-only (Unix mode check; on + Windows, reuse whatever the existing permission tests check). + - The password is absent from `STATUS`, the doctor output, the daemon log, + and (Unix) `ps eww -p `. + - The password survives a supervisor restart of `hyperd`. +- **Also:** add a line to `.claude/skills/update-hyperd-release/SKILL.md` + saying that a failure of the auth-config guard test means `authorized_users` + changed, and pointing to design D6's fallback. +- **Acceptance:** the full gate, including Windows-target clippy. +- **Commit:** `fix(mcp): run the shared engine on TCP with a generated SCRAM password`. + +### Task S.2 — Document the engine trust model + +- **Files:** module docs in `hyperdb-mcp/src/daemon/mod.rs`, `run.rs` + (`build_params`) and `engine_auth.rs`, and `hyperdb-mcp/README.md` if it + describes the daemon. +- **Content:** the shared engine listens on loopback TCP; connecting requires + a per-daemon password whose plaintext lives only in the owner-only + `daemon.json`; `hyperd` holds only its SCRAM verifier, in an owner-only + config file; clients require SCRAM-SHA-256 with server verification; anyone + running as the same user can read the password and so reach the engine; + the daemon refuses to publish an engine that accepts password-less + connections. State these as properties, not as a weakness walkthrough. +- **Acceptance:** `cargo doc` for `hyperdb-mcp` with `-D warnings`, and + markdownlint. +- **Commit:** `docs(mcp): document the shared engine's trust model`. + +--- + +## Phase A — Move the daemon into `hyperdb-daemon` + +**Goal:** D1–D4. Behaviour, wire formats and the MCP tool surface are +unchanged. Tasks A.1 and A.2 refactor in place so that A.3 is a pure move. + +### Task A.1 — Product-identity seam (in place) + +- **Files:** `hyperdb-mcp/src/daemon/{spawn,health,discovery,run}.rs`, + `hyperdb-mcp/src/main.rs`, `hyperdb-mcp/src/engine.rs`. +- **Steps:** add `DaemonIdentity` (design D3) to `daemon/mod.rs`. Thread it + through `DaemonConfig` and `ensure_daemon` (and anything else that reads + `crate::version`). The four `crate::version::…` references in `daemon/` must + disappear; only `main.rs` and `engine.rs` construct the identity, from + `crate::version`. Keep the PONG token, the `mcp_version` JSON key and the + takeover semantics exactly as they are. +- **Acceptance:** `rg -n 'crate::version' hyperdb-mcp/src/daemon` prints + nothing; full gate passes. +- **Commit:** `refactor(mcp): pass the daemon's product identity in rather than reading MCP_VERSION`. + +### Task A.2 — Move `ReportedPath` and `PathEncoding` (in place) + +- **Steps:** move both types from `diagnostics.rs` into a new + `hyperdb-mcp/src/daemon/report_path.rs`, and `pub use` them from + `diagnostics.rs` so every existing path still resolves. Update the doc + comment in `discovery.rs` that links `crate::paths::persistent_home_dir` so + it no longer depends on `paths` (plain text, or drop the link). +- **Acceptance:** `rg -n 'crate::(diagnostics|paths|version)' hyperdb-mcp/src/daemon` + prints nothing; full gate passes. +- **Commit:** `refactor(mcp): make the daemon module self-contained`. + +### Task A.3 — Create the crate and move the modules + +- **Steps:** + 1. `git mv hyperdb-mcp/src/daemon hyperdb-daemon/src`, then rename + `hyperdb-daemon/src/mod.rs` to `lib.rs`. Use `git mv` so history follows. + 2. Write `hyperdb-daemon/Cargo.toml` modelled on `hyperdb-bootstrap/Cargo.toml` + and `hyperdb-mcp/Cargo.toml`: `version.workspace = true`, the workspace + `edition`, `license`, `repository` and `[lints] workspace = true`. Copy + only the dependencies the moved code uses (design, finding 1), with the + same feature sets and the same `cfg(unix)` / `cfg(windows)` split. Pin + `hyperdb-api` exactly as `hyperdb-mcp` does, inside its own + `# x-release-please-start-version` / `# x-release-please-end` markers. + 3. Inside the moved files, replace `crate::daemon::` with `crate::`. + 4. Add `"hyperdb-daemon"` to the root `Cargo.toml` `members`. + 5. In `hyperdb-mcp/Cargo.toml`, add + `hyperdb-daemon = { path = "../hyperdb-daemon", version = "=" }` + **inside** the existing release-please marker block next to + `hyperdb-api`, so the pin is bumped in lockstep. Remove any dependency + `hyperdb-mcp` no longer uses; CI builds with `CARGO_BUILD_WARNINGS`, so + cargo's unused-dependency warnings fail the build. + 6. In `hyperdb-mcp/src/lib.rs`, replace `pub mod daemon;` with + `pub use hyperdb_daemon as daemon;` keeping its `#[doc(hidden)]`, and + update the architecture bullet. + 7. Fix visibility: anything `pub(crate)` that `hyperdb-mcp` still uses must + become `pub`. Let the compiler list them; do not widen anything else. +- **Acceptance:** `cargo build --workspace` and `cargo clippy` pass. Tests are + A.4. +- **Commit:** `refactor(daemon): move the shared-hyperd daemon into a hyperdb-daemon crate`. + +### Task A.4 — Fix test re-exec paths and prove the tests still run + +The moved unit tests in `discovery.rs` (and possibly others) re-exec their own +test binary with a filter string naming the test, for example +`"daemon::discovery::tests::raw_discovery_rejects_fifo_without_blocking"`. +After the move the binary is `hyperdb-daemon`'s and the path is +`discovery::tests::…`. + +- **Steps:** + 1. `rg -n '"daemon::' hyperdb-daemon/src` and update every hit. + 2. For each re-exec helper, make the parent assert the child actually ran + one test (for example by checking the child's stdout for + `1 passed` or `running 1 test`), so a stale filter fails loudly instead + of passing vacuously. If such an assertion already exists, confirm it. + 3. Run both crates' tests and compare counts with the pre-move baseline: + `cargo test -p hyperdb-mcp` on `upstream/main` before A.1, versus + `cargo test -p hyperdb-daemon` plus `cargo test -p hyperdb-mcp` now. The + totals must match; list any difference with a reason. +- **Acceptance:** full gate; the test-count comparison pasted into the report. +- **Commit:** fold into A.3's commit or a follow-up `test(daemon): …`. + +### Task A.5 — Release and CI plumbing + +A missing entry here fails the *release*, not CI, so check every site. +Discovery method: `rg -n 'hyperdb-bootstrap' .github Makefile build.ps1 *.md docs release-please-config.json` +lists the places that enumerate crates. + +- **Must change:** + - `.github/workflows/release.yml`: add `publish hyperdb-daemon` **after** + `hyperdb-api` and **before** `hyperdb-mcp`, and update the dependency-edge + comment block above the publish calls (`hyperdb-daemon → hyperdb-api`, + `hyperdb-mcp → hyperdb-daemon`). + - `release-please-config.json`: add `hyperdb-daemon/Cargo.toml` to + `extra-files` as a `generic` entry, like the other crates with markers. + - `.github/workflows/ci.yml`: add `-p hyperdb-daemon` to the `doc` job, and + to any publish-dry-run or per-crate list. + - `Makefile` `doc` target and its "Covers all 8 workspace members" comment; + `build.ps1` `$DocCrates` (and `$Crates` if the daemon should build with + the MCP). +- **Check, and update comments if they enumerate crates:** + `.github/workflows/release-please.yml` (the lockfile sentinel derives members + from `cargo metadata`, so only its comments change), + `.github/dependabot.yml` (root `/` already covers it), `deny.toml` and + `about.toml` (no new licenses expected). +- **Acceptance:** `cargo publish --dry-run -p hyperdb-daemon` succeeds (it can, + because the pinned `hyperdb-api` version is already on crates.io), and the + gate's `cargo doc` with both crates passes. +- **Commit:** `ci(release): publish hyperdb-daemon before hyperdb-mcp`. + +### Task A.6 — Documentation + +- `hyperdb-daemon/README.md`: what it is, and a prominent "not a public API + yet" statement modelled on `hyperdb-api-core/README.md`. Link the design. +- `hyperdb-daemon/CHANGELOG.md`: a new file with one `## [Unreleased]` section + and an `### Added` bullet. Copy the header format from a sibling crate. +- `hyperdb-daemon/src/lib.rs`: crate docs with the same internal positioning, + the trust-model text from S.2, and the module map. +- `AGENTS.md`: add the crate to the architecture layer list ("`hyperd` daemon → + `hyperdb-daemon`"), and change the per-crate changelog count from nine to + ten in reminder 8, adding `hyperdb-daemon` to its list. Check + `CONTRIBUTING.md` and `docs/GITHUB_OPERATIONS.md` for crate lists or publish + order and update them. +- `hyperdb-mcp/CHANGELOG.md`: nothing required (the library target is not + public), unless S.1 has not shipped yet. +- **Acceptance:** `npx markdownlint-cli2` with no new findings versus + `upstream/main`; `cargo doc` for `hyperdb-daemon` with `-D warnings`. +- **Commit:** `docs(daemon): document the hyperdb-daemon crate`. + +### Phase A exit + +- Full gate, including Windows-target clippy. +- **End-to-end smoke**, with a scratch `HYPERDB_STATE_DIR` so the + maintainer's real daemon is untouched: build `hyperdb-mcp` in release; start + two MCP clients against it (the end-to-end tests show how to drive one over + stdio); confirm `hyperdb-mcp daemon status` reports one daemon with the same + PID for both; confirm `hyperdb-mcp doctor` is clean; then + `hyperdb-mcp daemon stop` and confirm the lock is released. +- Independent review. Then one PR. Suggested PR title: + `refactor(daemon): extract the shared-hyperd daemon into hyperdb-daemon`. + Note `refactor:` does not cut a release on its own; it ships with the next + `fix:` or `feat:`. + +--- + +## Phase B — Public `acquire()` API (outline; spec revision required) + +Prerequisites: the maintainer's go decision from Phase 0's numbers, decision +D8 made, Phase S shipped, and issue #242 (recovery from an unresponsive +`hyperd`) fixed. + +Expected tasks, to be specified in a design revision: + +1. **Protocol version.** Integer in `daemon.json` and the `PING` reply; clients + accept N and N-1 and treat anything else as "no daemon". +2. **Cohort state directories.** `~/.hyperdb/daemons//` for + library daemons; the MCP keeps `~/.hyperdb`. +3. **Leases.** `ACQUIRE` / `RELEASE` commands, lease count in `STATUS`, idle + timer runs only at zero leases, heartbeats expire dead clients' leases. +4. **Launcher** per D8, likely a `hyperdb-daemon` binary target plus a lookup + order (`HYPERDB_DAEMON_PATH`, beside `hyperd`, `PATH`), and its distribution + story. +5. **API surface.** `Acquisition`, `Options` (`#[non_exhaustive]`), `Engine`, + `SharedEngine`, `acquire` and `acquire_async`, typed errors, and the + `SharedOrPrivate` fallback deadline. +6. **Library defaults.** Idle timeout on by default; libraries never take over + an older daemon. +7. **Docs and examples.** A shared-engine example under `hyperdb-api/examples/` + or the new crate, the IPC-versus-TCP performance trade-off (design D5), and + the trust model. +8. **Security review** of the protocol changes before release. + +Phase B makes `hyperdb-daemon` a public API, so it is a `feat:` and needs a +`### Added` entry in its changelog. diff --git a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md new file mode 100644 index 00000000..31c9932c --- /dev/null +++ b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md @@ -0,0 +1,387 @@ +# Extract the shared-`hyperd` daemon into a `hyperdb-daemon` crate — design + +**Status:** Draft from a read-only spike, 2026-11-24, revised the same day to +move the shared engine to TCP with a password (D5, D6). Not scheduled. +**Plan:** [`../plans/2026-11-24-hyperdb-daemon-extraction.md`](../plans/2026-11-24-hyperdb-daemon-extraction.md) + +## Summary + +`hyperdb-mcp` contains a single-instance daemon that keeps one `hyperd` warm and +shares it across MCP clients: discovery file, single-instance lock, health and +control channel, supervision with crash restart, and idle shutdown. That +machinery is useful to ordinary Hyper API users — test suites, CLIs invoked in +a loop, warm worker pools — but today it can only be reached from the MCP. + +This design splits the work into four phases, each of which can stop there: + +| Phase | What | Public API? | Rough size | +|---|---|---|---| +| **0** | Measure `hyperd` startup cost and idle RSS | No | ~0.5 day | +| **S** | Control-command token; engine password on TCP; strict-SCRAM client | No | ~3–4 days | +| **A** | Move `hyperdb-mcp/src/daemon/` into a new `hyperdb-daemon` crate, positioned as internal | No | ~2–3 days | +| **B** | User-facing `acquire()` API: cohorts, leases, protocol version, a launcher | Yes | ~1.5–2 weeks | + +Sizes are agent time including review and CI iterations, not calendar time. +Phase B also depends on the open issue #242, which is not sized here. + +## What exists today + +`hyperdb-mcp/src/daemon/` is nine files and about 7,400 lines, including inline +unit tests: + +| Module | Role | +|---|---| +| `spawn` | Find or start the daemon (`ensure_daemon`), version takeover | +| `discovery` | State directory, `daemon.json` read/write, trusted-endpoint checks | +| `lock` | Single-instance `daemon.lock` | +| `control` | Health channel transport: Unix socket or named pipe, peer checks | +| `health` | Command loop: `PING`, `HEARTBEAT`, `STOP`, `STATUS`, `REPORT_HYPERD_ERROR` | +| `run` | Daemon main loop, `HyperProcess` supervision, restart limiter, idle timeout | +| `state_perms` | Owner-only directory and file permissions | +| `legacy` | Compatibility with daemon records written by pre-1.0 daemons | +| `mod` | Constants (`DEFAULT_IDLE_TIMEOUT_SECS`, `ENV_IDLE_TIMEOUT`) | + +The daemon already talks to its engine over IPC (#304): `run::build_params` sets +`TransportMode::Ipc` and points `domain_socket_directory` at an owner-only +directory under the state dir. On Windows the named pipe uses `hyperd`'s default +owner-only DACL. + +## Spike findings + +### 1. Coupling into the rest of `hyperdb-mcp` is small + +References from `daemon/` to non-daemon modules: + +| Reference | Uses | Where | +|---|---|---| +| `crate::diagnostics::{ReportedPath, PathEncoding}` | 14 | `discovery.rs` | +| `crate::version::{MCP_VERSION, mcp_version_string}` | 4 | `spawn.rs`, `health.rs`, `discovery.rs` | +| `crate::paths::persistent_home_dir` | 1 | a doc comment in `discovery.rs` only | + +External crates used: `std`, `tokio`, `serde`, `serde_json`, `tracing`, +`tempfile`, `chrono`, `hyperdb_api`, and `libc` / `windows-sys` per platform. +None are MCP-specific (`rmcp`, `arrow`, `plotters` and the rest are not used). + +Inbound users: `main.rs`, `engine.rs`, `server.rs`, `diagnostics.rs`, and +integration tests through `hyperdb_mcp::daemon::…`, for example +`spawn::client_should_take_over`, `run::STARTUP_WAIT` and +`run::DaemonConfig::from_args`. + +### 2. The real blocker is how the daemon process is launched + +`spawn.rs` starts the daemon by re-running the current executable with a +`daemon` argument (`std::env::current_exe()` plus `.arg("daemon")`). So the +daemon process *is* the `hyperdb-mcp` binary. A Hyper API user's program has no +`daemon` subcommand, and a `cargo test` binary is generated by libtest and +cannot take one at all. That is the single largest design question for +Phase B; see [D8](#d8--launcher-for-library-users-open). + +Phase A does not need to solve it: the MCP keeps launching itself. + +### 3. Mechanical traps for the move + +- **Hard-coded test paths.** `discovery.rs` re-execs its own unit-test binary + with a filter string naming the test path, for example + `"daemon::discovery::tests::raw_discovery_rejects_fifo_without_blocking"`. + After the move the path loses its `daemon::` prefix. A stale filter matches + zero tests, so the child runs nothing and the parent can pass for the wrong + reason. Every such string must be updated and the child's test count checked. +- **`pub(crate)` items** that `hyperdb-mcp` uses (for example + `DaemonRecord::executable_path` and `DaemonRecord::mcp_version`) stop being + reachable across the crate boundary and must become `pub`. +- **Product identity.** The PONG token, `daemon.json`'s `mcp_version`, and the + takeover rule all read `MCP_VERSION`. These need a seam, not a global. + +### 4. Correction: there is no pre-1.0 deadline for Phase A + +An earlier exploration argued the extraction had to happen before 1.0 because a +later move would be breaking. That no longer holds. `hyperdb-mcp/src/lib.rs` +declares the library target explicitly *not* a public API: every module is +`#[doc(hidden)]`, and only the MCP tool surface is semver-governed. Moving +`daemon` out later is therefore not a breaking change for anyone. + +What *does* matter for 1.0 is how the new crate is positioned. If +`hyperdb-daemon` ships at the lockstep `1.0.0` with a documented API, that API +is frozen at 1.0. Phase A avoids this by positioning the crate as internal, +following the `hyperdb-api-core` precedent, until Phase B designs the real +surface. + +## Goals + +- Phase A: the daemon lives in its own crate; `hyperdb-mcp` behaviour, + on-disk formats, the control protocol, and the MCP tool surface are unchanged. +- Phase B: a Hyper API user can share one warm `hyperd` across processes of the + same application, opt-in, with a typed error or an observable fallback when + sharing is unavailable. + +## Non-goals + +- Sharing across unrelated applications or trust domains. +- A network-reachable daemon. The engine listens on loopback only + (`127.0.0.1`). A remote engine is a plausible later extension, because D6's + TCP-plus-SCRAM model does not tie authentication to the local machine. It + would need its own design for TLS, credential provisioning to remote + clients, and a remote control channel; nothing here should preclude it. +- Changing `HyperProcess`'s default transport. It stays TCP. +- Moving MCP policy into the crate: attachment replay, the persistent and + ephemeral database model, the catalog, the KV store, watched directories, + the doctor, and the MCP's version-takeover UX all stay in `hyperdb-mcp`. + +## Decisions + +### D1 — Phase A ships an internal crate + +`hyperdb-daemon` joins the workspace, is lockstep-versioned like every other +crate, and is published (Cargo requires it, since `hyperdb-mcp` depends on it). +Its README and crate docs state that it is not yet a public API, mirroring +`hyperdb-api-core/README.md`. Phase B makes it public additively, in a minor +release. + +- **Rejected — independent `0.x` versioning.** The release model is a single + release-please package (`"."`) with lockstep pins. An independently + versioned crate would need a second package and its own tag stream. + +### D2 — The MCP keeps its binary and subcommand + +`hyperdb-mcp daemon` stays the MCP's daemon entry point and calls +`hyperdb_daemon::run::run_daemon`. `hyperdb_mcp::daemon` becomes +`pub use hyperdb_daemon as daemon;`, so existing `crate::daemon::…` and +`hyperdb_mcp::daemon::…` paths keep compiling with no churn in `main.rs`, +`engine.rs`, `server.rs`, `diagnostics.rs`, or the integration tests. + +### D3 — A product-identity seam replaces `MCP_VERSION` + +Introduce a small value type, provisionally: + +```rust +#[derive(Clone, Debug)] +pub struct DaemonIdentity { + /// Token in the PONG reply and the discovery record, e.g. "hyperdb-mcp". + pub product: &'static str, + /// Semver used by the takeover rule. + pub version: &'static str, + /// Human-readable version for STATUS and daemon.json, e.g. with git hash. + pub version_string: String, +} +``` + +The MCP constructs it from `crate::version` and passes it into `DaemonConfig` +and `ensure_daemon`. Wire output is byte-for-byte unchanged: same PONG token, +same `mcp_version` JSON key. Renaming the key is a Phase B protocol change, not +a refactor. + +Do this refactor *inside* `hyperdb-mcp` first, so the move itself is purely +mechanical. + +### D4 — `ReportedPath` and `PathEncoding` move with the daemon + +They are bounded, display-safe path types. Move them to +`hyperdb_daemon::report_path` (name provisional) and re-export them from +`hyperdb_mcp::diagnostics`, so the doctor's code is untouched. + +### D5 — The shared engine listens on TCP loopback, with a password + +The shared engine listens on `127.0.0.1` and requires a per-daemon password +(D6). This keeps TCP's throughput, which IPC does not match for bulk work. +Measurements behind the comment in `hyperdb-api/src/process.rs` and +`docs/BENCHMARK_GUIDE.md`: + +| Workload | IPC vs TCP loopback | +|---|---| +| Connect | about 30% faster (macOS, Unix socket) | +| Small round-trip | about 19% faster (macOS) | +| Streamed reads past about 10k rows | up to 62% slower (macOS) | +| Windows named pipe, single-connection insert | 34–41% slower | +| Windows named pipe, async full scan | 76% slower | + +The password gives the TCP listener the same boundary the IPC transports get +from file permissions: connecting requires reading an owner-only file. + +**TCP over the PostgreSQL protocol is the only transport.** New daemons never +create an IPC or gRPC listener: + +- **No IPC option.** A second transport means a second permission model to + build, test and document. Its connect-latency gain matters little once + connections are pooled. Clients still connect to an *older* daemon whose + record names a socket or pipe, for the upgrade transition only. +- **No gRPC.** `hyperd`'s gRPC service accepts only trusted users. Making + gRPC work would need a password-less user, which any local process could + use over TCP, undoing D6. Probed on 2026-11-24 with the D6 config: a gRPC + query with no user was refused ("access denied"), and one naming the engine + user was refused ("gRPC connections only support trusted authentication"). + Nothing is + lost: the MCP does not use local gRPC (the gRPC kind in `attach.rs` is a + planned remote Data 360 attach with its own authentication), and Arrow reads + work over PostgreSQL TCP through `ArrowReader`. Callers who want a local + gRPC engine keep private `HyperProcess` with `ListenMode::Grpc` or + `ListenMode::Both`. + +Private mode (`HyperProcess`) is unchanged by this design. It could adopt the +same mechanism later as separate work. + +### D6 — Engine credential: a generated password, delivered by config file + +**Decided (maintainer, 2026-11-24):** the config-file route below, with the +environment variable kept as a documented fallback. Each daemon +start generates a random password and gives the engine only its SCRAM-SHA-256 +verifier. Verified against the pinned `hyperd` (0.0.26479) on 2026-11-24, both +directly and through `HyperProcess` with no `hyperdb-api` change. + +**Primary route: a `hyperd` settings file.** + +- The daemon writes `/engine/hyperd-auth.json`, created owner-only + (mode `0600` at creation, not `chmod` afterwards; on Windows, the existing + owner-only DACL helpers), containing: + + ```json + {"authorized_users": [{"name": "tableau_internal_user", "superuser": true, + "authentication": {"method": "scram_sha256", + "encrypted_password": "SCRAM-SHA-256$4096:$:"}}]} + ``` + +- It starts `hyperd` with the `config` and `strict_settings_mode` parameters + (`--config=` and `--strict-settings-mode` in `hyperd --help`). +- The password itself goes only into `daemon.json`, for clients. +- The daemon computes the verifier itself, in the standard PostgreSQL format + (PBKDF2-HMAC-SHA256, then `HMAC("Client Key")` hashed and + `HMAC("Server Key")`), reusing the primitives in + `hyperdb-api-core/src/client/auth.rs`. `hyperd scram-sha256-hash` cannot be + used: it reads the password from the terminal and hangs when its input is + piped. + +Properties confirmed by the probe: + +- The password appears neither in `hyperd`'s arguments nor in its environment + (`ps eww`). +- `hyperd` never reaches its password prompt when `authorized_users` is set. +- The `--no-password` that `HyperProcess` adds by default is ignored when + `authorized_users` is set; no password, a wrong password and the right one + give rejected, rejected and connected. + +**Strict settings mode is mandatory.** Without it, `hyperd` treats an unknown +setting name as a warning and starts anyway, and the `--no-password` default +from `HyperProcess` would then apply. With `--strict-settings-mode` an +unrecognised setting fails startup (exit 1, "Critical setting errors +encountered"), so the engine either starts with the configured user or not at +all. + +**Startup self-check.** Before the daemon writes `daemon.json`, it connects to +the engine with no password and requires a rejection. If the engine accepts +the connection, the daemon stops `hyperd` and fails startup. This catches any +other way the engine could come up unauthenticated, including a future change +in how `--no-password` and `authorized_users` interact. + +**Fallback route: the `HYPER_INITIAL_USER_PASSWORD` environment variable.** +`authorized_users` is not listed in `hyperd --help`, but it appears in +publicly visible Hyper configurations, which is why the maintainer accepted +it. If a `hyperd` bump breaks the pin-bump test, or the Hyper team advises +against it, switch to the environment variable, which is also absent from +`--help`. Consequences: + +- The password is in `hyperd`'s initial environment and visible to the same + user through `ps eww`. That is no new exposure, because the same user can + read `daemon.json`. +- `--no-password` must be omitted, and the variable must always be set: + without either, `hyperd` prompts on the terminal. A test must show that a + missing variable fails startup rather than hangs. +- `HyperProcess` needs two additions in `hyperdb-api`: a way to suppress the + default `--no-password`, and a way to set the child's environment. Both are + public API changes. + +Only the daemon's parameter builder (`run::build_params`) and the new +password module change between the two routes. + +**The client requires SCRAM.** A password on the server is only half the +mechanism; the client must also insist on it. Connections to a shared engine +use a new strict mode in `hyperdb-api-core/src/client/connection.rs` (and its +async twin), comparable to libpq's `require_auth=scram-sha-256`, while the +default mode keeps today's behaviour for other servers. In strict mode the +connection succeeds only if the server ran +SCRAM-SHA-256 and its final message verified (`scram_verify_server`). Every +other authentication request, and an `AuthenticationOk` before a verified +SASL final, is an error before any query is sent. + +**No gRPC listener** (D5): `hyperd`'s gRPC service cannot authenticate a SCRAM +user, so the daemon never enables it. + +### D7 — A capability token gates state-changing control commands + +Generate a random token per daemon start, store it in the owner-only +`daemon.json`, and require it on `STOP` and `REPORT_HYPERD_ERROR`. `PING`, +`STATUS` and `HEARTBEAT` stay open. This is defence in depth: today these +commands are only reachable by the owning user, so this is hardening, not a +fix. Phase S, and independent of the extraction. + +Compatibility: a pre-token client talking to a token-requiring daemon must be +handled deliberately. The plan specifies the behaviour and a test for it. + +### D8 — Launcher for library users (open) + +How does a library caller start a daemon when the host binary has no `daemon` +subcommand? + +| Option | How | Works for `cargo test`? | Cost | +|---|---|---|---| +| **L1** host hook | Host calls `hyperdb_daemon::run_if_requested()` first thing in `main`; spawn re-execs `current_exe` with an env var | **No** — libtest owns `main` | None to ship | +| **L2** standalone binary | Ship a `hyperdb-daemon` binary; locate it via `HYPERDB_DAEMON_PATH`, beside `hyperd`, or on `PATH` | Yes | A distribution artifact (`cargo install`, or a release download) | +| **L3** no supervisor | First client spawns a detached `hyperd`; no daemon process | Yes | Loses restart, idle shutdown and leases | + +**Recommended: L2**, with L1 as an optional extra for applications that prefer +not to ship a second binary. The primary motivating workload — test suites — +rules out L1 alone. + +### D9 — Phase B API: adopt the earlier exploration's shape + +The offline design exploration proposed an API worth keeping. In brief: + +- **Cohorts.** A daemon is keyed by a caller-supplied cohort name, with state + under `~/.hyperdb/daemons//`. The MCP stays on `~/.hyperdb` for + compatibility. No machine-wide default for libraries. +- **Three explicit intents.** `Acquisition::{Private, Shared, SharedOrPrivate}`. + `Private` is the default and is today's `HyperProcess`. `Shared` fails with a + typed error. `SharedOrPrivate` has a hard `fallback_deadline` and reports why + it fell back, logged at `warn`. +- **Leases.** Clients register on acquire and release on drop; the idle timer + runs only at zero leases; heartbeats expire leases of dead clients. Idle + timeout is **on** by default for library daemons, so a test run leaves no + resident service behind. +- **Libraries never take over.** A library never sends `STOP` to an older + daemon. An incompatible daemon is treated as absent and a separate cohort + daemon is started. Takeover stays an MCP and operator action. +- **Protocol version.** An integer in `daemon.json` and the `PING` reply, + versioned independently of the crate; clients support N and N-1. +- **Surface.** `acquire(how, &Options) -> Result` and `acquire_async`, + with `Engine::endpoint()` plus the engine credentials (D6) usable by every + existing `hyperdb-api` connect API and by `PoolConfig`, with strict SCRAM + switched on. `Options` is `#[non_exhaustive]`. Dropping a + `SharedEngine` releases its lease and does **not** stop `hyperd`. + +Phase B gets its own spec revision before work starts; this section only fixes +the direction. + +## Open decisions for the maintainer + +1. **Go / no-go on Phase B**, after Phase 0's numbers. Suggested bar: if a + release-mode `HyperProcess::new()` to first query is well under a second on + macOS and Linux, the sharing benefit is small for most users and Phase A is + the place to stop. +2. **D8:** L2 alone, or L2 plus L1. +3. **Timing of Phase A:** any time; there is no 1.0 deadline (finding 4). It + can wait until after the Linux ARM work lands, which touches the same + release plumbing. + +## Risks + +- **Stale test filters** (finding 3) passing vacuously. Mitigated by asserting + the child's test count in the plan's gate. +- **Windows-only code** in `control.rs` and `state_perms.rs` that only CI + compiles. Mitigated by local Windows-target clippy before pushing. +- **Release plumbing drift.** A new crate must be added to the publish order, + lockstep pins and every crate list. Missing one fails the release, not CI. +- **Internal `hyperd` setting** (D6). `authorized_users` could change format + or be renamed in a `hyperd` release. Mitigated by strict settings mode (an + unknown setting fails startup), the startup self-check, and an integration + test that the `update-hyperd-release` procedure runs on every pin bump. The + environment-variable route is the planned fallback. +- **Phase B security review.** The control-protocol changes (token, leases, + protocol version) should get an independent security review before release. From 3d83a87172144ad884968757bd84c8149caed449 Mon Sep 17 00:00:00 2001 From: Stefan Steiner Date: Wed, 25 Nov 2026 12:10:01 -0800 Subject: [PATCH 2/4] docs(daemon): add upgrade and mixed-version decision (D7a) Pre-1.0 clients are unsupported against a 1.0 daemon; the daemon reports a rejected client in STATUS/log naming the upgrade, and the changelog documents the rule. --- .../2026-11-24-hyperdb-daemon-extraction.md | 4 +++ ...-11-24-hyperdb-daemon-extraction-design.md | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md index 7ae9f183..65a83fbe 100644 --- a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md +++ b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md @@ -246,6 +246,10 @@ Design D5 and D6 hold the rationale and the probe results; read them first. authenticate. Make sure that surfaces as a clear error (and, where the MCP has a takeover path, that it behaves like any failed attach). Note it in the `hyperdb-mcp` changelog. + Per design D7a, pre-1.0 clients are unsupported against a 1.0 daemon: + the daemon reports a rejected client in `STATUS` and its log, naming the + upgrade, and a test records what an old client sees so the changelog can + quote it. 8. **Fallback, documented only.** In `engine_auth.rs`'s module docs, record the environment-variable route from design D6 and what switching to it takes. Do not implement it. diff --git a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md index 31c9932c..9bad6709 100644 --- a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md +++ b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md @@ -315,6 +315,34 @@ fix. Phase S, and independent of the extraction. Compatibility: a pre-token client talking to a token-requiring daemon must be handled deliberately. The plan specifies the behaviour and a test for it. +### D7a — Upgrading from pre-1.0 clients and daemons + +Nobody has to uninstall an older `hyperdb-mcp` before using a newer one. The +daemon is per user (one per state directory), and the existing version rule +only ever replaces an *older* daemon: a newer client sends it `STOP` and starts +its own; an older or equal client reuses whatever is running. Phase A changes +none of this, because the binary, tool surface, record format and control +protocol stay as they are. Only Phase S (D6, D7) can break a mixed install: + +| Client | Daemon | Result | +| --- | --- | --- | +| newer | older | The client takes the daemon over, or keeps using it: a record with no password or token behaves as today. | +| older | newer | The client cannot authenticate to the shared engine and gets `ERR unauthorized` on `STOP`. It cannot take over a newer daemon, so it fails for as long as that daemon runs. | + +The second row is the case to handle. It arises when an old client stays +running next to a newer one (for example, a version pinned in a second editor). +**Decision:** from 1.0, pre-1.0 clients are unsupported against a 1.0 daemon. +There is no compatibility layer, as with the earlier move of the health channel +off TCP. What the design adds is clarity, not compatibility: + +- The first release carrying Phase S documents the rule in the `hyperdb-mcp` + changelog and release notes: upgrade every client together. +- The daemon reports a rejected client in `STATUS` and its log, with a message + that names the upgrade, so a failure is diagnosable from the daemon side. +- An already-shipped client cannot be changed, so its own error text is outside + the design. Phase S includes a test that records what an old client sees, and + the changelog quotes it. + ### D8 — Launcher for library users (open) How does a library caller start a daemon when the host binary has no `daemon` From 484dd3c9320b084942ed0d49fef08eb991f32521 Mon Sep 17 00:00:00 2001 From: Stefan Steiner Date: Wed, 25 Nov 2026 12:35:53 -0800 Subject: [PATCH 3/4] docs(daemon): standalone binary for other-language users; protocol_version and engine_user in Phase S Decide D8 (standalone hyperdb-daemon binary, L1 dropped) and reshape Phase B around a language-neutral contract (command line, record schema, control protocol) with the Rust acquire() API as a layer on top, so users of the Hyper API in C++, Python or Java can share an engine. Phase S gains protocol_version and engine_user in daemon.json so that contract starts from a known baseline. Also reflow a broken line in D5. --- .../2026-11-24-hyperdb-daemon-extraction.md | 41 ++++++---- ...-11-24-hyperdb-daemon-extraction-design.md | 81 ++++++++++++++----- 2 files changed, 84 insertions(+), 38 deletions(-) diff --git a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md index 65a83fbe..fe11c3b2 100644 --- a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md +++ b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md @@ -143,12 +143,16 @@ S.3 + S.4 + S.2. takeover path then treats it like any failed takeover. Document this in the `hyperdb-mcp` changelog. 7. Never print the token in `STATUS`, the doctor output or any log. + 8. **Protocol version** (design D7). Add `protocol_version: u32` to + `DaemonRecord` with `#[serde(default)]` (absent means `0`) and to the + `STATUS` JSON; this daemon writes `1`. Leave the `PING` reply unchanged. - **Tests** (unit tests in the touched modules, plus `hyperdb-mcp/tests/daemon_tests.rs`): `STOP` with the correct token stops the daemon; `STOP` with no token or a wrong token is rejected and the daemon keeps running; same for `REPORT_HYPERD_ERROR` (three wrong-token reports must **not** trip `RESTART_LIMIT`); a record without the field parses; `STATUS` and the doctor - output contain no token. + output contain no token; a new record and `STATUS` carry + `protocol_version: 1`, and a record without it parses as `0`. - **Acceptance:** the full gate. - **Commit:** `fix(mcp): require a per-daemon token for STOP and REPORT_HYPERD_ERROR`. @@ -232,8 +236,9 @@ Design D5 and D6 hold the rationale and the probe results; read them first. must fail with an authentication error. If it succeeds, stop `hyperd`, log an `error`, and fail startup. Then connect with the password and strict SCRAM on, and run `SELECT 1`. - 5. **Discovery record.** Add `engine_password` to `DaemonRecord` with - `#[serde(default)]`. Never print it in `STATUS`, the doctor, or any log. + 5. **Discovery record.** Add `engine_password` and `engine_user` (the + `authorized_users` name) to `DaemonRecord` with `#[serde(default)]`; + clients connect as `engine_user` rather than a hard-coded name. Never print it in `STATUS`, the doctor, or any log. The password stays the same for the daemon's lifetime, including supervisor restarts of `hyperd`, so clients keep working across a restart; the config file is reused as-is on restart. @@ -440,32 +445,36 @@ lists the places that enumerate crates. --- -## Phase B — Public `acquire()` API (outline; spec revision required) +## Phase B — Standalone daemon and public contract (outline; spec revision required) -Prerequisites: the maintainer's go decision from Phase 0's numbers, decision -D8 made, Phase S shipped, and issue #242 (recovery from an unresponsive -`hyperd`) fixed. +Prerequisites: the maintainer's go decision from Phase 0's numbers, Phase S +shipped, and issue #242 (recovery from an unresponsive `hyperd`) fixed. D8 is +decided: a standalone binary. Expected tasks, to be specified in a design revision: -1. **Protocol version.** Integer in `daemon.json` and the `PING` reply; clients - accept N and N-1 and treat anything else as "no daemon". +1. **Protocol version.** Phase S put it in `daemon.json` and `STATUS`; add it + to the `PING` reply. Clients accept N and N-1 and treat anything else as + "no daemon". 2. **Cohort state directories.** `~/.hyperdb/daemons//` for library daemons; the MCP keeps `~/.hyperdb`. 3. **Leases.** `ACQUIRE` / `RELEASE` commands, lease count in `STATUS`, idle timer runs only at zero leases, heartbeats expire dead clients' leases. -4. **Launcher** per D8, likely a `hyperdb-daemon` binary target plus a lookup - order (`HYPERDB_DAEMON_PATH`, beside `hyperd`, `PATH`), and its distribution - story. -5. **API surface.** `Acquisition`, `Options` (`#[non_exhaustive]`), `Engine`, +4. **Standalone binary** per D8: a `hyperdb-daemon` binary target, a lookup + order (`HYPERDB_DAEMON_PATH`, beside `hyperd`, `PATH`), a `hyperd` path + option, and prebuilt release assets for every supported platform. +5. **Language-neutral contract** per D9: the `acquire --json` and `exec` + commands, the documented `daemon.json` schema and control protocol, and a + C++ Hyper API example that connects with the printed credentials. +6. **Rust API surface.** `Acquisition`, `Options` (`#[non_exhaustive]`), `Engine`, `SharedEngine`, `acquire` and `acquire_async`, typed errors, and the `SharedOrPrivate` fallback deadline. -6. **Library defaults.** Idle timeout on by default; libraries never take over +7. **Library defaults.** Idle timeout on by default; libraries never take over an older daemon. -7. **Docs and examples.** A shared-engine example under `hyperdb-api/examples/` +8. **Docs and examples.** A shared-engine example under `hyperdb-api/examples/` or the new crate, the IPC-versus-TCP performance trade-off (design D5), and the trust model. -8. **Security review** of the protocol changes before release. +9. **Security review** of the protocol changes before release. Phase B makes `hyperdb-daemon` a public API, so it is a `feat:` and needs a `### Added` entry in its changelog. diff --git a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md index 9bad6709..42bc258f 100644 --- a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md +++ b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md @@ -19,7 +19,7 @@ This design splits the work into four phases, each of which can stop there: | **0** | Measure `hyperd` startup cost and idle RSS | No | ~0.5 day | | **S** | Control-command token; engine password on TCP; strict-SCRAM client | No | ~3–4 days | | **A** | Move `hyperdb-mcp/src/daemon/` into a new `hyperdb-daemon` crate, positioned as internal | No | ~2–3 days | -| **B** | User-facing `acquire()` API: cohorts, leases, protocol version, a launcher | Yes | ~1.5–2 weeks | +| **B** | Standalone `hyperdb-daemon` binary with a language-neutral contract (command line, record, control protocol); Rust `acquire()` on top | Yes | ~2–3 weeks | Sizes are agent time including review and CI iterations, not calendar time. Phase B also depends on the open issue #242, which is not sized here. @@ -74,7 +74,7 @@ integration tests through `hyperdb_mcp::daemon::…`, for example daemon process *is* the `hyperdb-mcp` binary. A Hyper API user's program has no `daemon` subcommand, and a `cargo test` binary is generated by libtest and cannot take one at all. That is the single largest design question for -Phase B; see [D8](#d8--launcher-for-library-users-open). +Phase B; see [D8](#d8--launcher-for-library-users-a-standalone-binary). Phase A does not need to solve it: the MCP keeps launching itself. @@ -112,7 +112,9 @@ surface. on-disk formats, the control protocol, and the MCP tool surface are unchanged. - Phase B: a Hyper API user can share one warm `hyperd` across processes of the same application, opt-in, with a typed error or an observable fallback when - sharing is unavailable. + sharing is unavailable. This includes users of the Hyper API in other + languages (C++, Python, Java), who run the standalone `hyperdb-daemon` + binary and connect with their own Hyper API client. Rust is not required. ## Non-goals @@ -209,12 +211,11 @@ create an IPC or gRPC listener: use over TCP, undoing D6. Probed on 2026-11-24 with the D6 config: a gRPC query with no user was refused ("access denied"), and one naming the engine user was refused ("gRPC connections only support trusted authentication"). - Nothing is - lost: the MCP does not use local gRPC (the gRPC kind in `attach.rs` is a - planned remote Data 360 attach with its own authentication), and Arrow reads - work over PostgreSQL TCP through `ArrowReader`. Callers who want a local - gRPC engine keep private `HyperProcess` with `ListenMode::Grpc` or - `ListenMode::Both`. + Nothing is lost: the MCP does not use local gRPC (the gRPC kind in + `attach.rs` is a planned remote Data 360 attach with its own + authentication), and Arrow reads work over PostgreSQL TCP through + `ArrowReader`. Callers who want a local gRPC engine keep private + `HyperProcess` with `ListenMode::Grpc` or `ListenMode::Both`. Private mode (`HyperProcess`) is unchanged by this design. It could adopt the same mechanism later as separate work. @@ -241,7 +242,9 @@ directly and through `HyperProcess` with no `hyperdb-api` change. - It starts `hyperd` with the `config` and `strict_settings_mode` parameters (`--config=` and `--strict-settings-mode` in `hyperd --help`). -- The password itself goes only into `daemon.json`, for clients. +- The password itself goes only into `daemon.json`, for clients, next to the + engine user name (`engine_user`), so that clients in other languages + (Phase B) read the user rather than hard-coding it. - The daemon computes the verifier itself, in the standard PostgreSQL format (PBKDF2-HMAC-SHA256, then `HMAC("Client Key")` hashed and `HMAC("Server Key")`), reusing the primitives in @@ -315,6 +318,14 @@ fix. Phase S, and independent of the extraction. Compatibility: a pre-token client talking to a token-requiring daemon must be handled deliberately. The plan specifies the behaviour and a test for it. +**Protocol version.** Phase S also adds an integer `protocol_version` to +`daemon.json` and the `STATUS` JSON, starting at `1` for the first daemon that +requires the token. A record without it is version `0`. The number covers the +record and the control protocol, is versioned independently of the crates, and +gives Phase B's public contract a known baseline. The `PING` reply is +unchanged in Phase S; existing clients ignore any token after the version, so +Phase B can append the number there without breaking them. + ### D7a — Upgrading from pre-1.0 clients and daemons Nobody has to uninstall an older `hyperdb-mcp` before using a newer one. The @@ -343,7 +354,7 @@ off TCP. What the design adds is clarity, not compatibility: the design. Phase S includes a test that records what an old client sees, and the changelog quotes it. -### D8 — Launcher for library users (open) +### D8 — Launcher for library users: a standalone binary How does a library caller start a daemon when the host binary has no `daemon` subcommand? @@ -354,13 +365,36 @@ subcommand? | **L2** standalone binary | Ship a `hyperdb-daemon` binary; locate it via `HYPERDB_DAEMON_PATH`, beside `hyperd`, or on `PATH` | Yes | A distribution artifact (`cargo install`, or a release download) | | **L3** no supervisor | First client spawns a detached `hyperd`; no daemon process | Yes | Loses restart, idle shutdown and leases | -**Recommended: L2**, with L1 as an optional extra for applications that prefer -not to ship a second binary. The primary motivating workload — test suites — -rules out L1 alone. - -### D9 — Phase B API: adopt the earlier exploration's shape - -The offline design exploration proposed an API worth keeping. In brief: +**Decided (maintainer, 2026-11-25): L2.** The standalone binary is the product, +because users of the Hyper API in other languages have no Rust host to hook +into, and test suites rule out L1 anyway. L1 is dropped. Consequences: + +- Release assets carry a prebuilt `hyperdb-daemon` for every supported + platform; other-language users will not have `cargo`. +- The binary takes the `hyperd` to run as an option (for example the one + bundled with the user's Hyper API package), falling back to `HYPERD_PATH`. + Strict settings mode and the startup self-check (D6) make a `hyperd` too old + for `authorized_users` fail startup cleanly. Phase B tests and documents the + oldest supported `hyperd`. + +### D9 — Phase B contract: language-neutral first, Rust on top + +The public contract is the binary's behaviour, not a Rust API, so that any +language can use it: + +- **Command line.** `hyperdb-daemon acquire --cohort --json` starts the + cohort's daemon or reuses it, and prints the engine endpoint, user, password + and protocol version. `hyperdb-daemon exec --cohort -- ` + holds a lease for the lifetime of the child process, which suits test + suites. Exact names are fixed in the Phase B spec revision. +- **Documented formats.** The `daemon.json` schema and the control protocol + are documented and versioned by `protocol_version` (D7), for applications + that want to hold leases in-process. +- **Semver surface.** The command line, the record schema and the protocol. + The `hyperdb-daemon` Rust crate can stay internal (D1) even after Phase B. + +The offline design exploration proposed a Rust API worth keeping as a +convenience layer over that contract. In brief: - **Cohorts.** A daemon is keyed by a caller-supplied cohort name, with state under `~/.hyperdb/daemons//`. The MCP stays on `~/.hyperdb` for @@ -376,8 +410,8 @@ The offline design exploration proposed an API worth keeping. In brief: - **Libraries never take over.** A library never sends `STOP` to an older daemon. An incompatible daemon is treated as absent and a separate cohort daemon is started. Takeover stays an MCP and operator action. -- **Protocol version.** An integer in `daemon.json` and the `PING` reply, - versioned independently of the crate; clients support N and N-1. +- **Protocol version.** The integer Phase S introduces (D7), added to the + `PING` reply; clients support N and N-1. - **Surface.** `acquire(how, &Options) -> Result` and `acquire_async`, with `Engine::endpoint()` plus the engine credentials (D6) usable by every existing `hyperdb-api` connect API and by `PoolConfig`, with strict SCRAM @@ -393,8 +427,7 @@ the direction. release-mode `HyperProcess::new()` to first query is well under a second on macOS and Linux, the sharing benefit is small for most users and Phase A is the place to stop. -2. **D8:** L2 alone, or L2 plus L1. -3. **Timing of Phase A:** any time; there is no 1.0 deadline (finding 4). It +2. **Timing of Phase A:** any time; there is no 1.0 deadline (finding 4). It can wait until after the Linux ARM work lands, which touches the same release plumbing. @@ -411,5 +444,9 @@ the direction. unknown setting fails startup), the startup self-check, and an integration test that the `update-hyperd-release` procedure runs on every pin bump. The environment-variable route is the planned fallback. +- **Other-language clients.** D6's client-side requirement (strict SCRAM) is + enforced by this repository's client only. Phase B documents, for each + supported language, whether its Hyper API client can require SCRAM, and + raises any gap with the Hyper team. - **Phase B security review.** The control-protocol changes (token, leases, protocol version) should get an independent security review before release. From 392030c2035baffac87b519154ac9017d877d624 Mon Sep 17 00:00:00 2001 From: Stefan Steiner Date: Thu, 26 Nov 2026 11:11:18 -0800 Subject: [PATCH 4/4] docs(daemon): one engine per app ID; database sharing as the motivation Sharing a .hyper file across processes needs a shared engine because the file is locked by the hyperd that opened it. Key each daemon by a required app ID (the MCP is app `mcp`, keeping ~/.hyperdb) instead of a shared default cohort: an app's processes share one engine, apps do not share databases and update independently. Takeover stays lease-aware and only happens between versions of the same app. --- .../2026-11-24-hyperdb-daemon-extraction.md | 14 ++-- ...-11-24-hyperdb-daemon-extraction-design.md | 72 ++++++++++++++----- 2 files changed, 65 insertions(+), 21 deletions(-) diff --git a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md index fe11c3b2..deb01ea0 100644 --- a/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md +++ b/docs/superpowers/plans/2026-11-24-hyperdb-daemon-extraction.md @@ -456,8 +456,9 @@ Expected tasks, to be specified in a design revision: 1. **Protocol version.** Phase S put it in `daemon.json` and `STATUS`; add it to the `PING` reply. Clients accept N and N-1 and treat anything else as "no daemon". -2. **Cohort state directories.** `~/.hyperdb/daemons//` for - library daemons; the MCP keeps `~/.hyperdb`. +2. **Per-app state directories.** A required app ID (`[a-z0-9-]`) keys each + daemon; state lives under `~/.hyperdb/apps//`. The MCP is app `mcp` + and keeps `~/.hyperdb`. 3. **Leases.** `ACQUIRE` / `RELEASE` commands, lease count in `STATUS`, idle timer runs only at zero leases, heartbeats expire dead clients' leases. 4. **Standalone binary** per D8: a `hyperdb-daemon` binary target, a lookup @@ -469,8 +470,13 @@ Expected tasks, to be specified in a design revision: 6. **Rust API surface.** `Acquisition`, `Options` (`#[non_exhaustive]`), `Engine`, `SharedEngine`, `acquire` and `acquire_async`, typed errors, and the `SharedOrPrivate` fallback deadline. -7. **Library defaults.** Idle timeout on by default; libraries never take over - an older daemon. +7. **Per-app engines and takeover.** One engine per app ID, no shared + default; apps do not share databases. Version takeover becomes lease-aware + (no `STOP` while another process of the app holds a lease) and only + happens between versions of the same app; libraries never take over. + Define which `hyperd` an app's daemon runs across an app update and how + database file versions are handled. Idle timeout on by default for + library daemons. 8. **Docs and examples.** A shared-engine example under `hyperdb-api/examples/` or the new crate, the IPC-versus-TCP performance trade-off (design D5), and the trust model. diff --git a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md index 42bc258f..95db81b1 100644 --- a/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md +++ b/docs/superpowers/specs/2026-11-24-hyperdb-daemon-extraction-design.md @@ -12,6 +12,17 @@ control channel, supervision with crash restart, and idle shutdown. That machinery is useful to ordinary Hyper API users — test suites, CLIs invoked in a loop, warm worker pools — but today it can only be reached from the MCP. +The main reason to share an engine is to share its **databases**. A `.hyper` +file is locked by the `hyperd` that opened it, so two processes that each +start their own engine cannot both work on the same file. A shared engine +lets all the processes of one application, written against the Hyper API in +any language, work on the same databases at the same time. Each application +gets its own engine, keyed by an **app ID** (D9): the MCP, an indexing +service and a catalog service each run a separate engine and do not share +databases with each other, so each can be updated and restarted on its own. +Startup cost is secondary: Phase 0 measured about 61 ms from spawn to first +query. + This design splits the work into four phases, each of which can stop there: | Phase | What | Public API? | Rough size | @@ -110,15 +121,23 @@ surface. - Phase A: the daemon lives in its own crate; `hyperdb-mcp` behaviour, on-disk formats, the control protocol, and the MCP tool surface are unchanged. -- Phase B: a Hyper API user can share one warm `hyperd` across processes of the - same application, opt-in, with a typed error or an observable fallback when - sharing is unavailable. This includes users of the Hyper API in other +- Phase B: the processes of one application, running as the same OS user, + can share one `hyperd` and the databases it has open. Each application has + its own engine, identified by its app ID; the MCP is app `mcp`. Sharing is + opt-in, with a typed error or an observable + fallback when it is unavailable. This includes users of the Hyper API in other languages (C++, Python, Java), who run the standalone `hyperdb-daemon` binary and connect with their own Hyper API client. Rust is not required. ## Non-goals -- Sharing across unrelated applications or trust domains. +- Sharing across OS users or trust domains. The trust boundary is the OS + user: anyone running as that user can read the engine password (D6). +- Sharing databases between applications. Each app ID gets its own engine, + and the `.hyper` file lock keeps one engine's databases out of another's. + The separation between apps is organisational, not a security boundary: + every engine runs as the same OS user, so a process that knows another + app's ID can join that app's engine. - A network-reachable daemon. The engine listens on loopback only (`127.0.0.1`). A remote engine is a plausible later extension, because D6's TCP-plus-SCRAM model does not tie authentication to the local machine. It @@ -382,9 +401,9 @@ into, and test suites rule out L1 anyway. L1 is dropped. Consequences: The public contract is the binary's behaviour, not a Rust API, so that any language can use it: -- **Command line.** `hyperdb-daemon acquire --cohort --json` starts the - cohort's daemon or reuses it, and prints the engine endpoint, user, password - and protocol version. `hyperdb-daemon exec --cohort -- ` +- **Command line.** `hyperdb-daemon acquire --app --json` starts the + app's daemon or reuses it, and prints the engine endpoint, user, password + and protocol version. `hyperdb-daemon exec --app -- ` holds a lease for the lifetime of the child process, which suits test suites. Exact names are fixed in the Phase B spec revision. - **Documented formats.** The `daemon.json` schema and the control protocol @@ -396,9 +415,16 @@ language can use it: The offline design exploration proposed a Rust API worth keeping as a convenience layer over that contract. In brief: -- **Cohorts.** A daemon is keyed by a caller-supplied cohort name, with state - under `~/.hyperdb/daemons//`. The MCP stays on `~/.hyperdb` for - compatibility. No machine-wide default for libraries. +- **App IDs.** A daemon is keyed by an app ID, which every caller must + supply; there is no shared default. All processes of one application use + the same ID and so share one engine and its databases; different + applications use different IDs and get separate engines, which they update + and restart independently. The MCP is app `mcp` and keeps its existing state + under `~/.hyperdb`, so it needs no migration. Other apps keep state under + `~/.hyperdb/apps//`. IDs are limited to `[a-z0-9-]`, so the directory + name is the ID itself. A test suite that wants isolation picks its own ID. + Each engine costs about 56 MiB idle (Phase 0); the idle timeout reclaims + engines no process is using. - **Three explicit intents.** `Acquisition::{Private, Shared, SharedOrPrivate}`. `Private` is the default and is today's `HyperProcess`. `Shared` fails with a typed error. `SharedOrPrivate` has a hard `fallback_deadline` and reports why @@ -407,9 +433,20 @@ convenience layer over that contract. In brief: runs only at zero leases; heartbeats expire leases of dead clients. Idle timeout is **on** by default for library daemons, so a test run leaves no resident service behind. -- **Libraries never take over.** A library never sends `STOP` to an older - daemon. An incompatible daemon is treated as absent and a separate cohort - daemon is started. Takeover stays an MCP and operator action. +- **Takeover respects leases.** Stopping an app's daemon stops the engine of + every process of that app, so version takeover changes: no client, the MCP + included, sends `STOP` while another client holds a lease. Takeover only + ever happens between versions of the same app, for example during a rolling + update. A newer client + meeting an older daemon with live leases uses it if the protocol versions + are compatible, and fails with a typed error naming the version mismatch + otherwise. A library never takes over; an explicit operator stop still can. +- **One engine version per app.** Each app chooses and pins its own `hyperd`, + so apps never have to agree on one. Within an app, processes from different + releases may bring different builds; the Phase B revision defines which one + the app's daemon starts and how database file versions are handled across + an app update: a file upgraded by a newer engine may not open in an older + one. - **Protocol version.** The integer Phase S introduces (D7), added to the `PING` reply; clients support N and N-1. - **Surface.** `acquire(how, &Options) -> Result` and `acquire_async`, @@ -423,10 +460,11 @@ the direction. ## Open decisions for the maintainer -1. **Go / no-go on Phase B**, after Phase 0's numbers. Suggested bar: if a - release-mode `HyperProcess::new()` to first query is well under a second on - macOS and Linux, the sharing benefit is small for most users and Phase A is - the place to stop. +1. **Go / no-go on Phase B.** Not gated on startup time. Phase 0 measured + about 61 ms from spawn to first query (macOS arm64, `docs/BENCHMARK_GUIDE.md`), + so startup alone would not justify Phase B; sharing databases across the + processes of an application (Summary) is the reason, and the decision rests + on that. 2. **Timing of Phase A:** any time; there is no 1.0 deadline (finding 4). It can wait until after the Linux ARM work lands, which touches the same release plumbing.