Skip to content

fix(migrations): make per-database upgrades safe to run concurrently - #532

Merged
fazpu merged 4 commits into
mainfrom
fix/per-database-upgrades
Nov 6, 2026
Merged

fazpu merged 4 commits into
mainfrom
fix/per-database-upgrades

Conversation

@fazpu

@fazpu fazpu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

UMC relaunch plan phase 2 item (h), "Upgrades per database, in parallel, no machinery." Migrations must be safe to run against each Project database independently and concurrently. An operator loops over databases, and no rollout runner is built here (that is a deferred ticket).

Audit: what a migration or setup shares across databases

  • Roles are cluster-global.
    • rememberstack_query_<db> (p9_02_0023) and rememberstack_graph_<db> (p9_17_0038) are per database, so nothing races. They are, however, subject to 63-byte truncation (see fix 2).
    • rememberstack_view_owner (p9_02_0023) is shared. Its IF NOT EXISTS … CREATE ROLE raced: two first migrations at once both see it missing, and the second fails with unique_violation on pg_authid. I reproduced this in the new test.
  • Advisory locks (p9_38_0059 pg_advisory_xact_lock) are database-scoped, so they need no change.
  • Extensions and pg_partman are per database. The pg_partman_bgw.dbname server setting must list every database, so that is documented.
  • setup:
    • ALTER ROLE … PASSWORD targets the per-database query role.
    • ensure_bucket already tolerates BucketAlreadyOwnedByYou.
    • The deployment bootstrap is per database.

Fixes

  1. create_role_if_absent_sql wraps CREATE ROLE in EXCEPTION WHEN duplicate_object OR unique_violation THEN NULL. Editing the old migration body is safe: databases that already ran it are unaffected, and new ones get the safe form. Alembic runs a whole upgrade in one transaction, so a concurrent first migration waits for the first one's commit and then proceeds.
  2. migrations/env.py refuses a database name longer than 43 bytes (63 − len("rememberstack_query_")). PostgreSQL truncates role names at 63 bytes, so two long database names with the same prefix would share one query role. That role would then get CONNECT and view grants on both databases, which breaks isolation.

Docs

  • Upgrades page: new section Several deployments on one PostgreSQL server. It covers the loop (docker run --env-file … setup & per deployment, then wait) and the three shared things: the name limit, the shared role, and pg_partman_bgw.dbname.
  • Packaging design §6 records the rule. llms-full.txt is regenerated.

Tests (src/tests/spine/test_per_database_migrations_pg.py, PG 19 Beta 3)

  • A concurrent shared-role creator. It waits on a lock, then succeeds. I checked that it fails with the old SQL (UniqueViolation).
  • Two fresh databases, migrated by two alembic upgrade head processes at once, both reach head and get distinct roles.
  • A 44-byte database name is refused.

For the UMC runtime: Project database names must be at most 43 bytes.

Checks

  • ruff, ruff format, pyright on the changed files; docs truth and llms check
  • The new tests (3 passed)
  • CI (all checks green)
  • Codex review: round 2 APPROVE

🤖 Generated with Claude Code

https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm

fazpu and others added 3 commits November 6, 2026 16:31
Deployment databases on one server share only cluster-global roles.

- The shared rememberstack_view_owner role is now created tolerating a
  concurrent creator (duplicate_object/unique_violation swallowed), so
  first migrations of several databases at once no longer fail.
- Migrations refuse a database name longer than 43 bytes: the per-database
  roles rememberstack_query_/graph_<database> would be truncated at 63
  bytes, and two databases could share a role and its grants.
- The upgrades page documents how an operator loops setup over databases,
  and the three shared things (name limit, shared role,
  pg_partman_bgw.dbname); packaging design §6 records the rule.
- Tests: a concurrent shared-role creator, two databases migrated by two
  processes at once, and a too-long name refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
Codex round 1: role names are unquoted, so PostgreSQL lowercases them;
two databases differing only in case shared one query role. Database
names must be 1-43 characters of [a-z0-9_], not starting with a digit.
The operator loop now reports a failed run, and the docs say first-time
shared-role creation can make one upgrade briefly wait for another.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 1 (gpt-6.1-sol, max effort)

VERDICT: REQUEST_CHANGES

  1. Major — Short database names can still share a query role. p9_02_0023_query_space_roles.py:95 checks the exact name but executes unquoted CREATE ROLE, which folds ASCII uppercase to lowercase. The preflight:58 permits both names. I reproduced two databases differing only by case migrating through 0023 with one query role holding CONNECT on both. Advancing the mixed-case database then fails in 0024 with UndefinedObject. This is an audit gap beyond truncation. Simplest fix: extend the existing preflight with a documented lowercase, identifier-safe naming rule; add this regression test.

  2. Minor — The operator loop hides failed upgrades. upgrades/page.mdx:125: bare wait returns zero even when every background job fails; set -e does not fix that. Simplest fix: collect each PID and check each wait "$pid", or show a sequential loop with docker run … setup || exit 1.

  3. Minor — “Never wait” is inaccurate. upgrades/page.mdx:112 contradicts the shared-role creation behavior described below it. A concurrent creator waits until the winning upgrade transaction finishes. Simplest fix: say upgrades run independently but can briefly wait during shared-role creation. Regenerate llms-full.txt with both documentation corrections.

Otherwise, the nested exception handler is correct, the rollback before Alembic configuration correctly restores transaction ownership, and 43 = 63 − 20 fits both role prefixes. I found no additional shared-state races in the migrations or setup path; graph memberships, password provisioning, and existing bucket guards are adequate with distinct role names. The image entrypoint accepts setup; the pg_partman comma-list documentation is accurate.

The three new tests and 36 related tests passed. Additional checks confirmed a 43-byte multibyte name reaches head and a 44-byte name fails before schema changes. The deterministic race test is useful; the missing case-pair test matters. The isolated PostgreSQL container was removed, and the worktree remains unchanged.

Disposition (Claude): all three accepted

  1. Database names must now be 1 to 43 characters of [a-z0-9_], not starting with a digit. A test case covers an upper-case name; that case and the 44-character one now also check that no schema was created.
  2. The loop collects PIDs, waits for each, and exits non-zero if any run failed.
  3. The docs now say one upgrade can wait for another while the shared role is first created. llms-full.txt is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Codex review round 2 (gpt-6.1-sol, max effort)

VERDICT: APPROVE

  • Minor, nonblocking — Graph role described as a login role. upgrades/page.mdx:142 calls both roles “login roles,” but the graph migration:1067 creates its role with NOLOGIN. Simplest fix: remove “login” and regenerate llms-full.txt.

No blocker or major findings. All three round-1 findings are fixed; none were declined. I found no additional unsafe shared state or races across databases in the migration chain or SelfHostProfile.setup.

The nested exception handler preserves the surrounding transaction. The preflight rollback correctly restores Alembic’s transaction ownership. With names restricted to ASCII, 43 = 63 − 20 fits both role prefixes exactly. Password provisioning targets distinct roles, graph memberships remain separate, and bucket creation already handles concurrent creators.

The Docker command matches the image entrypoint. The loop checks every PID and reports failures; the shared-role wait description is accurate. The comma-separated pg_partman_bgw.dbname setting matches upstream documentation.

The new tests meaningfully cover lock contention, concurrent upgrades, and rejection before schema changes. 56 tests passed, plus manual boundary, transaction, and shell-loop checks. Lint, formatting, types, and documentation checks passed.

The isolated PG 19 Beta 3 container was removed. No files were modified.

Disposition (Claude)

The minor finding is fixed in the latest commit, a docs-only wording change ("its own roles").

@fazpu
fazpu marked this pull request as ready for review November 6, 2026 16:36
@fazpu
fazpu merged commit 6fd48cc into main Nov 6, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant