Skip to content

feat(tenancy): PostgreSQL backup and restore with a replay gate - #200

Merged
Yoshiofthewire merged 2 commits into
masterfrom
feat/tenancy-pg-backup
Nov 25, 2026
Merged

Yoshiofthewire merged 2 commits into
masterfrom
feat/tenancy-pg-backup

Conversation

@Yoshiofthewire

@Yoshiofthewire Yoshiofthewire commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

In one line: Multi mode gets a PostgreSQL backup and restore with no 256 MiB limit. Any restore now keeps every customer org unserved until erasures and org deletions since the backup have been replayed.

What changed

  • kynotes-server pg-backup --out FILE writes a sealed archive of the whole database, taken from one consistent snapshot. The blob rows (the object references) come from the same instant as the notes.
  • kynotes-server pg-restore --in FILE --confirm-stopped loads an archive into a new, empty database in one transaction, together with the existing restore fence. Either all of it loads or nothing does.
  • Every restore (this one and prepare-postgres-restore) writes a replay gate. While the gate is set, no customer org serves: sessions, devices, share links, reminders, GC and the orphan sweep all wait.
  • The elected worker lifts the gate only once the org and erased-subject feeds, read from zero, have nothing more. The deleted orgs are then purged again.
  • Multi startup stays refused.

Review this

  • internal/storage/pg_archive.go RestorePostgres / clearFreshTarget: it disables user triggers during the load (foreign keys stay checked). It also decides which targets count as empty; this is the guard against overwriting a live database.
  • internal/storage/orgs.go OrgServes: the gate is added to the one SQL predicate behind every credential check. The staff org is exempt.
  • internal/httpapi/erased_feed.go FinishRestoreReplay: lifts the gate only when both feeds are empty past cursors that didn't move.
  • Safe to skip: docs, and the CLI flag parsing.

Checked: full race suite, FIPS suite and the PostgreSQL 17 CI suites, rerun after the rebase and after the Guide fix (results below). Also vet, gofmt, actionlint, govulncheck, no-binaries, strong-crypto Compose, and the docs book (287 links). 11 mutations each fail their test (below).
Not checked: a real multi-GB archive; memory is bounded by 1 MiB frames, but not measured. There's no blob-coverage check after a restore; RESTORE.md says so. go mod tidy -diff lists stale go.sum lines that are already on master and untouched here.

Decided for you: for open question 3 I built a logical COPY archive rather than base backup plus WAL. It needs no PostgreSQL tooling or superuser on the host, round-trips in CI, and has no capsule limit. A host that runs its own PITR still restores through prepare-postgres-restore, which now writes the same gate. The backup key is an operator file of 64 hex characters, KYNOTES_PG_BACKUP_KEY_FILE.

You need to: nothing for merge. The object-storage destination and schedule binding come with startup binding.

Detail

Archive. One JSON header line (format, schema version, DB time, tables with columns in foreign-key order). Then each table's COPY ... TO STDOUT rows, each table ended by \.. Then a trailer with row counts and sequence values. Sealing: HKDF-SHA256 with a per-archive salt, 1 MiB AES-256-GCM frames via NewGCMWithRandomNonce (FIPS-approved). The associated data binds magic, salt, frame index and the final flag.

Restore. The target must be just created: only the migration and ensureOrgs seed rows. Those are deleted. The schema version must match. User triggers go off for the load (the org-usage triggers would otherwise count twice) and come back on before the fence. Row counts are checked against the trailer, and sequences are set.

Cells (C5). The archive's object-storage prefix becomes cell-scoped when the destination lands, alongside OrgPrefix. The gate needs no change: it follows OrgServes, which becomes a membership test against the cell list.

Tests (PostgreSQL)

  • TestPostgresArchiveRoundTripsEveryRow: all 45 tables byte for byte, with COPY escapes (including a value containing a \. line), NULLs and the sequence. Triggers are back on. The test names the 7 tables it leaves empty, so a new table gets noticed.
  • TestPostgresArchiveRestoreIsAllOrNothing: truncated, no trailer, extra data, other schema, wrong row count, a failing fence, and a target that holds data. Each changes nothing.
  • TestPostgresArchiveIsOneSnapshot
  • TestSealedArchiveRefusesEveryChange: wrong key, bit flip, swap, drop, early final, cut, extension.
  • TestPostgresBackupRestoresFencedAndGated
  • TestRestoreAfterPurgeReplaysBeforeServing
  • The gate case in TestStoppedOrgIsRefusedOnEveryCredential (session, device, sealed link, page link).
  • TestPostgresArchiveCommandRefusesBadInput

Mutations (each fails, PG17 on kjob k82):

  • gate ignored in OrgServes
  • gate lifted without reading the org feed
  • gate lifted without reading the erased feed
  • no gate written
  • triggers left on during the load
  • READ COMMITTED instead of one snapshot
  • fence error ignored
  • row counts unchecked
  • target emptiness unchecked
  • no frame index in the AAD
  • no final flag in the AAD

The unmutated run passes.

Commands
Head 3d174e5, rebased onto master eba624a (which includes #199 and #201). The only conflict was the two new command cases in cmd/kynotes-server/main.go; both are kept.

  • 3d174e5 fixes the Reviewer Guide finding "Unstable ordering" from 6310b8e. Names and parent lists are sorted before the topological walk. TestArchiveTableOrderIgnoresCatalogOrder fails with either sort removed (2 mutations) and passes with the fix.
  • At 3d174e5: PG17 storage/httpapi plus backup/cmd suites exit 0 on kjob k82; internal/storage race, normal and FIPS, pass.
  • At 6310b8e (same code except the ordering fix): race and FIPS, both CI halves, exit 0 on k82, k81, k80 and Major. The PG17 suite on k83 failed once in TestServeOwnsAdminSocketLifecycle, a 5-second wait for the admin socket in code this PR doesn't touch, with httpapi running alongside. internal/app alone then passed on PG17 (k82), with that test passing 5 of 5 repeats. GitHub's postgres job passed.

Earlier runs, at dddd63a:

  • go test -race -count=1 -timeout 20m -p 2 ./..., both CI halves (-run=^Test[A-M], -skip=^Test[A-M]), normal and GODEBUG=fips140=on: exit 0 on Major (kjob fell back while every K host was busy).
  • PostgreSQL 17 CI suites (storage, httpapi, auth, app, sso, orgsync, worker, blobstore, mcp; then backup/cmd ^(TestPostgresRestore|TestPostgresBackup|TestStaffUserCommand)): exit 0 against my own throwaway postgres:17-alpine on Major, because every K host was busy. Before the rebase the same suite passed on kjob k81.
  • An earlier unsplit make test on k80/k82 hit the 20-minute package budget in internal/httpapi (the test running at the timeout had been going for 2 s). The same package split into CI's two halves passes in both profiles, and CI splits it the same way.
  • Mutations: kjob k82, PG17; 11 of 11 killed, the unmutated run passes.
  • vet, gofmt, actionlint, govulncheck ("No vulnerabilities found"), scripts/check-no-binaries.sh, docs/check-strong-crypto-compose.py, mdbook build docs plus docs/check-links.py (287 links): pass.
  • GitHub CI at 3d174e5: 13 checks pass, publish/promote skip. Security reviewer cleared; Reviewer Guide reports no major issues.

🤖 Generated with Claude Code

@Yoshiofthewire

Yoshiofthewire commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵

🧪 PR contains tests

⚡ No major issues detected


Advisory only: this comment never gates the pull request.
gpt-6.1-sol using pr-agent on behalf of Yoshi

@Yoshiofthewire

Yoshiofthewire commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Security review - cleared

Detail withheld: this repository is public, and posting an unfixed finding here would be public disclosure. The full report was posted to the hand-off board at https://myslop.urlxl.us/f/pr-reviewer-busnes-app-kynotes-server-200, where it is readable by the operator and expires seven days after the last post.


gpt-6.1-sol using security-audit on behalf of Yoshi

@Yoshiofthewire

Yoshiofthewire commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Autonomous review - 1/1 personas cleared

  • security: cleared

Merging remains a human decision; this bot never approves.


gpt-6.1-sol using security-audit on behalf of Yoshi

pg-backup streams every table by COPY from one REPEATABLE READ snapshot
into an archive sealed in 1 MiB AES-256-GCM frames under an operator key
file. The blob rows in it are the object references of the same instant.
pg-restore loads it into a just-created database in one transaction,
user triggers off and foreign keys on, with the restore fence.

Every restore now writes a replay gate. OrgServes refuses each customer
org until the elected worker has read the org and erased feeds from zero
and found nothing more, so erasures and org deletions since the backup
are applied before anyone is served.

Multi startup stays refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The foreign-key query had no ORDER BY, so a table with several parents
could be laid out in another valid order on the target than on the
source, and the restore, which compares table lists position by
position, would refuse a good archive. Names and parent lists are now
sorted before the topological walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Yoshiofthewire

Copy link
Copy Markdown
Member Author

Reviewer Guide finding "Unstable ordering" (head 6310b8e) is fixed in 3d174e5. The foreign-key query now has ORDER BY, and orderTables sorts the table names and each parent list before the topological walk, so the archive layout depends on the schema alone. The regression test TestArchiveTableOrderIgnoresCatalogOrder gives the same foreign keys in two different catalog orders and expects one layout. It fails when either the parent sort or the name sort is removed (both mutations checked), and passes with the fix.

🤖 Generated with Claude Code

@Yoshiofthewire
Yoshiofthewire merged commit e675d5b into master Nov 25, 2026
15 checks passed
@Yoshiofthewire
Yoshiofthewire deleted the feat/tenancy-pg-backup branch November 25, 2026 06:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant