Refuse writes when the database schema is ahead of the binary #2

Merged
kerryhatcher merged 22 commits from schema-compatibility-guard into main 2026-11-05 12:35:09 +00:00
Owner

Summary

Several peachmem servers share one Postgres database and migrate it at startup. A newer binary can migrate a database that older servers still hold open, and those servers would keep writing against the new schema.

This PR enforces one invariant: if the database schema is ahead of the binary, reads proceed and every write is refused, with a message telling the user to restart Claude Code.

  • schema::guarded_tx is the single write choke point. Inside each write's own transaction it takes sqlx's migration lock in shared mode and then checks the applied version, so a write either sees a committed migration or waits for it.
  • save_note, delete_note, and link_project each run in one transaction. Before this, a failure partway through save_note could leave a note inserted with unsynced links, projects, and paths.
  • The MCP server instructions carry a warning banner when writes are disabled.
  • A session worklog that hits a refusal is dropped with a log line instead of failing session start.
  • Startup: if a newer binary commits a migration between the version check and the migrator, the server now comes up read-only instead of exiting with no tools. A deterministic test reproduces the window. Found in review.
  • HANDOFF.md is removed. It was the resume guide for this branch and said to delete it on merge.
  • Version 0.4.0 (minor, because writes now return a different error). Published to the kerryhatcher registry from commit 63014de.

Points for review

  • The design spec's reasoning about transactional DDL is wrong under READ COMMITTED: a plain version read does not serialize against a running migration. The implementation takes sqlx's migration lock instead, and a test runs sqlx's own migrator against an open guarded write to check the lock key. The spec is not amended in this PR.
  • The refusal's fallback command (cargo install peachmem --registry kerryhatcher) now resolves to 0.4.0. It clears a refusal only while the database schema is at or below the binary's version. Once a migration 0005 exists, that fallback will need a newer release.
  • docs/pi-extension-plan.md is excluded from the crate package.

Verification

  • cargo test --features db-tests against the dev database on port 55433: 59 unit, 45 knowledge, 29 schema_guard, all passing.
  • Bare cargo test (no database): passing.
  • cargo clippy --all-targets --features db-tests: no warnings.
  • End-to-end over stdio against the dev database, with a forged future migration: the initialize result carries the banner, save_note is refused naming both schema versions, and list_notes succeeds.
  • Real database (port 5432), read-only: schema version 4, unchanged.
  • cargo fmt --check still fails, but only on code that predates this branch (config, knowledge, links, topic, tests/knowledge, worklog, and a few older hunks in projects and store).

Deviations from the plan

Recorded in the execution ledger during implementation. The main ones: link_project runs its whole resolution inside the guarded transaction, so a refused call creates nothing; the partial-write test injects its failure with a trigger, because no natural failure happens after the note row is written; and a few expected test counts in the plan were stale.

🤖 Generated with Claude Code

## Summary Several peachmem servers share one Postgres database and migrate it at startup. A newer binary can migrate a database that older servers still hold open, and those servers would keep writing against the new schema. This PR enforces one invariant: **if the database schema is ahead of the binary, reads proceed and every write is refused**, with a message telling the user to restart Claude Code. - `schema::guarded_tx` is the single write choke point. Inside each write's own transaction it takes sqlx's migration lock in shared mode and then checks the applied version, so a write either sees a committed migration or waits for it. - `save_note`, `delete_note`, and `link_project` each run in one transaction. Before this, a failure partway through `save_note` could leave a note inserted with unsynced links, projects, and paths. - The MCP server instructions carry a warning banner when writes are disabled. - A session worklog that hits a refusal is dropped with a log line instead of failing session start. - Startup: if a newer binary commits a migration between the version check and the migrator, the server now comes up read-only instead of exiting with no tools. A deterministic test reproduces the window. Found in review. - `HANDOFF.md` is removed. It was the resume guide for this branch and said to delete it on merge. - Version 0.4.0 (minor, because writes now return a different error). Published to the `kerryhatcher` registry from commit `63014de`. ## Points for review - **The design spec's reasoning about transactional DDL is wrong** under READ COMMITTED: a plain version read does not serialize against a running migration. The implementation takes sqlx's migration lock instead, and a test runs sqlx's own migrator against an open guarded write to check the lock key. The spec is not amended in this PR. - **The refusal's fallback command** (`cargo install peachmem --registry kerryhatcher`) now resolves to 0.4.0. It clears a refusal only while the database schema is at or below the binary's version. Once a migration 0005 exists, that fallback will need a newer release. - `docs/pi-extension-plan.md` is excluded from the crate package. ## Verification - `cargo test --features db-tests` against the dev database on port 55433: 59 unit, 45 knowledge, 29 schema_guard, all passing. - Bare `cargo test` (no database): passing. - `cargo clippy --all-targets --features db-tests`: no warnings. - End-to-end over stdio against the dev database, with a forged future migration: the initialize result carries the banner, `save_note` is refused naming both schema versions, and `list_notes` succeeds. - Real database (port 5432), read-only: schema version 4, unchanged. - `cargo fmt --check` still fails, but only on code that predates this branch (`config`, `knowledge`, `links`, `topic`, `tests/knowledge`, `worklog`, and a few older hunks in `projects` and `store`). ## Deviations from the plan Recorded in the execution ledger during implementation. The main ones: `link_project` runs its whole resolution inside the guarded transaction, so a refused call creates nothing; the partial-write test injects its failure with a trigger, because no natural failure happens after the note row is written; and a few expected test counts in the plan were stale. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Many peachmem servers share one database and migrations run automatically
on startup, so a newer binary migrates a database that older servers are
still holding open. Those servers keep serving pre-migration code against
a post-migration schema and keep writing. On 2026-08-12 the plugin cache
flipped 0.1.0 -> 0.3.0 while seven other claude processes were live.

The startup path already fails closed by accident: sqlx's
validate_applied_migrations raises VersionMissing, which connect()
propagates before serve() runs. An already-running server has no such
protection, and cannot get it from a startup check.

Design: one invariant -- schema ahead of binary means reads proceed and
writes are refused -- enforced by a guarded_tx() choke point that checks
the applied version as the first statement of the write's own
transaction. Postgres DDL is transactional, so that serializes against a
concurrent migration with no check-then-write race.

This requires save_note to become transactional (it currently fires ~10
independently-committing statements against the pool), which also fixes
a latent partial-write bug.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Nine tasks, each ending in an independently testable deliverable:
version detection, connect returning the status, the guarded_tx choke
point, the mechanical executor refactor, save_note becoming one
transaction, the remaining two write entry points, surfacing the refusal
through the MCP instructions, the quiet worklog path, and docs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Compares the migration set compiled into this binary against what the
database has actually applied. Compares max(version) rather than catching
sqlx's VersionMissing, which cannot tell 'schema is ahead' from 'a
migration file was deleted' and carries neither version number.
The plan mandated .unwrap_or(None), which turned every sqlx error into 0.
Since detect() computes applied > known, a database outage would have
reported Current -- safe to write -- at exactly the moment the guard
exists to prevent that. The WHERE to_regclass(...) IS NOT NULL guard was
also inert: Postgres resolves the FROM relation at parse time, so a
missing table errors before the guard runs.

Existence is now its own statement and every other error propagates.
Adds tests for the unmigrated-database case and for error propagation.

Found by the Task 1 review; ruled on by the repo owner.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
applied_version() swallowed every error from fetch_optional into a silent
0, so a real outage (connection drop, auth failure, timeout, pool
exhaustion) was indistinguishable from "no migrations applied" — which
detect() reads as SchemaStatus::Current, i.e. safe to write, at exactly
the moment the guard exists to prevent that.

Checks table existence in its own statement (to_regclass) and returns 0
only for that case; every other failure now propagates via ?. The old doc
comment's claim that a WHERE to_regclass(...) guard made a missing table
read as 0 was also wrong: Postgres resolves the FROM relation at parse
time and errors before that WHERE clause ever runs, so the 0-on-missing
behavior came entirely from the error swallow.

Adds coverage for both paths: an unmigrated database (sqlx::test with
migrations = false) reporting 0, and a closed pool propagating an error.
connect() now returns the compatibility status alongside the pool. When
the database has migrations this binary lacks, the migrator is not run at
all -- it would fail with VersionMissing, and a newer binary has already
applied what's needed. Returning Ahead rather than an error is what lets
the server come up read-only instead of leaving the session with no
memory tools.

Also updates worklog.rs's db::connect call site to destructure the new
tuple return, which is required for the crate to compile.
src/worklog.rs is the second db::connect caller and the tuple return is a
breaking change for it; the file list omitted it. Test count was stale
after two tests were added to Task 1.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Tasks 1-2 of 9 are complete and the work is paused. This points a fresh
agent at the ledger, plan and spec, names the resume point (Task 3, BASE
ba40b8a), and records what would otherwise have to be rediscovered: the
decisions already ruled on, the three plan defects found and fixed during
execution, and the two environment traps -- a running MCP server is frozen
at its starting binary, and config.toml points at the real 808-note
database on 5432 rather than the docker one on 55433.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous version pointed at .superpowers/sdd/…/progress.md as the
source of truth for progress. That directory is git-ignored by design (the
tooling writes a self-ignoring .gitignore there) and was never pushed, so
on any other machine the handoff referenced a file that does not exist.

Folds the ledger's surviving content inline: exact per-task state, the
commit map, what src/schema.rs and src/db.rs now expose, the test
inventory, the decisions already ruled on, the three plan defects found
during execution, and the one deferred minor.

Also makes the environment portable. Adds clone-to-green setup with the
raw commands for anyone without `just`, and replaces the versioned
superpowers script path with a discovery glob plus by-hand git equivalents,
so the plan can be executed without the plugin.

Reframes the database warning, which was machine-specific and misleading
elsewhere: PostgresConfig::default() is port 55433 matching
docker-compose, so a fresh machine is safe by default. The 5432 hazard was
a local customization of one machine's config.toml, not a project default.
The portable rule is to always pass DATABASE_URL explicitly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Reads the applied schema version as the transaction's first statement, so
the check and the writes that follow are one atomic unit -- Postgres DDL
is transactional, so a concurrent migration either commits before the
read or after the transaction ends and cannot interleave. Refused and Db
are distinct variants so a genuine database failure is never reported as
a version problem.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Mechanical refactor with no behavior change: multi-statement helpers take
&mut PgConnection, single-statement helpers become generic over
PgExecutor so read-path callers keep passing &pool. resolve_or_create_ref
and resolve_or_create_workspace no longer open their own transactions, so
project creation can join the caller's.

Groundwork for making save_note a single transaction.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
save_note previously fired ~10 independently-committing statements at the
pool, so a failure partway through left a note inserted with its links,
projects and paths unsynced. It is now one transaction obtained from
guarded_tx, which both fixes that partial-write bug and makes the write
impossible when the database schema is ahead of this binary.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Completes the write surface: save_note, delete_note and link_project are
now the only ways to write, and all three obtain their transaction from
guarded_tx. Adds a test asserting reads are deliberately unaffected.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
An agent otherwise only discovers the mismatch by having a write fail.
Prepending a banner to the server instructions at initialize means it
knows from the first turn and can tell the user to restart instead of
retrying. get_info's existing text is unchanged; it just moves to a
const.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
peachmem worklog writes through save_note and so hits the guard, but a
missing worklog must never disrupt session start. A refusal is logged and
swallowed; a genuine error still propagates.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Qualifies the existing 'migrations run automatically on startup' claim,
which is only safe because of the guard.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Pass &mut tx to the concrete &mut PgConnection helpers instead of &mut *tx,
as clippy's explicit auto-deref lint asks. Generic PgExecutor parameters
keep the explicit reborrow, which they need. Format schema.rs and the
schema guard tests, which this branch wrote. Remaining rustfmt diffs are in
code that predates the branch.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
The guard read the applied version under READ COMMITTED, which sees only
committed migrations. A write could therefore read the old version while a
migration was still running, block on the migration's table locks, and then
execute against the new schema. sqlx's migrator holds a session advisory
lock for the whole migration, so the guard now takes the same lock in
shared mode, for the life of the transaction, before reading the version.
A write either sees a committed migration or waits for it to finish.

The lock key mirrors sqlx-postgres's generate_lock_id. A test checks it by
running sqlx's own migrator against an open guarded write, so a key mismatch
would fail the suite rather than go unnoticed.

Also: a failed rollback no longer replaces the restart message; write
helpers are crate-private; tests now assert the rollback of paths and
projects, the foreign-key failure, and reads while the schema is ahead.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
The write guard changes what writes return when the database schema is
ahead of the binary, and adds a warning to the server instructions. That is
a behavior change, so this is a minor bump under the repo's convention.

Cargo.toml, Cargo.lock, plugin.json, and .claude-plugin/plugin.json move
together, as in the 0.3.0 bump.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
docs/pi-extension-plan.md is a working draft, not part of this crate, and it
is untracked, so cargo would otherwise package it. Excluding it keeps the
published crate to the code and its documentation.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
prepare checked the applied version, then ran the migrator. A newer binary
could commit a migration between those two steps. The migrator then failed
with VersionMissing, and the server exited with no memory tools at all.

If the migrator fails, prepare now re-checks the version. A schema that is
now ahead comes up read-only, as the design intends. Any other error still
propagates.

The new test reproduces the window: it holds the migration lock, lets prepare
detect the current schema and block on the lock, then commits a newer
migration. It failed with "migration 5 was previously applied but is missing"
before the fix.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
HANDOFF.md was the resume guide for this branch and said to delete it once
the branch merged. It also described a latch that was never built.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
kerryhatcher/peachmem!2
No description provided.