Postgres Migration Deployment Policy¶
Date: 2026-05-19
Status: - draft reference operations policy - non-normative - intended for local shared-infra and small-network reference deployments
Purpose¶
The QR trust network treats Postgres as the source of truth for root programs, delegated authorities, issuers, destination policies, published artifacts, verifier cache entries, scanner decisions, and worker queues. Schema changes therefore need an explicit deployment policy before reference workers are treated as continuously runnable services.
This policy defines the minimum migration discipline for the local reference implementation. It is not a substitute for a production deployment system, but it records the controls a production system should preserve.
Authority Boundary¶
The migration runner may create or extend the qr_trust schema. It must not:
- drop
qr_trustor any application table - delete trust-state rows
- truncate queues, artifacts, cache entries, or scanner decisions
- rewrite an applied migration checksum
- treat Redis, NATS, or scanner clients as schema authorities
Alembic owns the shared schema for the backend and reference workers. Its
alembic_version ledger records the installed revision. The older standalone
Node migration drill records SQL checksums in qr_trust.schema_migrations.
Required Gates¶
Before starting reference workers against a shared database:
- Run
make ensure-shared-infra-db. - Run
make check-shared-infra-network. - Run
make apply-network-migrationsonly after confirming the target is the separate QR Trust database, not another project database. - Run
make check-network-migrations. - Start workers only if
check-network-migrationsexits successfully.
check-network-migrations runs alembic current --check-heads against the
existing database selected by the Makefile's EXTERNAL_DB_* settings. The
status check fails if the database is missing or any source head is unapplied.
Run the separate apply command when you intend to provision or migrate it.
Migration Packaging Rules¶
Each migration must have:
- a stable Alembic revision ID and its parent revision
- a human-readable description
- a checked-in SQL file or checked-in generated SQL artifact
- a source file covered by the deployment's provenance manifest
- an idempotent apply path
- a documented rollback posture
- a smoke or status command that can prove the expected tables or columns exist
Migration revisions are append-only. The Alembic head check verifies revision coverage. Operators verify file integrity separately against the approved deployment manifest and record its checksums alongside the migration evidence.
Rollback Posture¶
For this reference implementation, rollback means stopping new writes and restoring from a known-good database snapshot. It does not mean automatically running destructive down migrations.
Reason:
- trust artifacts and scanner decisions are audit evidence
- queue rows may represent accepted governance work
- deleting or rewriting those rows can change the historical trust record
Allowed rollback actions:
- stop artifact-publication, verifier-cache, and outbox workers
- block new issuer or policy publication
- restore the QR Trust database from a pre-migration backup
- roll forward with a corrective additive migration
- mark bad worker rows failed for review
Disallowed rollback actions:
drop schema qr_trust cascadeon a shared or non-disposable database- truncating
published_artifacts,status_events,scanner_decisions, or queue tables to force a green worker status - deleting applied migration ledger rows to re-run changed SQL
- editing a signed artifact in place
Backup Requirement¶
Before applying migrations outside disposable local development, the operator must capture:
- a database backup or snapshot
- the current
alembic_versionrows and deployment migration-file checksums make check-network-migrationsoutput- worker versions or image digests that will run after the migration
The backup must be restorable before the migration is considered approved.
Run the database backup from a scheduler¶
Provision a dedicated login for the backup job. Give it access to connect to
the QR Trust database, use the archived schemas, and read the archived tables
and sequences. Run the following as the schema owner or an administrator in
qr_db. This example assumes the migrations run as qr_admin and the
Alembic ledger is in public.
CREATE ROLE qr_backup LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOREPLICATION NOBYPASSRLS;
GRANT CONNECT ON DATABASE qr_db TO qr_backup;
GRANT USAGE ON SCHEMA public, qr_trust TO qr_backup;
GRANT SELECT ON ALL TABLES IN SCHEMA public, qr_trust TO qr_backup;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public, qr_trust TO qr_backup;
ALTER DEFAULT PRIVILEGES FOR ROLE qr_admin IN SCHEMA public, qr_trust
GRANT SELECT ON TABLES TO qr_backup;
ALTER DEFAULT PRIVILEGES FOR ROLE qr_admin IN SCHEMA public, qr_trust
GRANT SELECT ON SEQUENCES TO qr_backup;
Use the actual owner roles that create objects in each archived schema. Use the deployment's PostgreSQL authentication policy to configure the credential and restrict the login to the backup runner and intended database. If the database has other archived schemas or uses row-level security, verify effective access with a scratch backup and restore before enabling the job. PostgreSQL default privileges
Configure a libpq service for this login with credentials available to the
backup account. Use Python 3.11 or later and compatible PostgreSQL client
tools. Put the trusted installation of psql, pg_dump, and pg_restore
on the backup account's PATH using absolute directories. Create an
operator-only destination on the backup filesystem, then run this command
as the backup account. PostgreSQL connection service files
PGSERVICE=qrtrust-backup python3 scripts/qrtrust_postgres_backup.py \
--expected-database qr_db \
--output-directory /srv/qrtrust/backups/postgres
A successful run prints the path to a new directory containing
database.dump, collector-role-map.json, and manifest.json. The manifest
records the database name, server version, Alembic ledger schema and revision
rows, and SHA-256 hashes for the archive and role map. The tool uses one
PostgreSQL snapshot for the archive and metadata, checks that pg_restore
can list the archive, and publishes the directory only after those steps
succeed. Pause role and schema changes while taking the backup. PostgreSQL
pg_dump documentation
Check the exit status in the scheduler and alert on failure. Verify the manifest hashes before restoring, then rehearse the restore and collector handoff below. Retain the migration-file checksums, deployment check output, worker image digests, and corresponding broker backup with the recovery point.
Restore collector assignments¶
PostgreSQL role OIDs belong to the source cluster. During backup, keep role and assignment changes paused and capture the OIDs with their role names. Save the result alongside the database archive without any role passwords. A null name indicates an orphaned binding to resolve on the source before using the backup for a collector handoff.
select coalesce(jsonb_agg(
jsonb_build_object('source_role_oid', b.collector_role_oid, 'role_name', r.rolname)
order by b.collector_role_oid
), '[]'::jsonb)
from (select distinct collector_role_oid from qr_trust.runtime_collector_bindings) b
left join pg_catalog.pg_roles r on r.oid = b.collector_role_oid;
Restore into a scratch database first. Provision the roles named in the
archive and the collector map on the target, then restore the database with
its grants. Pause target role changes and keep the collectors stopped until
their assignments are rebound. Use the saved JSON as the
collector_role_map_json psql variable.
psql -X -v ON_ERROR_STOP=1 \
-v collector_role_map_json="$(cat collector-role-map.json)" \
-f docs/public/network-contracts/reference-postgres-runtime-collector-rebind.sql
The rebind script requires a complete map and a target login for every captured role. It changes the assignments together in one transaction. Verify the restored ledger and a known artifact hash. Then run collector preflight under the restored login and check the expected provider endpoint, policy scope, and destination URL before resuming collection.
Recover the reference JetStream broker¶
The single-node reference stack keeps JetStream data in the nats_data
volume. Coordinate its recovery point with the PostgreSQL backup. Pause
publication, wait for the outbox and durable acknowledgements to settle, and
stop the workers and broker gracefully before taking a cold copy of the
JetStream store. Retain the server version, backup checksum, stream sequence
ranges, and durable acknowledgement positions alongside the backup.
Restore the verified store into a new, empty volume. Start a scratch broker with the same server version and the matching configuration and credentials. Compare stream subjects, message contents, sequence ranges, and durable positions before connecting workers. Connect the runtime subscriber to the scratch broker and restored PostgreSQL database. Verify that the next delivery is acknowledged and that replay of a known artifact leaves one runtime observation for its hash.
For managed or clustered deployments, use the deployment's supported JetStream backup procedure and retain consumer state when the recovery plan depends on it. NATS disaster recovery
Schedule and retain coordinated recovery points¶
Choose the recovery point objective and maximum time the reference stack can pause publication. Schedule the combined backup inside that window and allow only one combined backup at a time. For each recovery point, record a shared identifier with the PostgreSQL and JetStream archive digests, database schema revision, broker image digest, stream sequences, and durable positions. Pause new publication requests, scanner decision writes, and collector runs while the workers drain. Verify that artifact-publication and verifier-cache work have no pending or processing rows, the outbox has no pending or publishing rows, and the broker durables have no pending deliveries or acknowledgements. Review failed work before selecting the recovery point. Stop the workers after the drain and keep application writes paused until both snapshots are captured. Save the drain checks alongside the archives.
In a private staging directory for the pair, put the PostgreSQL bundle in
postgres/ and name the cold broker archive jetstream.tar. Save the broker
inventory as broker-catalog.json with server_name and a catalog object
keyed by stream name. Record each stream's messages in sequence order with
their seq values, and include all configured durable consumers in its
consumers object. Record each consumer's ack_floor, num_pending, and
num_ack_pending. Save application queue counts in drain.json under
artifact_publication, verifier_cache, and outbox, each with in_flight
and failed counts.
python3 scripts/qrtrust_recovery_point.py seal "$pair_dir" \
--id "$recovery_point_id" --broker-image "$broker_image_digest"
python3 scripts/qrtrust_recovery_point.py verify "$pair_dir"
The seal step checks the archived files and drain records before writing
recovery-point.json. It refuses to replace an existing index. The verify
step checks the index and file hashes against the received copy before
restore. Generate the inventory and capture both archives during the same
pause, then verify the restored database, broker catalog, and replay as
described above.
Keep a verified copy of each retained pair outside the source host's failure domain. Check that the configured backup volume is mounted before running the copy. Use a private storage directory on a filesystem that supports advisory locks and atomic directory rename.
python3 scripts/qrtrust_recovery_point.py copy "$pair_dir" "$backup_storage" \
--require-separate-filesystem
python3 scripts/qrtrust_recovery_point.py verify "$backup_storage/$recovery_point_id"
The copy verifies both the source and the bytes on the destination before publishing the recovery point under its ID. An interrupted transfer can leave a hidden staging directory. Verify that the transfer has stopped before removing that directory. Keep the previous verified pair available throughout the transfer.
Review local retention candidates with the same destination and the policy's approved count and minimum age. The plan preserves the newest verified pairs and holds any local point whose replica is missing, unreadable, or different. It reports candidates without deleting them.
python3 scripts/qrtrust_recovery_point.py retention-plan "$local_points" \
"$backup_storage" --require-separate-filesystem \
--keep "$retention_count" --min-age-days "$retention_min_age_days"
Track backup age, copy failures, available storage, and the last successful scratch restore. Apply retention to whole pairs after the off-host copy is verified. Rehearse using that copy and measure the time to resume the subscriber and collector against the recovery objective.
Run the capture and copy from the deployment scheduler¶
Use the one-shot schedule entry with capture and resume executables from the deployment. Both receive the private staging directory and recovery-point ID as positional arguments. The capture executable pauses writes, drains the queues, and captures both archives and their evidence before returning. It keeps writers paused and waits for its foreground commands to finish. The resume executable reconciles the services after success or partial capture and returns success only after writes can resume. Rehearse the two executables against the actual deployment before enabling the schedule.
For the Compose reference stack, record the project and the container IDs and running states before stopping services. Check those identities again before resuming. Bring the broker and API to a healthy state before starting their workers and the scanner. Resume services that were previously running and return scheduled collectors to their normal cadence. Verify the broker catalog and service readiness before reporting resume success.
python3 scripts/qrtrust_scheduled_backup.py \
--local-root "$local_points" --storage "$backup_storage" \
--broker-image "$broker_image_digest" \
--capture "$capture_executable" --resume "$resume_executable" \
--capture-timeout "$capture_seconds" --resume-timeout "$resume_seconds"
Invoke the same job with the same local root for scheduled and manual
captures of this stack.
The job locks the root, attempts resume after capture, seals the local pair,
and verifies the replica. It records phase results and hook output under
.backup-jobs/. Exit 0 means a verified replica, 75 means a concurrent
job already holds the lock, and 1 means a failure. Treat a failed resume
as a service incident. After a failed resume or abrupt job exit, the job
blocks new captures. Confirm the earlier capture processes have settled and
then rerun the command with --resume-pending to run the original resume
executable without another capture or copy. Leave enough time for resume
when setting the scheduler's overall deadline. The capture and resume
timeouts cover their own commands. Use the scheduler to monitor the
remaining copy time.
Give the backup and readiness check separate scheduler entries so a missed
backup can still raise an alert. Run both under the backup account with
absolute executable, hook, and data paths. If the entries use shell wrappers,
use exec for the Python command to preserve its exit status. Configure the
scheduler or monitor to retain the JSON result and alert on failed runs.
On the target, verify that the timer starts both commands and that a failing
status result reaches the operator before enabling unattended backups.
If replication fails after the local pair is sealed, retry using the copy
command and that pair's ID. This avoids another pause for a fresh capture.
Use the separate retention review after confirming the destination replica.
Monitor recovery readiness¶
Run the status check from an independent monitor so it can detect a missed backup. Supply the deployment's maximum backup age and minimum free space.
python3 scripts/qrtrust_recovery_point.py status "$local_points" "$backup_storage" \
--require-separate-filesystem --max-age-seconds "$maximum_backup_age" \
--min-free-bytes "$minimum_backup_free_bytes"
The command reports the age of the newest integrity-verified replica, free
space, the last completed job, and whether a capture is running or needs
resume. Exit 1 with an issue list signals a condition requiring attention.
If a newer replica fails verification, the status reports the failure and
identifies the newest usable fallback. An exact retry of a sealed local
pair can resolve a copy failure while preserving the original job receipt.
Monitor the last successful scratch restore separately as evidence that
the archived system can still be recovered.
Drift Handling¶
If the deployed migration files differ from the approved manifest:
- Do not start workers.
- Do not delete the ledger row.
- Compare the approved checksum to the current migration file.
- If the change is intentional, create a new migration.
- If the checked-in file was accidentally edited, restore the migration file to the applied checksum.
If a known revision is pending, confirm the database target and restore point before applying it. If the ledger contains an unknown revision, stop the local rollout and match the database to its deployment.
Worker Start Policy¶
The standalone make up-network-*-worker targets check the database through
the same Compose network path as the worker. The database must already exist
and be at its Alembic head. The HTTPS NATS stack targets start the API, wait
for its normal migration and health checks, then check the head before starting
workers. For a direct Compose launch, run the status check before selecting
worker services.
Worker schema dependencies include:
- artifact-publication worker requires
artifact_publication_work_items,published_artifacts, andevent_outbox - verifier-cache worker requires
verifier_cache_work_items,verifier_cache_entries,scanner_decisions,trust_keys, andpublished_artifacts - event-outbox worker requires
event_outbox
If readiness is not green, the operator should leave workers stopped. A partially working schema can produce misleading scanner outcomes because publication, cache derivation, and propagation are intentionally separate stages.
Production Adoption Notes¶
A production deployment should replace the local runner with the platform's approved migration mechanism while preserving the same controls:
- checksum or immutable migration artifact tracking
- backup and restore verification
- additive-first migrations
- no automatic destructive rollback for trust evidence
- pre-worker readiness gate
- post-deploy table and ledger inventory
This keeps the reference implementation faithful to the paper: scanner-visible trust depends on governed source state and derived verifier cache state, not on best-effort runtime side effects.