On this page
- Status: Accepted — implemented 2026-07-15
- Owner: Platform owner; destructive same-org restore requires an operator confirmation and recovery review
- Related: ADR 0010,
docs/plans/ops-center-implementation-plan.md,docs/SECURITY.md - Decision scope:
org_data_jobs, archive export/import library, org-data worker, super-admin API
Context#
Tenant backup/restore must copy many related tables while preserving foreign keys, natural-key uniqueness, is_sample, and tenant isolation. The earlier import design depended on session_replication_role=replica/superuser behavior and multiple subprocess phases. That could disable referential checks, bypass RLS, partially restore on a later failure, accept the wrong tenant artifact, or replay a different source row after the request was approved.
Tenant archive is not PostgreSQL disaster recovery. It is an operator feature for scoped export, safe cloning, and controlled same-tenant recovery; PITR and object-store recovery remain separate platform obligations.
Decision#
Frozen request receipt and retention
- Restore accepts an exact completed backup job UUID, validates its artifact key and 64-hex SHA-256 in the source-org RLS scope, locks it while creating the request, and freezes
{mode, artifactJobId, sourceOrgId, artifactKey, artifactChecksumSha256}on the restore row. source_artifact_job_idis a foreign-key retention lock. A referenced backup cannot be deleted while a restore record depends on it.- The restore job, audit event, target-organization creation/policies when applicable, and durable outbox intent commit atomically.
- A preset backup freezes both the reviewed profile ID and the exact discovered table list on the job receipt. The worker intersects that list with the archive ACL and permanent exclusions; it never expands a profile back to every table in a broad category.
Selective backup profiles
third_party_market_intelligencecontains the reviewed external market/social fact tables plus the requiredbrandsparent. It deliberately omits AI, users/RBAC, connections/secrets, runtime state, and market-intelligence operator settings/watchlists.first_party_operationalcontains reviewed commerce, CRM, inventory, media-performance, and web-analytics facts plus the exact mapping/brand/category parents required to preserve referential integrity. It also omits AI, users/RBAC, connections/secrets, and runtime state.- Custom category selection remains available for same-environment operator recovery. Presets are exact table contracts; categories are retained only for display and restore selection compatibility.
- Profile compilation fails closed when any reviewed business or support table is absent from catalog discovery. The artifact manifest records format version 2, profile ID, categories, and the exact exported table receipt; import requires that receipt to match the ordered table plan, while version-1 category archives remain readable.
- Cross-environment artifact ingestion is supported only through the super-admin upload path. The upload records the manifest source organization and checksum, excludes secrets/runtime state through the archive contract, and defaults to a new-org clone; overwriting an existing target requires the same explicit slug confirmation and completed safety snapshot as native same-org recovery. Imported archives may use an older migration head only when target-column compatibility (unknown archive columns and required target columns) passes before COPY. This remains tenant-data transfer, not PITR or a substitute for encrypted off-site disaster recovery.
Artifact verification
- The worker uses the frozen receipt; it does not rediscover the source artifact through a broad cross-org query.
- It verifies the downloaded byte stream against the frozen SHA-256 and verifies the manifest source organization before any import SQL runs.
- Archive/table/path/UUID inputs are allowlisted or validated. PostgreSQL COPY text is encoded so embedded
\.cannot terminate input and inject subsequent commands.
Atomic database restore
- The runtime is
yng_worker, never a superuser orBYPASSRLSrole. - Export runs every client-side
\copyin one psql session underBEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY, pins the exact organization/brand RLS context before the first read, and derives manifest row counts from the completed CSVs. All exported table rows and counts therefore share one database snapshot. Catalog selection, organization labels, and the recorded migration head are planned immediately before that session rather than read inside it; deployment coordination must still prevent concurrent DDL, and the artifact remains a tenant-data export rather than WAL/PITR. - Restore builds one psql script: begin, pin RLS, acquire locks, create typed temporary staging tables, COPY validated data, apply deterministic remaps, perform dependency guards, write destination tables in FK order, conditionally quarantine staged connectors, update the durable completion receipt, and commit.
- Any parse, cast, uniqueness, FK, check, dependency, or subprocess failure rolls back the entire database mutation.
session_replication_role, policy disablement, and RLS bypass are forbidden and regression-tested.
Restore modes
to_new_orgis the default. The API generates the organization UUID, establishes role policies, and the import remaps organization IDs, UUID primary keys, references, and discovered global text natural keys so source and clone can coexist.into_same_orgrequires exact slug confirmation and a completed automatic safety snapshot before destructive writes. There is no bypass switch.- The API pre-creates that safety-snapshot job receipt in the same transaction as the restore request and outbox intent. The archive worker has update-only access to claim and complete the frozen receipt; it cannot mint an unapproved backup row. Cancellation and pre-import failure move the paired receipt to a terminal state.
- Connector rows are normally excluded. If a future reviewed artifact explicitly stages them, only those staged rows are quarantined inside the transaction; restoring unrelated categories never clears existing same-org connector secrets.
- For
to_new_org, missing tenant-parent references fail closed; nullable references to intentionally excluded global parents are detached, while required global references remain verbatim and must satisfy the target database FK at commit. - Identity-bound rows whose global uniqueness includes an existing user (for example briefing user/persona/date) are not portable to a coexisting clone. The portable clone journey excludes that
othersurface; selecting it fails atomically until a separately approved user-migration/remapping contract exists.
Interruption and resume (2026-11-06)
A worker restart, deploy or OOM resumes a running job instead of failing it.
- Boot reclaim runs before any job is consumed.
app_archive_reclaim_orphaned_jobs()requeues everyrunningrow (status = 'queued',error_class = 'transient') and writes a resume intent tojob_outboxwith job id<row id>-resume-<attempts_made>; the dead run's BullMQ job keeps the row id until its 60-minute lock expires, and the claim CAS makes its late delivery a no-op.attempts_madecounts claims; a row at 3 claims fails with a request-again message instead of looping. A safety snapshot returns toqueuedwith its requeued restore, and fails with a restore that is not resumed. - Deploys checkpoint and exit. On SIGTERM the archive pool aborts every archive child (
interrupt.ts→runChild), so psql closes its session and the open transaction rolls back within the 15 s shutdown budget. The processor leaves its rowrunningfor the next boot. - Backup stages are idempotent. The export is redone in full (one snapshot; per-table checkpoints would break its consistency). The artifact key is stable per job (
org-backups/<slug>/<created_at>-<id>.tar.gz), so a re-run overwrites its own partial upload. After upload the worker reads the object back and compares length and SHA-256, then checkpointsprogress.stage = 'uploaded'with the key and checksum. A resumed run that finds the checkpoint re-verifies the stored object and completes; one that does not verify is exported again.completedis written only whilestatus = 'running'; a row reclaimed or cancelled under the run keeps its state and the run deletes its artifact. - Restore stays one transaction. A row still
runningproves nothing committed, because the data and thecompletedrow commit together. The safety snapshot is the restore's one durable checkpoint: once its key is frozen on the receipt, a resumed restore skips it. The snapshot is read back and verified before any destructive write. - One archive transaction per org at a time. Restore scripts take
pg_advisory_xact_lock(hashtextextended('yng-org-archive:<org>', 0))and exports take the shared form, so a resumed restore waits for a killed run's backend instead of interleaving with it. Each session setsidle_in_transaction_session_timeout = 10minandclient_connection_check_interval = 10s, which end that orphaned backend. - Safety-snapshot retention (off by default). When
ORG_SAFETY_SNAPSHOT_KEEPandORG_SAFETY_SNAPSHOT_MAX_AGE_DAYSare both set on the archive worker, a completed same-org restore deletes that org's completed snapshots outside the newest KEEP that are older than MAX_AGE_DAYS (object, then row), unless a restore uses one as its source. Unset, nothing is pruned. Proposed values pending operator ratification: 3 and 30 (retention.ts).
Alternatives considered#
- Disable FK/RLS through replication role: rejected; it requires elevated privilege and permits structurally invalid or cross-tenant writes.
- Delete/COPY table-by-table with independent commits: rejected; a late failure leaves a partially restored tenant.
- Trust object key or mutable source row at execution time: rejected; approval could be applied to different bytes or a different tenant.
- Restore directly into the source tenant by default: rejected; safe clone is a lower-risk diagnostic and recovery path.
- Treat tenant export as PITR: rejected; it omits shared infrastructure, WAL history, queues, and complete platform configuration.
Threat and failure model#
The design covers corrupted/truncated archives, object substitution, cross-org receipts, path/table/COPY injection, natural-key collisions, FK ordering, external references into rows being replaced, and any database error during import. Database mutation plus the completion receipt is atomic. Import preflight bounds compressed bytes, archive entries, index output, manifest bytes, portable tables, and declared row counts before mutation. The surrounding download/upload/queue workflow is not exactly-once; a worker loss around subprocess completion can require outcome reconciliation. The synchronous subprocess path still needs measured execution deadlines and decompressed-byte budgets for complete resource governance. It assumes the migration-defined helper/policy contract and trusted object-store credentials, and does not replace encrypted off-site backups or protect against compromise of the database owner/object store.
Compatibility and migration#
- Schema changes are additive (
source_artifact_job_id, index/FK, frozen receipt fields already represented in job scope). - Existing native archives remain readable when their recorded checksum is present and their manifest schema head is either the target's head or a migration the target has already applied (an older archive restored forward). Both that case and an imported archive's compatible older head run the pre-COPY target-column guard described above: an archive column the target dropped, or a required target column the archive lacks, refuses with
ImportArchiveErrorbefore any mutation. A head the target has never applied (a newer archive, or one from a diverged environment) refuses withImportSchemaMismatchError, whose message says to deploy the environment to at least the archive's schema and request again. Decided 2026-11-06: every migrating deploy otherwise made each native backup un-restorable in one click, and the column guard already decides compatibility for imported archives. Data-only migrations between the two heads are not replayed onto restored rows; that residual matches the imported-archive path. - Existing version-1 manifests are accepted by the current importer; version-2 selection metadata is additive and becomes the provenance source for newer tooling.
- Unsupported or malformed legacy artifacts fail before mutation and require a reviewed conversion; the worker never guesses.
Rollout#
- Apply schema/helper migrations and verify worker role probes.
- Deploy checksum/receipt-aware workers before exposing new restore requests.
- Exercise
to_new_orgagainst isolated data categories and verify counts/constraints/connectors. - Exercise a same-org restore only in a production-like recovery environment with its safety snapshot.
- Record duration, archive size, table/row count, rollback behavior, and operator evidence.
Rollback#
- Before import starts, cancel only through the queued-state compare-and-set.
- A failed in-flight import rolls back automatically.
- For a completed same-org restore, the automatic safety snapshot is the recovery input; restoration from it is a new audited request, never an ad-hoc database bypass.
- Keep additive schema and archive metadata when rolling application images back.
Evidence and metrics#
- Worker unit suites cover script construction, injection defenses, source receipt, natural-key remapping, dependency guards, and error classification.
- Live role probes cover RLS, locks, temporary tables, and COPY round-trips under
yng_worker. - Operator E2E covers backup creation and restore-to-new-org lifecycle; same-org destructive behavior is additionally protected by pure gates and the mandatory safety-snapshot path.
- Metrics: archive bytes/rows/tables, duration by phase, checksum failures, rollback/failure class, safety-snapshot completion, restore completion, and open DLQ entries.
Consequences#
Tenant restore is slower and more explicit than a privileged bulk load, but its database mutation and completion receipt are auditable, replay-resistant, RLS-preserving, and atomic. Tenant table CSVs are point-in-time consistent within one export snapshot, while the end-to-end object/queue workflow is not exactly-once and the artifact is not a full-system backup. Full-system DR remains open until encrypted PITR, off-site replication, decompressed-byte/deadline enforcement, outcome reconciliation, and measured recovery drills satisfy ratified RPO/RTO.