Snapshot and Recovery Architecture
Maintenance admission, consistent capture, versioned S3 artifacts, and isolated runtime recovery.
The operator workflow is documented in Backups and Recovery.
scripts/backup.py uses Python’s standard library plus Docker and AWS CLI subprocesses. Installed
bundles ship the same implementation at lib/backup.py, exposed by oblive backup. Every snapshot
also carries the standalone script. Keep source, installed, and standalone commands compatible.
Consistency Boundary
Only the selected Compose project is captured. Inventory reads actual containers, image IDs,
environments, and mounts; it requires one running backend and healthy data services (or, with
create --stopped, one stopped backend and no running containers), all seven named volumes, and images for enabled services. Anonymous/nonlocal volumes, unsupported mount types,
external host directories except known credential files, shared live volumes, and unsupported
service isolation fail preflight. Development apps and packages bind mounts include uncommitted
files. AWS credential directories are rejected instead of silently copied.
Local login’s codex-auth-sync service may use the Compose project’s implicit default network.
Inventory accepts that exact project-owned network only for this service; external/custom networks
and other services on the default network remain rejected. Recovery places the saved service on its
isolated network and keeps it inactive alongside the agents.
On macOS, Docker Desktop’s /host_mnt bind paths are mapped to local paths only when the source and
destination match the rendered Compose configuration. Missing, symlinked and unsupported external
sources still fail preflight. Recovery uses the archived copy, not the original host path.
create --stopped captures an already stopped installation, including an inactive recovery copy.
It requires existing container metadata for all seven volumes, rejects any running container or
other live volume user, and checks for restarts before each volume archive and after capture. It
does not call the backend, acquire maintenance, change dispatch, or start services. Recovery mode
and validation status remain unchanged. Recovery inventory includes inactive profiles when reading
Compose configuration; it does not enable them for execution. The source manifest records
captureMode: "stopped"; the normal drain path records "drained".
The long drain uses PATCH /organizations/:id/work-dispatch, not global maintenance. All
organizations in the selected deployment are enumerated before changes. Already-paused organizations
are left alone. For each running organization, the script journals its chosen UTC pause timestamp
before sending {stopped: true, expectedStoppedAt: null, stoppedAt: <timestamp>}. The API applies
an atomic expected-state update. Cleanup sends {stopped: false, expectedStoppedAt: <timestamp>};
409 means another caller owns the current state, which is preserved. Exact retries are idempotent,
including a lost response or a resume whose queue publication must be retried. No schema migration
is needed; ownership uses the existing work_dispatch_stopped_at field.
During this wait, normal UI/API traffic and existing executions remain available. The script polls active chats, starting/running runs, and executing actions for up to 30 minutes. Queued work is excluded. The dispatch switch does not stop every chat or background cycle. Once database activity reaches zero, the script acquires the final maintenance gate and rechecks all writers, including work admitted between the last poll and acquisition. This final drain has a separate 30-second budget, also bounded by the scheduling window. A timeout restores dispatch and releases maintenance without stopping containers. Both deadlines are tested with a simulated clock.
/internal/maintenance accepts the agent service token, never an execution capability. POST acquires
a UUID owner lease, PATCH renews, GET reports protocol 1, dispatchPauseProtocol: 1 and drain state,
and DELETE releases. The script checks both protocols before changing dispatch, rejecting old
backend images without conditional pause support.
The single-process gate has a 120-second lease renewed every 15 seconds. It is deliberately not
persisted into the restored database. Losing the backup process eventually reopens global admission.
Dispatch pauses are durable and are repaired from the local journal by create --resume.
The middleware blocks new public mutations and provider reads, OAuth callbacks, chat claims, and
run claims. Existing internal executions can heartbeat, finish provider calls, synchronize output,
and finalize. Mutating requests and potentially active reads hold an in-flight counter until response
completion. An aborted request remains tracked until its handler ends its response; this also
releases its counter when Bun omits the disconnected response’s finish event. Disconnect alone
never releases unfinished work. Read-only event streams do not hold a drain
counter. Each background cycle checks admission and acquires its counter synchronously before
the first await. Existing cycles complete; new cycles wait.
Drain combines those counters with active chat messages, starting/running runs, and executing actions in PostgreSQL. Queued work is excluded. Workers retain Redis entries on a 503; chat claims remain retryable. Normal scheduler reconciliation republishes pending chat notifications after maintenance ends. A stuck tracked operation fails the short final drain closed; counters are never reset or ignored to force a capture.
Capture and Publication
The installation has a nonblocking file lock and private .runtime/backup/journal.json. Images
are exported before downtime. After drain, a timestamp prefix is reserved using an S3 conditional
write. Agents and frontend/auth synchronization stop before backend and data services. Forced or
failed stops invalidate capture. Archive helpers use the saved backend image, --network none,
read-only source mounts, and numeric ownership. Bind fingerprints and live-volume checks detect
concurrent host edits or container restarts.
Restart uses existing container IDs, with no Compose regeneration, removal, or pull. Failures
trigger restart attempts for every previously running service. A crash leaves durable restart intent;
create --resume repairs that and any owned dispatch pauses before requiring AWS access.
Cleanup attempts every organization and retains unresolved pauses in the journal if the backend
is unavailable. Only a fully restarted installation with dispatch cleanup complete may publish.
Failed uploads retain staging and
reuse the completed capture. New capture, restart, and upload failures have distinct status phases.
Resume a stopped-instance capture with create --stopped --resume. It uses the same archive,
publication and verification paths, with no service restart to recover. This option rejects a
journal from the normal drain mode, which must retain its original cleanup semantics.
Storage format 1 contains:
snapshots/<UTC timestamp>/RESERVED, immutable ownership of the timestamp prefix;- seven volume archives, an installation archive, the tool, and recovery instructions;
- images under
images/<OS>/<architecture>/<sha256 image identity>.tar.gz; - a manifest with capture time, deployment and source/release identity, effective services,
mounts, platform, image identities, sizes, SHA-256 hashes, and optional
workDispatchPauses; and COMPLETE, a conditional final write pointing to the exact manifest version and checksum.
Every artifact reference includes its S3 version ID. Retries may create new versions of incomplete artifacts, but cannot replace another completed snapshot. Images are reused by identity and platform. Multipart uploads use AWS CLI’s SHA-256 validation and SSE-S3. An S3 multipart composite checksum or ETag is not a full-file SHA-256; the manifest records a separate full-file digest that every download verifies. See S3 integrity semantics.
Normal backups do not edit bucket configuration or delete snapshots. Explicit bucket initialization enables public-access blocking, versioning, SSE-S3, and incomplete multipart cleanup. Read/write operators need STS identity lookup, bucket location/access/versioning/public-access inspection, object listing, object version reads, puts, and multipart upload permissions. Bucket initialization additionally needs bucket creation and configuration permissions. Scope object access to this dedicated bucket; AWS credentials are provisioned outside the snapshot.
Recovery Boundary
Restore rejects an occupied target or existing target project/volumes. It verifies COMPLETE, all
versioned downloads, tar paths and links, and the Docker architecture before loading the runtime.
Up to four archives download concurrently, each with its original version, size and checksum checks.
A failure cancels queued downloads and waits for active reads before staging cleanup.
The saved helper extracts archives with numeric ownership. Restore checks a unique ownership label
before populating each new volume. An incomplete restore retains its target for diagnosis.
The generated compose.restore.json references exact image IDs, disables builds and pulls, removes
migration dependencies, relocates binds, and publishes only loopback ports. Compose dollar escaping
preserves literal credentials and shell commands. Dynamic Docker hostnames are regenerated. Codex
authentication is seeded from the restored state volume instead of an older host credential file.
OBLIVE_RECOVERY_MODE=true skips startup catalog/integration/schedule reconciliation and all
background jobs. Its HTTP allowlist serves stored records and health, rejecting provider and internal
execution routes. Docker’s internal network supplies a second boundary against provider egress.
The verification command reads PostgreSQL/Redis, streams saved objects, compares database-owned
content hashes, and decrypts credential envelopes without printing secrets or calling providers.
recovery.json persists the activation decision. Activation requires successful validation, explicit
confirmation, and no running source containers/project. It commits the decision before starting any
normal-mode containers; a failed startup rolls configuration back to recovery and removes stopped
containers without deleting volumes. The generated launcher reconciles persisted mode before start.
The snapshot database contains the temporary dispatch pauses present at capture. The manifest’s
workDispatchPauses map carries those owned timestamps into recovery.json; explicit activation
conditionally clears only those pauses and republishes ready requests. Inactive recovery never
resumes them. An interrupted activation retries pending dispatch cleanup on the next normal-mode
start. Older manifests without this optional field retain their existing behavior.
Tunnels and backup schedules always require separate opt-in. External actions cannot be rolled back.
Scheduling and Release Compatibility
Schedules call the same script with the absolute root and Python path. A five-minute host timer checks the configured timezone’s 02:00–04:00 window, with at least 15 minutes between attempts. Image export or drain cannot cause a new daytime capture. Awake-host and noninteractive AWS access requirements are explicit. Installation requires a local successful backup and restore record.
Release updates preserve backup configuration and success/restore status, and reject a pending backup journal. Never run direct Docker lifecycle changes or source edits concurrently with capture. This feature requires a coordinated application release because older backend images do not expose the maintenance and recovery protocol; a bundle-only release is insufficient.
Validation
python3 -m unittest discover -s scripts/tests -p test_backup.py
bun test apps/backend/tests/services/maintenance.service.test.ts
bun test apps/agents/tests/chat-runtime.service.test.ts apps/agents/tests/worker-runtime.service.test.ts
.github/scripts/tests/deployment-bundle.test.sh
.github/scripts/tests/portable-install.test.sh
bash .github/scripts/tests/portable-instances.test.sh
bun run check:all
bun run testPython tests exercise versioned artifact round trips for all seven volume payloads, source edits, test secrets, file modes and symlinks; interrupted uploads and restarts; collisions, corrupted objects, architecture rejection, scheduling windows, overlap, and activation guards. Runtime tests cover maintenance leases, drain counters, background cycles, queue preservation, and admission rules. Dispatch tests cover pagination, pause ownership, concurrent updates in PostgreSQL, lost responses, timeout/defer, partial cleanup, AWS-independent recovery, and restored dispatch activation. These tests use simulated Docker/S3 boundaries and do not establish live recovery readiness.
Before enabling nightly backups, perform a manual snapshot and a clean restore with records/files in all seven volumes, source edits, numeric owners, and test credentials. Use a fresh same-architecture host with registry access disabled and no checkout/Bun. Verify startup, content hashes, decryption, and absence of agents/provider actions before activation. Repeat for source and installed named instances. Development deployment and this live acceptance run remain an operator rollout step.