Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Backup & Disaster Recovery
Data-redundancy truth: clustering is NOT replication. Every durable Sol table is
disc_copieson the single local node (sol_event_store_owner.erlschema blocks); distributed Erlang in ZERG coordinates lanes/catalog/lease ownership, it never replicates storage. A node loss therefore loses that node’s event/task history back to the last Mnesia backup — the backup is a file-level timer (sol_mnesia_backup), and a “3-node cluster” still has a single-node durability story. Plan RPO from the backup interval, not from node count; the outbox/journal artifacts below are the in-flight safety net, not a substitute.
Backup and restore for the full state set of a Zerg deployment. The state lives in several places, each with its own tooling:
| State | Owner | Storage | Backup tool |
|---|---|---|---|
| Orchestration state (events, tasks, workflows, sessions metadata, projections) | Sol | Mnesia | sol_mnesia_backup (built-in, automatic) |
| Scheduled jobs | Sol | filesystem — <data_dir>/scheduler_jobs.json | file-level copy of the data_dir |
Sol durable artifacts: the audit JSONL chain + signed checkpoint, dispatch_outbox.journal, memory_wal/ segments (+ live.manifest), sync_event_shed.log (+ .replaying), the compactor staging set (.dump/.cursor/.count), the archive quarantine dead-letter and the event lane-spill file | Sol | filesystem | built-in: bundled into each sol_mnesia_backup artifact directory. The CURVE node private key is deliberately never bundled (SEC-X2); restore it from your secret store |
Remaining Sol data_dir files: zmq_replay_fence.term / zmq_replay_fence.journal / zmq_replay_fence.journal.prev, the enrollment key file(s) (zmq_enrollment.json / the locally-minted zmq_enrollment_local.json), scheduler_jobs.json / scheduler_jobs.journal, managed_settings.json, coordinator.json | Sol | filesystem | operator copy set: listed in the backup’s manifest.json omitted array (generated from sol_backup_manifest:omitted_paths/0 and pinned to this table by ci/manifest_omitted_parity_lint.py; the CURVE keyfile is excluded by design, SEC-X2); copy them with the data_dir (§5). The built-in bundle cannot carry them (live writers / node-identity material) |
| Memory/embeddings + Mango identity/auth | Sol + Mango | PostgreSQL (optional) / SQLite | pg_dump / sqlite3 |
| Worker sessions (JSONL + SQLite/FTS5), memory files, git snapshots | Luna | ~/.luna/ tree | file-level copy |
| Config + secrets | all | env/config files, /fun/secrets (wild) | config archive + rotation (below) |
Operator context: on a wild-managed host, “the Sol box” is the running
zerg-solpodman container on blue. Erlang-shell access to the live node is viapodman execinto that container (the archived on-host runbook’s remote-console section is historical — the oldsolctlscript was removed in ); image-level state (Mnesia data dir) is per-container storage owned by wild’s runit definitions — see the WILDZERG operator runbook.
1. Mnesia (Sol orchestration state)
Automatic: sol_mnesia_backup (server/src/sol_mnesia_backup.erl)
runs mnesia:backup/1 every mnesia_backup_interval seconds (default
3600 — ?DEFAULT_INTERVAL, line 68), FSYNCS the backup output before the
backup may report ok ( — mnesia_backup_ok=1 is never a page-cache
truncation lying in wait), prunes backups by AGE —
mnesia_backup_retention_days, default 7 (: the real
recovery horizon is the configured days) — with DATE-BUCKETED count
capping: every backup within the window survives, and
MAX_BACKUPS=5 is a PER-UTC-DAY cap (the newest 5 files of each day,
older same-day extras dropped with their manifests), never a global
post-prune cap. The previous global cap silently truncated the horizon
to ~5h at the default hourly interval while the docs claimed 7 days; the
per-day cap keeps disk bounded by days × 5 files without crossing a day
boundary. Each backup also gets a .manifest with per-table
record counts + a sha256 content checksum (checksum verified FAIL-CLOSED
at restore); each backup’s DATA FILE and its .manifest are optionally
copied to sol_mnesia_backup_remote_path (: the
destination is a DIRECTORY; the data file and its .manifest travel as a
pair in one rsync with --delay-updates, and the destination manifest is
pulled back and checksum-verified. A missing/mismatched manifest is a copy
failure — the offsite pair is accepted only after the manifest bytes verify;
an interrupted or partial pair is NOT claimed restorable. A local/mounted
destination is copied through fsynced temp names + atomic renames). An
offsite failure fails the backup for the SolMnesiaBackupFailed alert — the
local file stays intact; the caller ack is the pair, not the data file
alone. : a LOCALLY-MOUNTED destination is
pruned by Sol with the same age/per-day retention, and its free space is
probed (sol_mnesia_backup_offsite_free_bytes); a REMOTE destination cannot
be pruned by Sol, so mnesia_backup_offsite_lifecycle_managed=true attests
an external lifecycle policy — otherwise sol_mnesia_backup_offsite_managed
is 0 and SolBackupOffsiteUnmanaged pages.
** (EV-18) artifact bundle.** Every backup carries a
<backup>.artifacts/sibling: the auditaudit-*.jsonlfiles
- the signed
audit-chain.checkpoint(and.audit_seq/.audit_sigwhen present),dispatch_outbox.journal, thememory_wal/segments +live.manifest,sync_event_shed.log, the event-lane spill file, the compactor staging set (.dump/.cursor/.count) and the archive quarantine dead-letter — each copied 0600 with a sha256manifest.json. The compactor staging/lane-spill/quarantine files live under the Mnesia directory and hold events already deleted from Mnesia, so they are exactly the mid-archive window a Mnesia-only restore used to lose. The manifest also records the operatoromittedcopy set (the node-identity/live-writer files in the table above), so a restore never assumes completeness.Consistent cut. The writer flushes the audit chain and the memory WAL, takes a durable audit cut (
sol_audit_log:snapshot_cut/0— flush + signed checkpoint), copies the sources, then re-reads the live checkpoint and RETRIES the cut when a flush raced the copy. The anchoredcut_seqis stamped in the artifactmanifest.json. At restore a bundle whose copiedaudit-chain.checkpointis AHEAD ofcut_seqis REFUSED ({error, {backup_cut_ahead, Cp, Cut}}) unless the operator accepts it with--allow-cut-mismatch(CRITICAL + degraded verdict, never silent). Acut_seq: nullmanifest is a legacy/chain-less bundle. The CURVE node private key (curve_server.cert) is deliberately NEVER bundled (SEC-X2 — a backup copy must not carry the node identity secret); reprovision workers withsol_zmq_curve:provisioning_info/0after a node rebuild. The destructive restore re-materializes the bundle only when called withrestore_artifacts => true(the offline entry point defaults it ON); every hash is verified before a file is written to its CURRENT configured destination. A clean restore leaves the audit chain verifiable against its restored anchor (sol_audit_log:verify_integrity_anchored/0). The bundle is local to the backup directory — ship it offsite with the backup file in the composite procedure (§5).
Retention drill (executable):
scripts/backup-retention-drill.sh --sol-root /opt/sol \
backup-dir /tmp/zerg-retention-drill
It builds a >5-bundle fixture and runs the real rotate_backups/1:
the 10-day-old backup + bundle are pruned, 6 same-day backups leave the
newest 5, each kept backup’s .artifacts/ survives, and unparseable
legacy names are capped at 5. The drill’s legacy leg is the proof
that .artifacts DIRECTORIES are not retention entries:
sol_mnesia_backup:rotate_backups/1 filters .manifest/.artifacts and
requires regular files, and the drill PASSES on that corpus.
Bundle dirs are deleted with their parent.
Backup directory resolution (lines 92-109), in order:
- config
mnesia_backup_dir— honored only when set (set it ABSOLUTE; sys.config ships an anchored/tmp/sol/mnesia_backupssince then a CWD-relative value here silently orphaned backups on a different-CWD restart); <mnesia_dir>/backups— the anchored default (under the Mnesia data dir; the old CWD-relativepriv/mnesia_backupsdefault was removed in Because a container restart from a different CWD silently orphaned backups).
Manual backup (live node, Erlang shell):
sol_mnesia_backup:backup(). %% returns {ok, Filename}
sol_mnesia_backup:list_backups(). %% {ok, [FullPath,...]} — newest last
Restore (requires Sol stopped; the restore clears and recreates the disc tables so the backup IS the state — semantics; since RAM-FALLBACK tables are cleared too, so a degraded boot cannot silently merge and resurrect deleted rows).
restore_latest/1 is a gen_server call into the backup process — it
only works while the Sol application is running. The previous runbook
said “stop Sol” and then called it, which was unrunnable. Use the
offline entry point; it boots a minimal BEAM (Mnesia + the backup server
only, under the release schema’s node name), runs the restore, prints the
typed verdict, and exits non-zero unless {ok,...}:
# Sol must be stopped (Mnesia holds an exclusive lock on its directory).
scripts/sol-restore.sh --sol-root /opt/sol --yes
--yes skips the interactive confirmation; the script otherwise prints
the target node/config/Mnesia/backup paths and asks for restore. Options:
--mnesia-dir, --data-dir (artifact destination), --backup-dir,
--config, --no-artifacts, --spill-receipts. The same documented
command is exercised by scripts/restore-drill.sh against a scratch data
root. Raw mnesia:backup output has no manifest and is REFUSED by the
restore (below) — always back up through sol_mnesia_backup:backup/0.
Verification is automatic and TWO-LEGGED: a pre-flight checksum check
refuses the restore BEFORE any live table is touched (truncated/tampered
backups never destroy anything), and the post-restore table counts are
compared against the manifest with a 5% tolerance. The outcome is
surfaced as restore_verified / restore_mismatch events (never
swallowed — a drifted restore fails loudly). A live restore also rebuilds
the RAM projections (sol_sync_event:rebuild_projections).
** breaking change:** a backup with NO manifest now REFUSES to restore ({error, manifest_missing}) — an unmanifested backup is a failed backup. Since a manifest-less artifact cannot be produced (a Mnesia-not-running backup fails loudly with {error, mnesia_not_running}); if you hold a previous manifest-less relic, take one fresh backup after upgrading.
Restore order: stop EVERY writer,
then restore Mango (identity) -> Sol memory PostgreSQL -> Mnesia ->
Luna trees -> Sol data_dir operator copy set. Mnesia is restored after
Mango because restored task/session rows carry user_uuid references to
Mango accounts; it is restored before Luna so a re-registering worker sees
its restored workspace. §5 uses this same order — there is no second
variant.
2. PostgreSQL (Mango auth + Sol memory) / SQLite (Mango)
Mango uses one storage backend for identity, RBAC, audit and token state:
Default SQLite: sqlite:///data/mango.db (mango/mango/conf.py:40).
PostgreSQL: MANGO_DB_URL or the MANGO_DB_HOST/PORT/NAME/USER/PASSWORD
variables (conf.py:123-139). Schema is migration-managed
(mango/mango/migrations/v0001_initial_baseline.py + the migration
runner), so a restored schema must not be partially migrated.
Backup commands:
# SQLite backend — online-safe hot copy (safe during operation):
sqlite3 /opt/sol/mango/data/mango.db ".backup '/backup/mango-$(date +%F).db'"
# PostgreSQL backend:
pg_dump -h "$MANGO_DB_HOST" -U "$MANGO_DB_USER" -d "$MANGO_DB_NAME" \
-Fc -f "/backup/mango-$(date +%F).dump"
Restore:
# SQLite: STOP Mango first (sv stop zerg-mango on wild) so no WAL/page
# cache survives the file swap. sqlite3's `.backup` produces a
# transactionally consistent file; the -wal/-shm siblings belong to the
# LIVE database and must never be replayed against a restored file:
sv stop zerg-mango
rm -f /opt/sol/mango/data/mango.db-wal /opt/sol/mango/data/mango.db-shm
cp /backup/mango-<date>.db /opt/sol/mango/data/mango.db
sqlite3 /opt/sol/mango/data/mango.db 'PRAGMA integrity_check;' # must print ok
sv start zerg-mango
# PostgreSQL: STOP/quiesce every Mango writer first (sv stop zerg-mango),
# then restore — `--clean` DROPs and recreates objects; a live writer can
# race the DROP and hold locks:
sv stop zerg-mango
pg_restore --clean --if-exists -d "$MANGO_DB_NAME" /backup/mango-<date>.dump
psql -d "$MANGO_DB_NAME" -c 'SELECT count(*) FROM users;' # sanity
sv start zerg-mango
Sol memory/embeddings (sol_memory_pg, server/src/sol_memory_pg.erl)
is a separate PostgreSQL database when memory_pg_enabled and
memory_pg_url are configured (lines 102-103; the table carries a
user_uuid column migrated at pool start, line 127):
# SOL_MEMORY_PG_URL is the SAME connection URL configure(d) for
# memory_pg_url; pg_dump accepts a connection URI directly (the previous
# runbook called an undefined extract_db_from_memory_pg_url helper). Export
# it from the Sol env (0600) — never inline a password on the command line:
pg_dump -d "$SOL_MEMORY_PG_URL" -Fc -f "/backup/sol-memory-$(date +%F).dump"
# Restore with Sol stopped (the memory pool must not write during it):
pg_restore --clean --if-exists -d "$SOL_MEMORY_PG_URL" \
"/backup/sol-memory-<date>.dump"
The Mango database backup includes the event-archive table
(audit_events) — its own age-retention job and alert are documented in
audit-retention.md §“Archive store”; a first prune
is destructive, so take the database backup before running it.
If both Mango and memory use one PostgreSQL instance, one pg_dump
per database (never one dump of postgres covering both) keeps restores
independent.
3. Luna worker state (~/.luna/ tree)
Each Luna worker host keeps its sessions and memory on the worker machine — they are not replicated by Sol:
| Artifact | Path | Source |
|---|---|---|
| Session transcripts (JSONL, fsynced appends) | ~/.luna/sessions/session.jsonl (per-session files under ~/.luna/sessions/) | client/core/session.lua — the append/save fsync discipline |
| Session search index (SQLite + FTS5, dual-write) | ~/.luna/sessions.db (override: LUNA_SQLITE_PATH) | client/core/session_backend.lua:18 |
| Session index (JSON) | ~/.luna/session_index.json | client/core/session_index.lua:3 |
| Memory (file/vector/hybrid) | ~/.luna/memory* | client/core/memory_file.lua et al. |
| Git auto-snapshots | refs/luna-snapshot/* in each workspace repo (24h cleanup) | client/core/git_snapshot.lua:260-294 |
Backup = consistent file copy:
# Stop the worker first (dual-write consistency), then:
rsync -a ~/.luna/ /backup/luna-$(hostname)-$(date +%F)/
Restore = copy the tree back onto the worker host and restart; sessions
resume by id (zerg/Luna --resume-latest / Limon chat session id), and
the SQLite FTS index rebuilds under the staleness gate on open
. Git snapshots are per-repo refs — included only
if the workspace repos are backed up too.
4. Config, secrets & keys
Sol config archive: server/scripts/backup-config.sh [--remote=DEST]
archives the checkout config, the ACTUAL prod release config
(_build/prod/rel/sol/releases/<vsn>/), and /etc/sol/{sol.conf,env}
into a 0600 archive. Secret-bearing files require --encrypt=RECIPIENT
(GPG); --remote without a destination or a failed rsync is a hard
failure. See docs/production-runbook.md §Config Backup.
Secret inventory (all on blue under /fun/secrets/ on wild hosts,
plus container env files):
Crow: forgejo_token, deploy key + ssh-config, registry auth
(the .crow.yml env: block);
minisign update-signing key: /fun/secrets/minisign — provisioned by
wild’s scripts/release/gen-minisign-key.sh (the minisign signing step);
Mango MANGO_DB_PASSWORD (required for remote PG, conf.py:131);
Sol SOL_ZMQ_WORKER_SECRET / per-worker enrollment keys (zmq-security);
Forgejo admin credentials + INTERNAL_TOKEN/SECRET_KEY/DB password —
rotation covered by docs/forgejo-admin.md (§credential rotation).
Rotation: the legacy in-tree deployment/scripts/rotate-credentials.sh
is archived with the model; the wild repo owns the live rotation
scripts (scripts/rotate-postgres-password.sh is the migration-manifest
replacement — deployment/README.md:20). The zerg-cli update channel’s
TOFU pin (~/.config/zerg/trusted-key) re-pins deliberately via
zerg update trust-key <minisign.pub> (see docs/cli-reference.md
§Updates) — a signing-key rotation MUST be published with the matching
minisign.pub asset on the release.
Recovery plan (fastest path per failure)
| Failure | Restore steps | Verify |
|---|---|---|
| Sol node loss | Redeploy image; stop Sol; run scripts/sol-restore.sh --sol-root /opt/sol --yes | {ok, {restored, N}} verdict + restore_status.json; /api/v1/ready 200 |
| Mango DB loss | Restore SQLite file or PG dump, restart zerg-mango | zerg login with an existing account |
| Memory PG loss | pg_restore sol-memory dump | vector search returns results |
| Luna host loss | Replace worker; restore ~/.luna/ tree | session list + search work; worker re-registers via ZMQ |
| Update botched | zerg update rollback (zerg-cli) or the IMAGE flip (see runbook) | /api/v1/health + zerg update check |
5. Composite DR (multi-store quiesce + dispatch-receipt spill)
A single-store restore is not enough once tasks are in flight: Sol state (Mnesia), Mango (PG/SQLite), Sol memory (PG) and the Luna trees advance independently, and a destructive Mnesia restore clears the dispatch outbox — the durable acknowledged-in-flight task receipts ( ). The composite procedure, in order:
- Quiesce writers (operator command). Pause the scheduler and drain
workers before any backup — the composite quiesce command, scheduler
pause and Mango snapshot marker are provisioned by the wild runbook
(handoff G9; wild-pending — check the operator host before relying on
it). Until the command is available, pause jobs via the scheduler API
and wait for
in_flight = 0. - Back up each store (Sol/PG/Luna per §1–§3). The built-in
sol_mnesia_backupartifact bundle carries the audit JSONL chain (see the retention warning below),dispatch_outbox.journal,memory_wal/segments,sync_event_shed.log, the compactor staging set, the archive quarantine dead-letter and the event-lane spill — ship the<backup>.artifacts/directory with the backup file. The operator copy set (scheduler_jobs.json,zmq_replay_fence.term/journal, the enrollment key file(s) includingzmq_enrollment_local.json,managed_settings.json,coordinator.json) is listed in the bundle manifest’somittedarray — copy those from the data_dir yourself. Audit retention is destructive with NO archive leg: the daily sweep deletesaudit-*.jsonlolder thanaudit_retention_days(default 30) and nothing archives them first — back up the JSONL chain yourself (or raise the retention) before that horizon matters to you. The Mangoaudit_eventsarchive has its own age retention (docs/audit-retention.md§Archive store) and is part of the Mango database backup. - Restore with the stores down, in the §1 order: Mango (identity) ->
Sol memory PG -> Mnesia (
scripts/sol-restore.sh --sol-root /opt/sol yes) -> Luna trees -> the Sol data_dir operator copy set. The restore walks candidates newest→oldest and picks the first VERIFIED one (manifest readback + sha256 + image decode; ). A manifest-less partial newest file is quarantined to<backup_dir>/quarantine/(kept, never trusted) instead of blocking every retry;--backup PATHrestores one explicit artifact and--previousskips the newest candidate. When thesol_dispatch_outboxis non-empty, the Mnesia restore refuses by design with the typed{error, {outbox_nonempty, N}}: the receipts would evaporate silently otherwise. - Spill the receipts deliberately. Pass
--spill-receiptsto the offline entry point (the restore maps it tosol_mnesia_backup:restore_latest(#{spill_receipts => true})) — the receipts are exported to one durable file before the destructive clear and re-imported after it; the gateway’s live reconcile then requeues them at-least-once (the same idempotency key dedupes any duplicate delivery). Verify with therestore_verifiedevent and the outbox row count before and after. - Converge and verify. Let the cluster catalog/inventory converge then run the §Recovery-plan verify column for every store.
The outbox refusal is loud (CRITICAL log + typed error) — never bypass it by deleting outbox rows to force a restore; that is data loss with extra steps.
Composite drill (executable): scripts/composite-restore-drill.sh
builds a real bundle (Mnesia task/terminal rows + a completed HMAC audit
chain + dispatch_outbox.journal, backed up by the production
sol_mnesia_backup, plus a migrated Mango SQLite snapshot taken with
sqlite3’s backup API), restores Mnesia through scripts/sol-restore.sh and
the Mango file-swap, then asserts the same terminal task rows, audit chain
and Mango users/tokens/audit state. It also corrupts the Mnesia backup and
the Mango snapshot separately and requires a fail-closed refusal from each.
scripts/composite-restore-drill.sh \
sol-root /opt/sol \
schema-from /var/lib/sol/data/mnesia \
bundle /backup/zerg-composite-<date> \
scratch /tmp/zerg-composite-restore
Without --bundle it builds its own real fixture (the CI smoke gate). An
operator bundle needs --schema-from (a bootstrapped Sol Mnesia dir): a
real restore destination is a node that already created the table
definitions. The drill clears the destination tables before the restore, so
a no-op restore cannot pass.
Tested / untested
The Mnesia path is exercised by eunit + the documented restore-verification
flow (server/test/sol_ets_table_ownership_tests.erl calls
sol_mnesia_backup:backup), and the OFFLINE restore command above is
executed by scripts/restore-drill.sh (scratch data root; asserts the
verdict, materialized tables, the durable restore_status.json and the
artifact re-materialization). The composite Sol+Mango+outbox/audit path is
executed by scripts/composite-restore-drill.sh (wired into the required
tri-service smoke step via tests/smoke/test_restore_and_upgrade_drills.py).
Retention is exercised by
scripts/backup-retention-drill.sh (age prune, per-day cap, bundles
deleted with their parent, legacy cap ignores .artifacts dirs). The
PostgreSQL/SQLite/Luna paths use standard tooling (pg_dump,
sqlite3.backup, rsync) — validate your restore procedure in a staging
copy of your fleet, quarterly.
See also
WILDZERG runbook — the deploy/rollback flow that pairs with
this page
docs/production-runbook.md — monitoring, incident response, SLOs
docs/security.md — secrets posture, trust plane
docs/forgejo-admin.md — Forgejo backup/restore/rotation
(the git forge itself, separate from the state above)