Files
Atrium/deploy/RUNBOOK-one-account.md
adminandClaude Opus 5.5 b690e26de6 Retire Workflow (compass); Arbiter from its own repository
Workflow is removed from the kit: compose, init/push/preflight, front door,
catalogue seed, console, docs and tests. Revision 0014 deletes the compass
catalogue row (assignments and access requests cascade) and its
module_permission rows, with audit entries. Arbiter is now built from
deploy/modules/arbiter (Alpaq92/Arbiter); the submodule itself is added by
a separate commit once that repository exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:37:18 +01:00

75 KiB
Raw Permalink Blame History

Runbook — one account for the whole platform

Written for the Caddy release. Since the front door (RUNBOOK-front-door.md) there is no caddy service, no deploy/Caddyfile and no caddy_data volume: atrium-backend publishes :80, and each module stamps its own headers. Read every Caddy step below as history; the account merge itself is unchanged, and restart caddy / --force-recreate caddy have no equivalent now (recreate atrium-backend instead).

Who needs this. Only an EXISTING standalone deployment: four apps that each already own their accounts — a box installed before one account became the kit's default, or one installed with ./init.sh --standalone — whose people have to be merged into one account each. A fresh install does not: init.sh writes one account by default and the first ./push.sh builds it from an empty database in the right order — provision every app, then Atrium's 0004, then each module's cutover revision, each with nothing to move (deploy/README.md, "One account (the default)"). The live box described below has already been through this, on 2026-10-01; the runbook stays for the next standalone box, for the rehearsal it describes, and because its rollback (section 10) is the only record of how to undo it.

What this does. Today the live box runs four apps at one origin, and each one keeps its own app_user table. There are four rows spelled admin@example.com, and they are four different people who happen to share an email address — which is why opening Galena from Atrium still asks for a password. After this runbook there is one account per person, in one neutral schema every module reads, and signing in at /atrium signs you in everywhere.

How little the mechanism is. One origin, one cookie, one session row. There is no token handoff, no signed assertion, no audience binding and no redirect dance, because there is nothing cross-origin to bridge. If a step here looks like it is inventing a protocol, it is the wrong step.

Box: deploy@185.252.234.165, kit at /srv/atrium, deploy dir /srv/atrium/deploy, compose project dredd-family. <SITE> = http://dredd.185.252.234.165.sslip.io.

This runbook covers Atrium's half, which is the half that must go first: it creates the shared tables and grants every role its tier. The three modules move their own rows in their own phase, from their own repositories, and section 7 says exactly what they must do and why they cannot do it alone.

One thing here is not Atrium's alone, and it is the step people get wrong: section 3 provisions all four apps, as the platform admin. That is not the modules' phase arriving early — provisioning is the platform admin's job for every app, it needs nothing from the module repositories, and Atrium's own migration cannot finish without it, because it grants each module's role a tier inside a schema that role cannot yet see.


0. Read before you start

0.1 What this does to the four admin@example.com rows — the whole answer

row what happens to it when
atrium.app_user Survives, UUID and all. It is copied into dredd.app_user unchanged; its password becomes the one platform password. section 5 (this runbook)
galena.app_user Matched to the survivor by lower(email), its id replaced by the survivor's everywhere Galena references it, then the local table is dropped. Galena's own cutover revision
sygna.app_user The same. Sygna's own cutover revision
counsel.app_user The same. Counsel's own cutover revision

Nothing is renumbered in Atrium. Keeping the survivor's UUID is the reason: all fourteen foreign key columns in the atrium schema that name a person — audit_log.actor_id, node.owner_id, node.personal_owner_id, app_setting.updated_by, permission_grant.created_by, favorite.user_id, module.created_by, module_assignment.user_id / .created_by, access_request.user_id / .decided_by, and session.user_id — keep the values they have. Only the constraint changes, from atrium.app_user(id) to dredd.app_user(id). No audit row changes its actor, and no permission grant changes hands.

In the modules it is the other way round, and that is why their revisions are the risky ones: every id that named a module-local account is rewritten to the survivor's. Two things the database will not warn about, so each module's revision must handle both explicitly:

  • permission_grant.principal_id carries no foreign key — it is polymorphic on principal_type — so a missed row silently grants nobody anything. dredd-core ships permission_grant_orphans_sql, which counts and raises inside the same transaction. Use it.
  • composite keys can collide when two rows merge into one person: favorite(user_id, node_id) is a primary key, Galena's notification_pref(user_id) is a primary key, Sygna's rate.user_id is UNIQUE. De-duplicate before the repoint commits.

A fresh install behaves identically, by construction rather than by a second code path: 0001 still creates the three tables in the app's own schema, 0004 still moves them. There are simply no rows to move — which is why a fresh install from this kit needs none of this runbook: its first push runs exactly sections 3, 5 and 7 in order, against an empty database, and logs moved 0 account(s).

0.2 Sessions are carried over, deliberately

Atrium's live session rows move with the accounts, and the cookie is renamed (atrium_session → dredd_session) without signing anyone out: the hub keeps reading the old name as well, for as long as that browser holds it, because the row behind the token is the same row either way and only the label on the jar changed. It is self-clearing rather than time-limited — the old cookie is deleted at that person's next login or logout — so an administrator who never signs out during the cutover simply carries on, which is the point: they are the person who would otherwise be locked out halfway through the one change they cannot half-finish.

One consequence to be aware of when the modules follow: a module's existing login session becomes a platform session once its rows merge. That is correct — it is the same person, and one account is the point — but it is a widening of an existing credential, so it belongs in the module's own review, not smuggled past it.

0.3 Three commands that must never be run in /srv/atrium/deploy

Never Why
./init.sh --force Regenerates POSTGRES_PASSWORD, all eight role passwords, Sygna's SECRET_KEY and Galena's ENCRYPTION_MASTER_KEY. The ENCRYPTION_MASTER_KEY part is unrecoverable. Nothing here runs init.sh in any form.
docker compose down -v Deletes pgdata, galena-data, sygna-data, caddy_data and caddy_config together.
docker compose restart caddy restart keeps the container's creation-time environment. Always up -d --force-recreate caddy.

0.4 And one more, specific to this change

alembic downgrade is not a rollback here. Once accounts are merged there is no mapping back: the information about which row each person used to be is gone, deliberately. Revision 0004 refuses to downgrade while IDENTITY_SCHEMA is set, and it refuses on purpose — a downgrade that dropped the shared tables would take every module's identity with it. The rollback is the dump from section 1. If you are not willing to take that dump, you are not ready to run section 5.


1. Back up, and rehearse on the copy

export SITE=http://dredd.185.252.234.165.sslip.io
export BK="$HOME/dredd-backup-one-account"
cd /srv/atrium/deploy
install -d -m 700 "$BK"

1.1 The images have to carry the code this runbook describes

Every command below is docker compose run --rm <app>-migrate, which runs whatever image was last built on this box. The cutover revisions — Atrium's 0004/0005 and each module's — do not exist in the images running there now, so without this step section 5 reports that there is nothing to upgrade and every later section has nothing to confirm. This is deploy/README.md §11 up to and including its build, and deliberately not its ./push.sh or its docker compose up -d: the cutover has an order, and section 3 is the start of it.

cd /srv/atrium
git pull && git submodule update --init --recursive    # the modules move to the commits Atrium pins
cd /srv/atrium/deploy
bash preflight.sh
read -rs DREDD_CORE_TOKEN && export DREDD_CORE_TOKEN    # the private core is a BuildKit build secret
docker compose build
unset DREDD_CORE_TOKEN

Nothing is recreated by a build, so the site stays up on the old images and the new ones are used the first time something runs from them — which is section 3, deliberately, and not before. If the build cannot reach dredd-core, stop here: a half-built set of images is the one state from which none of the messages below mean what they say.

A dump of the whole database, taken with the backends stopped so it describes one instant:

docker compose stop atrium-backend galena-backend sygna-backend counsel-backend
docker compose exec -T postgres pg_dump -U postgres -d dredd --format=custom > "$BK/dredd.dump"
docker compose start atrium-backend galena-backend sygna-backend counsel-backend
ls -l "$BK/dredd.dump"          # expect tens of MB, not zero

Rehearse the whole of sections 3–6 on a restored copy of that dump before touching the live database. Restore it into a throwaway database on the same server, point a scratch MIGRATION_DATABASE_URL at it, and run the sequence end to end including section 8's proof. The cost is an hour; the alternative is finding out about a missed foreign key with the platform down.

Then run section 10 on the copy as well, and run section 8 again afterwards. The rollback is the half nobody rehearses, because it is the half you hope not to need — and it is the only part of this runbook that is ever run under pressure. It is also where an unrehearsed instruction hides longest: §10.1 is one flag that restored every schema to the wrong owner, without an error, on a rehearsal that had never been done.


2. The census — run it before anything else

This is the one command that tells you whether the assumption behind every table above is true. Run it as the platform admin (it is the only role that can read all four schemas):

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
SELECT 'atrium'  AS schema, id, email, full_name, is_admin, is_active FROM atrium.app_user
UNION ALL SELECT 'galena',  id, email, full_name, is_admin, is_active FROM galena.app_user
UNION ALL SELECT 'sygna',   id, email, full_name, is_admin, is_active FROM sygna.app_user
UNION ALL SELECT 'counsel', id, email, full_name, is_admin, is_active FROM counsel.app_user
ORDER BY 2, 1;
SQL

Read it, do not skim it. Three things decide what the rest of this runbook costs:

  1. Emails that appear in one schema and not in Atrium's. Each one is an account that has to be imported by hand in section 6, because neither side can do it alone (see there for why). Sygna's seed creates a demo adwokat@example.com in addition to its bootstrap admin — Anna Wiśniewska, the responsible lawyer on one of the two demo matters.

    The decision on record used to be to drop that account. It has been reconsidered: import it, and deactivate it. Dropping it is not one DELETE. Six columns in sygna name her, and the foreign keys refuse the row until every one of them is dealt with: the responsible lawyer comes off a matter, the owner off its deadline and the attendee off a hearing, her time entries are deleted outright — billable minutes, and time_entry.invoice_id means some of them may already be on an invoice — and audit_log.actor_id is rewritten to NULL, which turns "Anna did this" into "somebody did this" in a table the whole design treats as append-only. A law firm may be required to keep exactly that. An imported-and-deactivated account cannot sign in, costs one row, keeps every one of those references intact, and is reversible with one UPDATE if the firm ever wants her back. Section 6 has both branches in full, and says which is which.

  2. The same email with different full_names. Harmless — one name wins, and you can correct it in the pane afterwards — but decide which, now, rather than discovering it later.

  3. is_admin = true in a module schema, on anyone other than the survivor. Those people are moderators of that module after the cutover, not administrators of the platform. That is section 9, and it is a hand-grant, not a migration: only Atrium's roles may write the moderator table, and only each module's migrator can read that schema's pre-merge is_admin. Neither side can do it alone, which is the same shape as section 6.

If the census shows nothing but the four admin@example.com rows plus Sygna's demo account, the answer to 2 and 3 is "nothing to do" and section 9 is a no-op. That is the outcome to hope for, and the census is what tells you whether you got it. Section 6 is not a no-op even then: that demo account is exactly the case it exists for, and Sygna's own revision refuses by name until it has been dealt with — shared identity: adwokat@example.com exists in sygna but not in dredd, with alembic_version left at 0002 and nothing committed.


3. Provisioning — all four apps, as the platform admin, before any migration

The schema, its owner, REVOKE … FROM PUBLIC, the USAGE each app's roles hold on it, and the eight roles' search_path are provisioning, not migration, and this is not a style preference. Alembic runs as atrium_migrator, which is created NOCREATEROLE and holds no CREATE on the database, and ALTER ROLE <other> SET search_path needs superuser or CREATEROLE with ADMIN on that role. A migration cannot do any of it. Only the platform admin can.

3.1 Why all four, and why now

Because Atrium's own migration grants the reader tier to every role named in IDENTITY_READER_ROLES — and a role can be granted nothing inside dredd until it holds USAGE on dredd, which comes from its own app's provisioning run and from nowhere else. Provision Atrium alone and section 5 stops dead:

M: shared identity grants: galena_app has no USAGE on schema dredd
H: USAGE on the identity schema comes from provisioning, not from here: re-run that module's
   provisioning with --identity-schema, as the platform admin.

That failure is safe — the revision is one transaction, so nothing is committed, alembic_version stays at 0003 and dredd holds no tables — and the way out is this section, run for the app the message names, followed by section 5 again. It is also entirely avoidable, and this ordering is how: provision all four, then migrate.

None of this needs the module repositories to have changed anything yet. Provisioning is driven entirely by flags, and --identity-owner atrium_migrator tells each run "this schema belongs to somebody else, so only ask for USAGE on it" — the schema itself is created by Atrium's run, the one whose own migrator owns it. What the modules still owe is the committed rendering, and section 7 says why that matters later.

3.2 The four commands

All from Atrium's image, which is the only one the admin URL is handed to (deploy/push.sh calls that service the provisioner). The flags per app are the ones in that app's own db/managed/provision.sql header, plus the two identity flags:

cd /srv/atrium/deploy
# The admin URL lives in deploy/db.env, which Compose never reads; `-e NAME` hands the value from
# this shell to the container without putting it on a command line. Nothing prints it.
export LOCAL_DB_ADMIN_URL=$(sed -n 's/^LOCAL_DB_ADMIN_URL=//p' db.env | tail -n 1)
run() { docker compose run --rm -e LOCAL_DB_ADMIN_URL --entrypoint python atrium-migrate \
          -m dredd_core.managed provision \
          --admin-url LOCAL_DB_ADMIN_URL --identity-schema dredd --identity-owner atrium_migrator "$@"; }

# Atrium first: its migrator OWNS dredd, so this run is the one that creates the schema.
run --schema atrium  --app-role atrium_app  --migrator-role atrium_migrator
run --schema galena  --app-role galena_app  --migrator-role galena_migrator  --extension pgcrypto
run --schema sygna   --app-role sygna_app   --migrator-role sygna_migrator
run --schema counsel --app-role counsel_app --migrator-role counsel_migrator --extension pg_trgm

No --*-password-env here, and that is allowed: a password is read only to CREATE a role or, with --reset-passwords, to change one, and these eight roles already exist. Each run prints no password given: both roles must already exist, and keep the passwords they have, then <role> exists (password left unchanged) for both. Do not add --reset-passwords: it would change passwords the env files still carry the old ones of, and it needs both flags anyway. (If a role were somehow missing, the run refuses by name — role X does not exist yet: a password is needed to create it (--app-password-env …) — and commits nothing, so a mistake here costs one message, not a half-provisioned schema.)

./push.sh does not replace this, because the cutover has an order this section is the start of and the push has no way to know where in it you are. What the push must not do is undo it, and after this section it will not: PLATFORM_IDENTITY_SCHEMA=dredd in deploy/db.env (section 4) makes every one of its runs carry these same two flags, in the drift check of step 1 and the provisioning of step 2 alike. Set it, because a provisioning run without the flags is not a no-op — it rewrites the role's search_path to <slug>, extensions, dropping dredd, and grants no USAGE on it, which is the cutover undone by a routine deploy with no error anywhere. The push refuses outright when an env/<app>.env names a shared identity schema and deploy/db.env does not, so the dangerous half of that mistake cannot be made quietly.

The other half is the committed db/managed/provision.sql in each module (section 7): step 1 of the push compares each checkout's file with what dredd-core renders with the flags the push is about to provision with, so once PLATFORM_IDENTITY_SCHEMA is set, a module still shipping the standalone rendering is reported stale — correctly, because that file and the run would then disagree. Re-render it; the push prints the exact command when it stops.

Expect result: DONE, committed from each run, and from Atrium's, among the steps:

schema dredd, owned by atrium_migrator: CREATE SCHEMA IF NOT EXISTS dredd AUTHORIZATION atrium_migrator
schema dredd: nothing for PUBLIC
schema dredd: USAGE for atrium_migrator and atrium_app
search_path of atrium_migrator: ALTER ROLE atrium_migrator SET search_path = atrium, dredd, extensions
search_path of atrium_app:      ALTER ROLE atrium_app      SET search_path = atrium, dredd, extensions

and from each module's run, the same thing for its own two roles — this time on a schema that already exists, so USAGE and the search_path rather than a CREATE SCHEMA:

schema dredd: USAGE for galena_migrator and galena_app
schema dredd: check that the USAGE grant took
search_path of galena_migrator: ALTER ROLE galena_migrator SET search_path = galena, dredd, extensions
search_path of galena_app:      ALTER ROLE galena_app      SET search_path = galena, dredd, extensions

The order atrium, dredd, extensions is not negotiable, and the app's own schema must stay first — otherwise alembic_version, the enum types and every new table would land in a schema atrium_migrator does not own. The entire cost of that correct choice is one failure mode: an unqualified app_user resolves to a local copy if one exists. Section 8 is how you prove there is not one.

Each run also opens with a [WARN] about the admin URL's own TLS:

  [WARN] admin URL, TLS (client): the URL sets no sslmode: pg8000 then tries TLS without verifying …

and still ends result: DONE, committed (0 warnings). Both are correct and they are not in conflict: the link is a loopback inside the Compose network, and the count at the end is of warnings raised by the steps, not of every line that carries the word. It is worth knowing only because a [WARN] in the first command of a cutover is exactly the sort of thing that makes somebody stop and ask.

It is idempotent. Re-running any of the four changes nothing.


4. The settings

Edit deploy/env/atrium.env (mode 600; the *.example templates carry every key, so set_key would accept them too):

key value
IDENTITY_SCHEMA dredd
SESSION_COOKIE_NAME dredd_session
IDENTITY_READER_ROLES galena_app,sygna_app,counsel_app
IDENTITY_MIGRATOR_ROLES galena_migrator,sygna_migrator,counsel_migrator
MODULE_EVENT_EMITTER_ROLES galena_app,agora_app,parafa_app (the shared event log, dredd-core 0.20.0; takes effect per role once it is a reader too)
COUNTERPARTY_WRITER_ROLES / COUNTERPARTY_READER_ROLES / COUNTERPARTY_MIGRATOR_ROLES sygna_app / (empty) / sygna_migrator (the shared counterparty register, dredd-core 0.21.0; each takes effect once joined)

The last two name the roles that will be granted the reader tier. List them now even though the modules have not moved yet: the grants are harmless before their migrations and required after, and a module joining later means adding it here and running Atrium's migrate again: atrium-migrate runs python -m app.identity_grants after alembic upgrade head on every run, which re-applies shared_identity_grants_sql to exactly these lists (the block is authoritative, not additive, so re-running it is how the matrix stays true). No Atrium revision is needed.

Then one key in deploy/db.env, the file ./push.sh reads:

key value
PLATFORM_IDENTITY_SCHEMA dredd

That is how the push knows this deployment keeps one account per person, and it is the whole of what keeps section 3 true afterwards: with it set, every ./push.sh carries --identity-schema dredd --identity-owner atrium_migrator into its drift check and its provisioning, for all four apps. Without it, the next routine deploy re-provisions each app without the flags, which takes dredd off the role's search_path and its USAGE with it — the cutover undone, silently. It is one key for all four on purpose: provisioning has to reach every app's roles before any of them cuts over (§3.1), and four env files can disagree where one key cannot. The push refuses when an env/<app>.env names a schema deploy/db.env does not, so the two cannot drift apart unnoticed.

Set it now, with the atrium.env keys above, and not earlier: from here the push's steps 4 and 5 also check that schema, and until section 5 has run there are no tables in it to check.

Nothing else in deploy/db.env changes, and do not touch any *.migrate.env, ENCRYPTION_MASTER_KEY, SECRET_KEY or POSTGRES_PASSWORD.


5. Atrium's migration — the cutover

Section 3 must have run for all four apps. Step 7 below grants the reader tier to galena_app, sygna_app and counsel_app, and a role that does not yet hold USAGE on dredd cannot be granted anything inside it — so a missed app stops this migration with the message in §3.1. Nothing is committed when that happens; provision the app it names and run this again.

docker compose run --rm atrium-migrate

That runs alembic upgrade head and then the seed. Revision 0004 does, in one transaction:

  1. Refuses unless dredd exists and atrium_migrator owns it. (If you skipped section 3 you get a named error here, not a half-migrated database.)
  2. Creates app_user, session and module_permission in dredd, schema-qualified.
  3. Copies every Atrium account and session across, keeping their UUIDs. Refuses if an account with the same email is already there under a different id.
  4. Counts permission_grant rows whose principal_id names nobody, and answers the two cases differently: an id still in the local app_user is a row the move missed and raises; an id in neither store is nobody's doing — an account somebody deleted rather than deactivated — and warns, on a WARNI line of its own (see the sample below). Raising on the second kind is what used to make a second attempt refuse for ever.
  5. Re-points all fourteen foreign keys at dredd.app_user. PostgreSQL validates each one as it is added, so a value that failed to move fails loudly here.
  6. Drops the local app_user, session and module_permission (and module_moderator, the name the table had before dredd-core v0.11.0) — after proving every local account is present in the shared store, and never unqualified.
  7. Grants each of the eight roles its tier, verifies the result, and raises if it did not take.
  8. Installs a trigger making DELETE FROM dredd.app_user raise.

Expect, in the container's own output, one line between Running upgrade 0003 -> 0004 and the next revision:

INFO  [alembic.runtime.migration] shared identity: moved 1 account(s), N credential(s) and 0 module permission row(s) from atrium to dredd

That line is the cutover, and it is worth knowing why it is a log line rather than a NOTICE before you go looking for one. atrium-migrate runs alembic upgrade head over pg8000, which collects server notices on the connection and never prints them: a RAISE NOTICE from inside a migration reaches the PostgreSQL log and no human running it, so for a while this section told you to confirm something you could not see, on the one step that moves the accounts. 0004 therefore parks its counts in a temporary table and logs them from Python, which Alembic puts on stdout with everything else. (Sections 2, 6 and 8 run through psql, which does print notices, so the blocks there raise them as normal — the difference is the client, not the database.)

A second line appears only if step 4 found grants naming an account that is in neither store — none on this box, and it is a warning rather than a failure:

WARNI [alembic.runtime.migration] shared identity: 1 permission grant(s) in this schema name an account that is in neither store, and were left exactly as they are. …

Nobody's access changed (a grant whose principal does not exist grants nothing) and this migration neither made those rows nor can undo them. Remove them deliberately afterwards, or re-create the account and grant again. It is read back and logged for the same reason the line above it is: the check raises that warning inside a DO block, where only the PostgreSQL log would ever hear it.

If anything raises, nothing is committed — the whole thing is one transaction. Read the message; every one of them names what to do.

One consequence worth having in mind before you read any of these lines as an outcome: they are logged from inside that transaction, so a run that prints shared identity: moved 1 account(s)… and then stops on step 7 has printed a true account of what it attempted and committed none of it. The log says what the migration did; alembic_version and section 8 say whether it stayed.

No such line, and no error either, is the third outcome and the only quiet one: 0004 took its standalone branch, because IDENTITY_SCHEMA was not set in env/atrium.env when it ran (section 4). Nothing is broken and nothing is lost, but Alembic has recorded 0004 as applied, so upgrade head will now say there is nothing to do, for ever, on a database that never cut over. Set the key, put the version back, and run this section again:

docker compose run --rm --entrypoint alembic atrium-migrate stamp 0003

upgrade head also runs 0005, which corrects one row of the catalogue. Counsel Scorecard was seeded as counsel-scorecard while the module itself answers to counsel — its path, its schema, its two roles and its MODULE_SLUG. Two names for one module is not cosmetic here: a moderator grant is written against the slug and read back by the module under its own, so POST /admin/modules/counsel-scorecard/moderators returned 201 and gave the person nothing, in silence; and POST /me/modules/counsel/tokens was a 404, which after this cutover means no Counsel app token can be minted by anybody. The seed only ever fills an empty catalogue, so the row on this box has to be corrected by the migration.

0005 reports itself the same way 0004 does, and for the same reason: its numbers cannot be recovered afterwards — the duplicate grants it drops are gone, and a count of nothing is indistinguishable from a count that was never taken — so they are captured where they are produced and logged from Python. Expect a second line, after the one above:

INFO  [alembic.runtime.migration] counsel slug: catalogue row renamed counsel-scorecard -> counsel, 0 module permission row(s) moved, 0 duplicate(s) dropped. The audit log keeps the old name, on purpose.

Both counts are nought on this box, and that is correct: a module permission cannot exist until the cutover you are running right now. The sentence on the end is the part worth reading — the rename writes no module.update audit row, deliberately, because that log is append-only and module.create under the old name is a true statement about the past. This line is the only place the rename is ever announced. On a database whose catalogue is already right it reads counsel slug: the catalogue already says counsel, nothing to rename instead, which is the honest answer for an idempotent revision and not a failure.

Then confirm the outcome as well, which a query can, once the migration has finished:

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
SELECT slug, name FROM atrium.module ORDER BY slug;
SELECT module_slug, role, count(*) FROM dredd.module_permission GROUP BY 1, 2 ORDER BY 1, 2;
SQL

counsel must appear in the first and counsel-scorecard in neither. The second is empty on this box today — module permissions can only exist after this cutover — and it is there because it is the half that fails silently: a grant still addressed to counsel-scorecard gives its holder nothing, in a table Counsel reads under its own name.

If somebody has already added a second, correctly-named module by hand, 0005 refuses by name rather than choosing between two rows that each carry their own assignments and access requests — delete the stale one in Modules → Manage and run this again.

Then recreate the backend so it picks up the new settings:

docker compose up -d --force-recreate atrium-backend
docker compose logs --tail=20 atrium-backend | grep 'Shared identity schema'

You are looking for Shared identity schema dredd: every identity table resolves there. That line is the boot assertion, and it runs on every start, not just this one: it is the only guard against a restored dump or a stray create_all putting a local app_user back, which has no other symptom — the search_path reaches it first and everything keeps working, silently back to two rows per person. The backend refuses to start without it.

Sign in at <SITE>/atrium. You should not be asked to sign in again if you were already signed in.


6. The accounts a module has and the hub does not

Skip this entirely if section 2's census showed no such email. On this box it did not: Sygna's demo adwokat@example.com is one, and it is the whole reason this section has two branches.

This step exists because of a gap nothing else can close: atrium_migrator can write dredd.app_user but holds nothing in galena, sygna or counsel; each module's migrator can read its own app_user but holds only SELECT and REFERENCES on the shared one. Neither can do it. Only the platform admin can see both sides, so this is a hand step, reviewed by eye, run from the census — exactly like the schema creation in section 3, and for the same reason.

Run it after section 5 and before the module in question migrates. Until it has run, that module's own revision refuses by name and leaves alembic_version where it was:

M: shared identity: adwokat@example.com exists in sygna but not in dredd
H: Either import the account as the platform admin (the runbook has the SQL) or delete it and its
   rows here deliberately.

Every block below is run as the platform admin, in one transaction, and is safe to run twice — a second run changes nothing, and the drop branch says so rather than erroring. That matters more than it sounds: the likely way to meet this section is halfway through a cutover, having just been refused, and an operator who is not sure whether the first attempt committed anything should be able to simply run it again.

Two things that "safe to run twice" does not cover, both harmless and both easier to meet than to guess at:

  • After that module's own step 6 has run, its app_user is gone, so 6.2 and 6.3 stop with ERROR: relation "sygna.app_user" does not exist rather than the notice they promise. Nothing is committed (they are transactions), and it is not a failure to repair — it is this section saying the module it names has already cut over. 6.4's check has a to_regclass guard for exactly this and answers properly whenever it is run.
  • On a managed PostgreSQL provider the platform admin is not a superuser, and provisioning grants itself the migrator role only for as long as it needs it — so sections 2 and 6 will stop on ERROR: permission denied for schema sygna. That is provisioning behaving correctly, not a mis-provisioned database. Grant the admin what these two sections read, as its owner, and take it away again afterwards: GRANT USAGE ON SCHEMA <app> TO <admin>. This does not arise on this box — here the platform admin is postgres in the postgres container, and a superuser sees every schema.

6.1 Which branch, and why the default changed

6.2 — import (the default) 6.3 — drop
the account created in dredd, keeping its UUID deleted from the module's schema
rows that named it unchanged, every one nulled, or deleted with it
cost one row somebody cannot sign in as the history those rows were
reversible yes, one UPDATE no

Import is the default, including for the demo lawyer. Section 2 used to record the opposite, and the reason it was reconsidered is in the right-hand column: an account is one row, but the rows that name it are the work. On this box Anna Wiśniewska is the responsible lawyer on a live-shaped matter, the owner of its deadline, the attendee at a hearing, the author of two time entries and the holder of a permission grant and a rate profile. Dropping her nulls the first three, deletes the time entries — billable minutes, and time_entry.invoice_id means some of them may already be on an invoice — and (on a box where she has ever done anything) rewrites audit_log.actor_id to NULL, in a table the rest of this design goes to some length to keep append-only. A deactivated account costs one row and none of that.

Take the drop branch only for an account that should never have existed — a typo, a test row, a person who was never a person. If you are not sure, import: 6.2 can be undone and 6.3 cannot.

6.2 Branch A — import the account, and deactivate it if nobody should sign in as it

One module at a time. The schema name appears twice (once in the guard, once in the INSERT); change both. Read the census first and satisfy yourself that every e-mail this touches really is the same person: this is the step that decides who is who, and it cannot be undone from inside the platform afterwards.

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
BEGIN;

-- A shared id that is already somebody else's account. It takes a UUID collision across two
-- schemas, so it will never happen — and what happens if it does is two people's rows merging with
-- nothing afterwards to say so, which is worth four lines to exclude. Without it the symptom is a
-- primary key violation naming a UUID and neither of the two people.
DO $import_collision$
DECLARE clash text;
BEGIN
  SELECT string_agg(m.email || ' -> ' || d.email, ', ' ORDER BY m.email || ' -> ' || d.email)
    INTO clash
    FROM sygna.app_user m JOIN dredd.app_user d ON d.id = m.id
   WHERE lower(d.email) <> lower(m.email);
  IF clash IS NOT NULL THEN
    RAISE EXCEPTION USING
      MESSAGE = 'shared identity: importing would give one id to two people (' || clash || ')',
      HINT = 'Re-key one of them before importing. Nothing is committed.';
  END IF;
END
$import_collision$;

-- The import. The row keeps its UUID deliberately: every column in the module's schema that names
-- this person already holds it, so the module's own cutover has nothing to re-point for them
-- (`WHERE d.id <> l.id` in its map) and the audit log's actor_id is literally unchanged.
-- `failed_login_count` and `locked_until` are reset because they counted attempts against a login
-- screen that is about to stop existing.
INSERT INTO dredd.app_user (id, created_at, updated_at, email, password_hash, full_name,
                            is_admin, is_active, failed_login_count, locked_until)
SELECT m.id, m.created_at, m.updated_at, m.email, m.password_hash, m.full_name,
       false,                     -- NOT is_admin: the platform tier is granted in Atrium, on purpose
       m.is_active, 0, NULL
  FROM sygna.app_user m
 WHERE NOT EXISTS (SELECT 1 FROM dredd.app_user d WHERE lower(d.email) = lower(m.email));

-- Deactivate the ones nobody should sign in as — the demo lawyer here. The row, the rate profile
-- and every reference to her stay exactly as they are; what she loses is the ability to log in,
-- which she should never have had on a platform. `AND is_active` is what makes a second run touch
-- no row at all: without it, updated_at would move every time somebody re-ran this.
UPDATE dredd.app_user
   SET is_active = false, updated_at = now()
 WHERE lower(email) = lower('adwokat@example.com')
   AND is_active;

SELECT email, full_name, is_admin, is_active FROM dredd.app_user ORDER BY email;
COMMIT;
SQL

is_admin is forced to false deliberately: a module could previously mint its own administrator, and carrying that flag across would silently turn a Counsel administrator into an administrator of everything. If someone should keep that power, grant it in Atrium afterwards, where it produces an audit row.

The imported row carries its password_hash, so the account is a real one the moment somebody sets is_active = true again — which is the point of the branch, and also why deactivating the demo account is not optional. To bring it back later:

UPDATE dredd.app_user SET is_active = true, updated_at = now()
 WHERE lower(email) = lower('adwokat@example.com');

6.3 Branch B — drop the account and everything that names it

Only for an account that should never have existed. Take the backup from section 1 first — this branch is the one thing in the whole runbook with no way back.

It is not a DELETE. Thirty-eight foreign keys in sygna point at its app_user, and the row will not go until each of them is dealt with, three different ways depending on how the column is declared. So read what it will do before it does it — this counts, and changes nothing:

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
DO $drop_census$
DECLARE
  module_schema text := 'sygna';               -- the module's schema
  victim_email  text := 'adwokat@example.com'; -- the account the census in section 2 listed
  victim        uuid;
  r             record;
  n             bigint;
  report        text := '';
BEGIN
  EXECUTE 'SELECT id FROM ' || quote_ident(module_schema)
       || '.app_user WHERE lower(email) = lower($1)' INTO victim USING victim_email;
  IF victim IS NULL THEN
    RAISE NOTICE 'no % in %: nothing to count', victim_email, module_schema;
    RETURN;
  END IF;

  -- Read from the catalogue rather than typed out, for the same reason the module's own revision
  -- reads its column list from the models: a foreign key added next year is counted here without
  -- anyone remembering to add it, and this is not a list worth being one row out of date.
  FOR r IN
    SELECT quote_ident(n2.nspname) || '.' || quote_ident(c2.relname) AS tbl,
           a.attname AS col, con.confdeltype = 'c' AS cascades, a.attnotnull AS required
      FROM pg_constraint con
      JOIN pg_class c2 ON c2.oid = con.conrelid
      JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
      JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = con.conkey[1]
     WHERE con.contype = 'f'
       AND con.confrelid = (quote_ident(module_schema) || '.app_user')::regclass
       AND cardinality(con.conkey) = 1
     ORDER BY 1, 2
  LOOP
    EXECUTE 'SELECT count(*) FROM ' || r.tbl || ' WHERE ' || quote_ident(r.col) || ' = $1'
       INTO n USING victim;
    IF n > 0 THEN
      report := report || '  ' || rpad(r.tbl || '.' || r.col, 46) || n || ' row(s) -> '
             || CASE WHEN NOT r.required THEN 'SET NULL'
                     WHEN r.cascades    THEN 'deleted with the account (ON DELETE CASCADE)'
                     ELSE 'THE ROWS THEMSELVES ARE DELETED' END || E'\n';
    END IF;
  END LOOP;

  -- permission_grant.principal_id carries no foreign key at all — it is polymorphic on
  -- principal_type — so the loop above cannot see it and nothing in the database would ever
  -- complain about a row left behind. The only symptom is somebody who can still see a matter.
  EXECUTE 'SELECT count(*) FROM ' || quote_ident(module_schema)
       || '.permission_grant WHERE principal_type = ''user'' AND principal_id = $1'
     INTO n USING victim;
  IF n > 0 THEN
    report := report || '  ' || rpad(module_schema || '.permission_grant.principal_id', 46)
           || n || ' row(s) -> THE ROWS THEMSELVES ARE DELETED (polymorphic, no foreign key)'
           || E'\n';
  END IF;

  RAISE NOTICE E'% (%) in %:\n%', victim_email, victim, module_schema,
        coalesce(nullif(report, ''), '  (nothing references this account)');
END
$drop_census$;
SQL

On this box, before the cutover, that prints:

NOTICE:  adwokat@example.com (cfc34aa7-…) in sygna:
  sygna.court_event.attending_id                1 row(s) -> SET NULL
  sygna.deadline.owner_id                       1 row(s) -> SET NULL
  sygna.lawyer_profile.user_id                  1 row(s) -> deleted with the account (ON DELETE CASCADE)
  sygna.matter.responsible_lawyer_id            1 row(s) -> SET NULL
  sygna.time_entry.user_id                      2 row(s) -> THE ROWS THEMSELVES ARE DELETED
  sygna.permission_grant.principal_id           1 row(s) -> THE ROWS THEMSELVES ARE DELETED (polymorphic, no foreign key)

Four of those six lines are history. If that is acceptable, the same two variables drive the destructive half:

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
BEGIN;
DO $drop_local_account$
DECLARE
  module_schema text := 'sygna';
  victim_email  text := 'adwokat@example.com';
  victim        uuid;
  r             record;
  n             bigint;
  report        text := '';
BEGIN
  EXECUTE 'SELECT id FROM ' || quote_ident(module_schema)
       || '.app_user WHERE lower(email) = lower($1)' INTO victim USING victim_email;
  IF victim IS NULL THEN
    -- Already gone, or never here. This is the second-run case, and it is a NOTICE rather than an
    -- error on purpose: an operator who is not sure whether the first attempt committed should be
    -- able to just run it again.
    RAISE NOTICE 'shared identity: no % in %, nothing to drop', victim_email, module_schema;
    RETURN;
  END IF;

  -- Refuse if the shared store HAS this person. Then the module's own revision would have matched
  -- them by e-mail and re-pointed every row, and deleting here destroys data for no reason at all.
  -- The likeliest way to arrive here is a mistyped address that happens to be somebody real.
  PERFORM 1 FROM dredd.app_user d WHERE lower(d.email) = lower(victim_email);
  IF FOUND THEN
    RAISE EXCEPTION USING
      MESSAGE = 'shared identity: ' || victim_email || ' IS in dredd, so it must not be dropped',
      HINT = 'This branch is only for an account the shared store has never heard of. This one the '
          || 'module''s own revision will match by e-mail and re-point. Nothing is committed.';
  END IF;

  -- The same catalogue query as the census, so the two cannot disagree, but ordered NOT NULL first:
  -- those are the rows that are deleted outright, and they should be the first thing in the log.
  --   nullable                     -> SET NULL, and the row survives without an author
  --   NOT NULL, ON DELETE CASCADE  -> left alone; it goes with the account at the end
  --   NOT NULL, no cascade         -> the row itself has to go, or the account cannot be deleted
  -- A row that is itself referenced by something else makes that DELETE fail, naming the
  -- constraint, and the whole transaction rolls back. That is the loud version, and it is correct:
  -- nothing here should guess what to do with an invoice line.
  FOR r IN
    SELECT quote_ident(n2.nspname) || '.' || quote_ident(c2.relname) AS tbl,
           a.attname AS col, con.confdeltype = 'c' AS cascades, a.attnotnull AS required
      FROM pg_constraint con
      JOIN pg_class c2 ON c2.oid = con.conrelid
      JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
      JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = con.conkey[1]
     WHERE con.contype = 'f'
       AND con.confrelid = (quote_ident(module_schema) || '.app_user')::regclass
       AND cardinality(con.conkey) = 1
     ORDER BY a.attnotnull DESC, 1, 2
  LOOP
    IF NOT r.required THEN
      EXECUTE 'UPDATE ' || r.tbl || ' SET ' || quote_ident(r.col) || ' = NULL WHERE '
           || quote_ident(r.col) || ' = $1' USING victim;
    ELSIF r.cascades THEN
      CONTINUE;
    ELSE
      EXECUTE 'DELETE FROM ' || r.tbl || ' WHERE ' || quote_ident(r.col) || ' = $1' USING victim;
    END IF;
    GET DIAGNOSTICS n = ROW_COUNT;
    IF n > 0 THEN
      report := report || '  ' || rpad(r.tbl || '.' || r.col, 46) || n
             || CASE WHEN r.required THEN ' row(s) DELETED' ELSE ' row(s) set to NULL' END || E'\n';
    END IF;
  END LOOP;

  EXECUTE 'DELETE FROM ' || quote_ident(module_schema)
       || '.permission_grant WHERE principal_type = ''user'' AND principal_id = $1' USING victim;
  GET DIAGNOSTICS n = ROW_COUNT;
  IF n > 0 THEN
    report := report || '  ' || rpad(module_schema || '.permission_grant.principal_id', 46)
           || n || ' row(s) DELETED' || E'\n';
  END IF;

  -- Last, so that every foreign key above has already let go. The ON DELETE CASCADE ones go with
  -- it here — the lawyer profile, the notification preferences, any ethical wall naming this
  -- person, the local sessions. If one is left that this did not account for, PostgreSQL refuses
  -- the delete and names the constraint, which is exactly what should happen.
  EXECUTE 'DELETE FROM ' || quote_ident(module_schema) || '.app_user WHERE id = $1' USING victim;
  RAISE NOTICE E'shared identity: dropped % (%) from %\n%', victim_email, victim, module_schema,
        coalesce(nullif(report, ''), '  (nothing referenced it)');
END
$drop_local_account$;
COMMIT;
SQL

Note what the loop does to audit_log.actor_id: it is nullable, so it is set to NULL, and the audit trail keeps the action while losing the actor. The runtime role cannot do that — the whole design keeps audit_log append-only — but the platform admin can, and this branch does. It is the sharpest single reason 6.2 is the default.

6.4 Afterwards

Not section 2's census, and this is the one place the difference bites: that query reads atrium.app_user, and by the time you are here section 5 has dropped it (step 6) — so re-running it answers relation "atrium.app_user" does not exist and tells you nothing about the thing you are checking. The question has changed too. Before the cutover it was "who exists where"; now it is the single condition each module's own revision refuses on — is there an account in this module's schema that dredd still does not have?

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
DO $still_missing$
DECLARE
  s      text;
  found  text;
  report text := '';
BEGIN
  FOREACH s IN ARRAY ARRAY['galena', 'sygna', 'counsel'] LOOP
    -- A module that has already migrated has no local app_user at all — its people ARE the shared
    -- rows now. That is why this is a loop with a guard rather than section 2's UNION: you arrive
    -- here three times, once per module, and by the third the first two are gone.
    IF to_regclass(quote_ident(s) || '.app_user') IS NULL THEN
      report := report || '  ' || rpad(s, 10) || 'already migrated (no local app_user)' || E'\n';
      CONTINUE;
    END IF;
    -- lower(email), because that is what the module's revision matches on and what both tables
    -- carry their unique index on. Matching any other way would answer a different question than
    -- the one that decides whether the migration goes through.
    EXECUTE 'SELECT string_agg(m.email, '', '' ORDER BY m.email) FROM ' || quote_ident(s)
         || '.app_user m WHERE NOT EXISTS (SELECT 1 FROM dredd.app_user d'
         || ' WHERE lower(d.email) = lower(m.email))' INTO found;
    report := report || '  ' || rpad(s, 10)
           || coalesce('STILL MISSING FROM dredd: ' || found, 'ready') || E'\n';
  END LOOP;
  RAISE NOTICE E'accounts a module has and dredd does not:\n%', report;
END
$still_missing$;
SQL

ready on every line is the go-ahead, and it is the same condition either branch reaches: 6.2 imported the account, 6.3 deleted it, and both leave nothing unmatched. Anything else names the address that will stop that module's migration — go back to 6.1 and decide which branch it takes. Then run that module's migration — section 7.


7. The three modules (their own repositories, their own phase)

Each module needs, in this order:

  1. its db/managed/provision.sql re-rendered with --identity-schema dredd --identity-owner atrium_migrator and committed. Its two roles already hold USAGE and already have dredd on their search_path — section 3 did that, live, and it had to, or Atrium's own migration could not have run. What the re-rendered file buys is everything after today. It is not what the push provisions from — provisioning is driven by flags, and PLATFORM_IDENTITY_SCHEMA=dredd in deploy/db.env (section 4) is what puts them there — but step 1 of every ./push.sh renders the same flags and compares the result with this file, and stops the push when they differ. That comparison is the standing guarantee that the committed SQL editor path and the routine deploy still say the same thing; a module left on the standalone rendering is reported stale, and the push prints the --output command to fix it. (The comparison runs in step 1 of a real push, not in --dry-run, which connects to nothing and only prints the plan — the plan now shows the exact flags step 1 will use, which is worth a look before the real run.);
  2. IDENTITY_SCHEMA=dredd and SESSION_COOKIE_NAME=dredd_session in deploy/env/<slug>.env (the templates now carry both ACTIVE, because a fresh install is one account; a box from before that has them commented out, or not at all — uncomment or add them). Those two, and nothing else. The push refuses a module on the platform whose cookie name is not the hub's. All three consoles now derive the hub's address from their own document — ../atrium/ against document.baseURI — because at one origin the hub is a sibling path, so the sign-in card links somewhere whatever the operator does or forgets. Galena took a setting for this once, and a deployment that left it empty got the card that says "your account lives elsewhere" and links nowhere; that is the bug the derivation fixed. IDENTITY_HUB_URL therefore stays commented out in deploy/env/galena.env.example and in your galena.env: it is an override for a hub that genuinely lives on another host, and a value set here would mean the derivation underneath it never runs in production — which is how a fix stops being a fix;
  3. MODULE_SLUG matching the slug in Atrium's catalogue — galena, sygna, counsel. It is the name a module permission is addressed by, and a module that answers to a different one reads an empty table and reports the person as having no tier, with no error on either side (that is exactly what counsel-scorecard did; see section 5). Each module's default is already its own slug, so this is a check, not an edit;
  4. its own cutover revision: match accounts by lower(email), raise on an unmatched one rather than orphaning it, de-duplicate the composite keys of §0.1, repoint every id, run the orphan check, re-point the foreign keys, drop the local tables;
  5. AuthPolicy(identity_writes_enabled=False, local_login_enabled=False, app_tokens_enabled=False) and its own assert_identity_schema in the lifespan;
  6. docker compose run --rm <slug>-migrate, then docker compose up -d --force-recreate <slug>-backend.

deploy/compose.yaml already declares that every module's migration waits for Atrium's (depends_on: atrium-migrate: service_completed_successfully), so a plain docker compose up -d cannot race them. Without that line all four one-shots start in parallel and a module can try to point a foreign key at a table that does not exist yet — nondeterministically, differently each time. Both revisions also refuse loudly on their own, so a missed ordering is a named error rather than a corrupted database; the compose line is the belt to that braces.

7.1 What step 6 prints, per module

Each cutover says what it did to your database, on stdout, between its Running upgrade line and the next — the same way and for the same reason as Atrium's in section 5: a RAISE NOTICE from inside a migration reaches the PostgreSQL log and no human, because pg8000 collects server notices on the connection and nothing prints them. All three therefore capture their counts where the counts exist and log them from Python. Expect, with this box's data:

# docker compose run --rm galena-migrate
INFO  [alembic.runtime.migration] shared identity: 1 account(s) matched in dredd, 1 of them under a different id

# docker compose run --rm sygna-migrate
INFO  [alembic.runtime.migration] shared identity: 2 account(s) of sygna matched in dredd, 1 of them under a different id
INFO  [alembic.runtime.migration] shared identity: re-pointed N reference(s) to them across 36 person-shaped column(s) of sygna, 0 of them the person an ethical wall bars

# docker compose run --rm counsel-migrate
INFO  [alembic.runtime.migration] shared identity: 1 account(s) of counsel matched in dredd, 1 of them under a different id
INFO  [alembic.runtime.migration] shared identity: re-pointed N reference(s) to them across 12 person-shaped column(s) of counsel

Read the second number on the first line of each. It is how many of the matched accounts are changing id, and it is smaller than the first exactly when section 6 imported somebody: branch A keeps the account's own UUID on purpose, so every column that already named them needs no re-pointing at all. Sygna is the one that shows it here — admin@example.com becomes Atrium's row and moves, adwokat@example.com was imported with her own id and does not — which is also how you can tell from the output alone which branch of section 6 was taken. If you took branch B and dropped her, Sygna reports 1 account(s) … 1 of them under a different id instead.

The second line is the size of the merge: every id in that schema that named one of those people, re-pointed in one transaction. N depends on how much work is in the database and there is no right value to check it against — what matters is that it is not zero on a box that has been used. The ethical-wall count on Sygna's line is the one to actually read, and it is there rather than folded into the total because it is the only number here whose being wrong is a confidentiality failure: a wall whose barred person points at an account that no longer exists bars nobody, and the screen it protects simply opens with nothing anywhere saying so. It counts the walls whose barred person moved — not the ones they merely wrote — so zero is the expected answer on this box: the demo firm's seed creates no walls at all. On a firm that has made some, it is non-zero exactly when one of the people who moved was barred from a matter. Galena prints one line rather than two; it also warns by name if somebody who administered Galena is not a platform administrator, which is a reminder to name them a moderator in section 9, not an error.

All three — and Atrium's 0004 in section 5 — add a WARNI line when a permission_grant in that schema names an account that is in neither store: the leftovers of an account somebody deleted rather than deactivated. It is not a failure and it is not this cutover's doing: the column is polymorphic and carries no foreign key, so nothing removed those rows when the account went. They grant nobody anything. Remove them deliberately afterwards, or re-create the account in Atrium and grant again. There should be none on this box.

WARNI [alembic.runtime.migration] shared identity: 1 permission grant(s) in this schema name an account that is in neither store, and were left exactly as they are. …

The distinction the check draws matters if you ever have to retry: a principal_id that is still a row of the module's own app_user is a row the merge missed and refuses the whole migration; one that is in neither store is unrepairable by anybody and only warns. Raising on the second kind is what used to make a second attempt refuse for ever, and the warning is the only place it is ever mentioned.

Counsel's run carries one more revision that moves a row, and it says so only to the PostgreSQL log. 0003_user_role_admin_removed runs in the same counsel-migrate as the cutover and rewrites every counsel_user_profile.role = 'admin' to legal_ops, because administering Counsel is a platform tier now and not a column this module can write. On this box that is exactly one row, the seeded admin@example.com, and the person loses nothing: legal_ops carries the same powers over firms, matters, questionnaires and cycles, and section 9 is where the administering comes back. It reports itself in a RAISE NOTICE, which nobody running Alembic ever sees, so confirm it the way a query can:

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
SELECT role, count(*) FROM counsel.counsel_user_profile GROUP BY 1 ORDER BY 1;
SQL

No admin in that list, and one more legal_ops than the census counted, is the whole of it.

No line at all, and no error either, is the third outcome and the only quiet one: the revision took its standalone branch because IDENTITY_SCHEMA was not in deploy/env/<slug>.env when it ran. Nothing is broken and nothing is lost, but Alembic has recorded the revision as applied, so upgrade head will now say there is nothing to do, for ever, on a schema that never cut over — and the backend will refuse to start, because its own assert_identity_schema can still see the local app_user. Set the key and put the version back, one revision before the cutover:

docker compose run --rm --entrypoint alembic galena-migrate  stamp 0006
docker compose run --rm --entrypoint alembic sygna-migrate   stamp 0002
docker compose run --rm --entrypoint alembic counsel-migrate stamp 0003_user_role_admin_removed

then run step 6 again. That is safe on a schema that has already been converted: all three revisions are idempotent, and re-running one after a successful cutover moves nothing. All three say so in as many words:

INFO  [alembic.runtime.migration] shared identity: no local app_user in <schema>, nothing to merge

That line is the whole of a re-run, and it is the answer to "did I just merge these people twice?". (Galena used to read differently here and did not say that — with its local table already gone, the unqualified app_user in its summary resolved through the search_path to the SHARED one and it reported every account the platform has, 0 of them under a different id. Nothing moved and nothing was wrong, but it read like Galena still owned those accounts, so it now asks whether it still has a local table before it says anything about one.)

The three module consoles lose their Create token button at step 5, because no module holds INSERT on session any more — a role that can insert a session row can mint a credential for the administrator. Atrium replaces it, and replaces it with a screen rather than a curl command: Połączone aplikacje / Connected apps in the hub's own sidebar — every signed-in person's, not only an administrator's — lists their tokens, mints one for a module they choose, and revokes one. It posts to POST /api/v1/me/modules/{slug}/tokens (or POST /api/v1/me/tokens for a token stamped with the hub's own prefix), and it ships now, in this phase, precisely so GalenaConnect never has a window in which a token cannot be obtained at all. The secret is shown exactly once, at the moment it is minted; nothing stores it, and there is no way to read it back.

Say this out loud to whoever hands those tokens out: <slug>_pat_ is provenance, not scope. A token minted "for Galena" is an ordinary platform credential — one session row, and every module resolves the same one — so a galena_pat_… presented to Sygna or Counsel authenticates there too, and returns 200 from their /auth/me. That is correct under one account, it is the same property the shared cookie has, and it is not a defect to fix: there is no audience field on a shared session row and adding one would be inventing the cross-origin protocol this topology does not need. But it is a real widening of what "a token for Galena" used to mean, so it belongs in writing rather than in somebody's assumption. What the prefix buys is a secret scanner's pattern, a name in the console that is not the secret, and — when one leaks — the first audit log to read. What actually limits a credential is each module's own permission grants, exactly as it limits the person holding it.


8. Prove it

for url in DATABASE_URL MIGRATION_DATABASE_URL; do
  docker compose run --rm --entrypoint python atrium-migrate -m dredd_core.managed check \
    --url "$url" --expect-schema atrium --app-role atrium_app --migrator-role atrium_migrator \
    --identity-schema dredd --identity-tier owner
done

--identity-tier owner, not writer: Atrium's migrator owns that schema, so measuring it against the writer tier reports an "escalation" on a perfectly correct deployment — the loudest possible message about the role the design trusts most. Each module is checked with --identity-tier reader after its own phase.

A passing report names the allowlist explicitly, and that is the sentence worth reading:

[OK] identity shadow: atrium holds no copy of app_user, module_permission, session
[OK] identity atrium_app: in dredd: USAGE, no CREATE, owns nothing;
     app_user: SELECT, INSERT, UPDATE; module_permission: SELECT, INSERT, UPDATE, DELETE;
     session: SELECT, INSERT, UPDATE; nothing else in dredd

and after a module has moved, the other half of it:

[OK] identity galena_app: app_user: SELECT (id, created_at, updated_at, email, full_name, is_admin,
     is_active), nothing at all on password_hash/failed_login_count/locked_until;
     module_permission: SELECT; session: SELECT, UPDATE (last_seen_at, expires_at, revoked_at)

That is the whole security argument in two lines: a module may read who exists and write three columns of a session row, and it may never create an account, elevate one, or mint a credential. The enforcement is the grant, not a missing screen.

Then, by hand: sign in at <SITE>/atrium, click a module tile, and confirm you land inside it already signed in. That is the thing this entire change exists to do. If it asks for a password, stop and read the module's logs before going further.


9. Name the moderators

In Administration → Users, click Permissions on a person: the platform-wide Administrator tier is a checkbox, and the modules they moderate are a list underneath. The same grants can be made from a module's own page, under Moderators. Both are administrator-only, both are audited, and neither can be done from inside a module — a module's role holds SELECT on that table and nothing else.

If section 2's census showed anyone with is_admin = true in a module schema, this is where they get their tier back, as a moderator of that module rather than an administrator of everything. Do it by hand, from the census, and check the result in Administration → Audit log.

The last administrator cannot be demoted or deactivated, so the platform can no longer be locked out in two clicks. It could before this change: Atrium's deactivate checked nothing at all.

9.1 Forgotten passwords, and correcting a name or an email

Also in Administration → Users, and behind one button: a row's Edytuj / Edit opens a dialog that corrects the person's name and email address, and carries Ustaw hasło / Set password for the reset. The row's other buttons are different jobs: Uprawnienia / Permissions is the two tiers from the paragraphs above, and Dezaktywuj / Deactivate switches the account off. Both acts here are administrator-only, and both are audited under their own action (user.update, user.password_reset).

Know where this lives before somebody needs it, because after the cutover there is nowhere else it can happen. A module's own reset answers 409 — no module may write app_user at all — and "change my password" needs the current one, which is exactly what a person who has forgotten it does not have. There is no e-mail reset on this platform and no SMTP configured to send one.

A reset ends every session and app token that person holds, in every module, because whoever opened them knew the old password; it also lifts the login lockout, which someone who has been guessing at their own password has usually just tripped. Hand them the new password over a channel you trust and ask them to change it themselves once they are in.


10. Rollback

There is one, and it is the dump:

docker compose stop atrium-backend galena-backend sygna-backend counsel-backend
docker compose exec -T postgres dropdb -U postgres --force dredd
docker compose exec -T postgres createdb -U postgres -O postgres dredd
docker compose exec -T postgres pg_restore -U postgres -d dredd --exit-on-error < "$BK/dredd.dump"

10.1 Never --no-owner

That flag was in this section once, and it is the one thing here that turns a rollback into a second incident. This database's whole design is per-app ownership: atrium owned by atrium_migrator, galena by galena_migrator, sygna and counsel by theirs, and dredd by atrium_migrator because the hub's revision is what creates its tables. --no-owner restores every schema, table, index and sequence owned by whoever runs the restore — postgres — and it does it without a single error. The site comes back up, the four accounts are there, and the deployment is quietly no longer the one section 8 verifies:

[FAIL] table owners: owned by a superuser or the platform admin: access_request, alembic_version,
       app_setting, app_user, audit_log, favorite, module, ...; objects the platform admin creates
       pick up the provider's default grants for its API roles; migrate as migrator
[FAIL] migrator role: schema atrium is owned by postgres, not atrium_migrator

The first line is why ownership is the design and not a detail — on a managed provider a table owned by the admin inherits the default grants that provider's auto-generated API roles hold, which is exactly the exposure §3 and §8 exist to prevent. The second is the isolation assertion itself.

And it does not stop at a failed report. The migrator's USAGE and CREATE on its own schema come from owning it, never from a grant, so --no-owner takes them away with the ownership. The schema's ACL before and after says the whole thing:

-- SELECT nspname, pg_get_userbyid(nspowner), nspacl FROM pg_namespace WHERE nspname = 'atrium';
before: atrium | atrium_migrator | {atrium_migrator=UC/atrium_migrator,atrium_app=U/atrium_migrator}
after:  atrium | postgres        | {postgres=UC/postgres,atrium_app=U/postgres}

atrium_app keeps its explicit grant, so the backends run and nothing looks wrong. atrium_migrator holds nothing at all, so the very next docker compose run --rm atrium-migrate — the next ordinary deploy, days later — stops on permission denied for schema atrium, and by then nobody connects it to the rollback. Without the flag none of this arises: roles are cluster-level and dropdb does not touch them, so postgres restores each object as the role that owned it and the ACLs come back byte-for-byte. Run section 8 after any restore — it is the same check either way, and it is the only thing that tells the two apart.

--exit-on-error is there for a related reason: pg_restore defaults to logging an error, carrying on, and reporting a count at the end. That is the right default for moving a database between servers and the wrong one for a rollback, where "most of it came back" is the worst outcome available.

10.2 The settings — four env files and db.env, not one

file put back
env/atrium.env IDENTITY_SCHEMA= (empty), SESSION_COOKIE_NAME=atrium_session, and clear IDENTITY_READER_ROLES and IDENTITY_MIGRATOR_ROLES (empty, or commented out)
env/galena.env, env/sygna.env, env/counsel.env comment IDENTITY_SCHEMA and SESSION_COOKIE_NAME out again — for each module that got as far as section 7 step 2
deploy/db.env remove PLATFORM_IDENTITY_SCHEMA

The two role lists are the ones that stop the hub from starting at all, and section 4 is what put them there, so a revert that clears only IDENTITY_SCHEMA leaves them naming reader roles for a schema this deployment no longer has. Settings refuses that half-configured pair on purpose — it is the shape in which 0004 would skip its grant block and each module would fail much later, on its own migration, as permission denied for schema dredd — and it refuses it in the constructor, so atrium-migrate and atrium-backend both die on import:

pydantic_core.ValidationError: 1 validation error for Settings
  Value error, IDENTITY_READER_ROLES / IDENTITY_MIGRATOR_ROLES need IDENTITY_SCHEMA set as well —
  they are the roles that read that schema

The message names both keys, so it is a minute's work — but it is a minute spent with the platform down, reading an error for the first time, which is the whole reason it is written here instead.

deploy/db.env is the one that gets forgotten, and it is the one that undoes the rollback: while PLATFORM_IDENTITY_SCHEMA=dredd is still there, the next ./push.sh provisions all four apps with --identity-schema dredd --identity-owner atrium_migrator, re-creating the schema and its eight USAGE grants on a deployment that has just gone back to four separate accounts, and then runs its step 4 and 5 checks against identity tables that no longer exist. The push also refuses outright while an env/<app>.env names a schema db.env does not, so reverting the env files and not this one stops the next deploy dead — loudly, which is the half of the mistake that cannot be made quietly.

docker compose up -d --force-recreate atrium-backend galena-backend sygna-backend counsel-backend

10.3 What comes back, and what a second attempt starts from

The restore restores the database. Roles, their passwords, their search_path and their statement_timeout live in the cluster, not in it, so dropdb never touched them and they are still exactly as section 3 left them — all eight still name dredd on their search_path. That is harmless (PostgreSQL ignores a schema that is not there) but it is worth knowing, because it is why the roles look right afterwards while the privileges behind them are gone.

dredd itself is not left behind: section 1's dump was taken before section 3 created it, so it goes with the dropped database. Nothing is inert and there is nothing to re-use — a second attempt starts again at section 3, which re-creates the schema, its owner and each app's USAGE on it.

Put the four versions back before that second attempt, and do it even though the restore already did once. The dump brings alembic_version back to the pre-cutover revision in every schema, and then the first migrate run of the rolled-back deployment moves it forward again for nothing: with IDENTITY_SCHEMA empty each cutover revision takes its standalone branch, does nothing at all, and is recorded as applied. That run is not something you have to go looking for — §10.2's own docker compose up brings each app's *-migrate one-shot with it (every backend waits on its migrate), and so does the next routine deploy. Nothing is broken by it and nothing is lost; the damage is only that upgrade head will now say there is nothing to do, for ever, on four schemas that never cut over. That is the quiet outcome §5 and §7.1 each warn about, met the one way neither of them is being read. So:

docker compose run --rm --entrypoint alembic atrium-migrate  stamp 0003
docker compose run --rm --entrypoint alembic galena-migrate  stamp 0006
docker compose run --rm --entrypoint alembic sygna-migrate   stamp 0002
docker compose run --rm --entrypoint alembic counsel-migrate stamp 0003_user_role_admin_removed

Stamp only the apps that got as far as their cutover — and stamping one that did not is harmless, as it names the revision such a database is already at. Check rather than remember:

docker compose exec -T postgres psql -U postgres -d dredd -v ON_ERROR_STOP=1 <<'SQL'
SELECT 'atrium' AS app, * FROM atrium.alembic_version
UNION ALL SELECT 'galena',  * FROM galena.alembic_version
UNION ALL SELECT 'sygna',   * FROM sygna.alembic_version
UNION ALL SELECT 'counsel', * FROM counsel.alembic_version;
SQL

A second attempt is safe from any of these four; what it cannot survive is starting from the revision after them with the work never done.

The exception is a rollback of a rehearsal whose dump was taken after provisioning. Then the restore brings an empty dredd back, and section 8 fails isolation <app>_app: USAGE on schema dredd — correctly, because a standalone deployment holds no privilege in a shared schema. There DROP SCHEMA dredd CASCADE as the platform admin is the fix rather than a tidy-up.

alembic downgrade is not an alternative, for the reason in §0.4.