Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Engine reference — generated from the canonical engineering source. Do not edit this page by hand.

Audit Log Retention (Mango)

Status: implemented (, /; migration v0014; event-archive audit_events retention added ). Scope: the Mango relational audit store (audit_logs). Sol’s JSONL audit chain has its own retention sweep — see Seats vs. stores.

audit_logs was previously retain-forever by construction. A naive prefix DELETE is not an acceptable remedy: verify_integrity requires the first observed sealed row to be seq = 1 (truncated_head) and a deleted middle row is a seq_gap, so the integrity tool would flag lawful hygiene as tampering. Retention is therefore an explicit, signed, operator-invoked contract:

the OLDEST sealed rows are deleted in bounded chunks; a signed retention floor (audit_chain_retention) advances in the SAME transaction as each chunk’s DELETE; verification treats retained_from_seq + 1 as the legal chain root while every signature / adjacency / checkpoint check above the cut is unchanged.

There is no automatic or date-based retention for the Mango DB store. Pruning is a deliberate operator action (CLI, --yes).

Marker contract (migration v0014)

mango/migrations/v0014_audit_retention_floor.py creates a single-row table (id INTEGER PRIMARY KEY CHECK (id = 1)):

ColumnTypeMeaning
retained_from_seqBIGINT NOT NULLHighest sealed seq lawfully pruned. Rows at/below it are absent by contract.
boundary_seqBIGINTFirst surviving sealed row above the cut.
boundary_signatureTEXTThat row’s chain signature — cryptographic continuity across the cut.
marker_macTEXT NOT NULLHex HMAC-SHA256 over the domain-separated material (below).
updated_atDOUBLE PRECISION NOT NULLWhen the marker was last (re)written.

The MAC material is:

"mango-audit-retention-v1|" + canonical JSON
{"boundary_seq":..., "boundary_signature":..., "retained_from_seq":...}

(sort keys, compact separators, ASCII). The prefix is a domain separator: a retention marker can never be replayed as a row signature or a checkpoint anchor MAC even though all three use the same key. Writes use the active MANGO_AUDIT_CHAIN_SECRET; verification accepts the whole trusted ring (MANGO_AUDIT_CHAIN_PRIOR_SECRETS included), so a marker outlives key rotation. The UPSERT is monotonic — a lower floor never regresses the marker.

Generation bounding. New anchors and markers stamp the writing key generation (key_epoch, migration v0017) and MAC under generation-bound v2 material, so verification resolves ONE key: a retired (potentially weaker) generation can no longer vouch for an artifact the current era wrote. NULL-epoch rows are the pre-v0017 corpus and keep the legacy ring-wide v1 verification byte-for-byte. Every MANGO_AUDIT_CHAIN_PRIOR_SECRETS entry carries the SAME 16-byte floor as the active secret — a short retired key is brute-forceable and its ring membership would let it vouch for chain anchors; a short entry refuses at boot (name the entry, store the ORIGINAL retired secret, and rotate it out of the ring only once every row it signed is outside the retention window). A benign stale anchor (the anchor trio agrees behind a fully verified tail — a write-time checkpoint refresh failed) is the typed anchor_stale verdict, NOT tampering; the next clean scan re-anchors forward.

Legacy rows with seq IS NULL (pre-v0003) are OUTSIDE the chain and are never pruned.

Operator prune

# inspect the plan (no writes; no --yes needed)
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/prune_audit_log.py \
 db postgresql://... --keep 50000 --dry-run

# prune the oldest rows, keeping the newest 50000 sealed rows
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/prune_audit_log.py \
 db postgresql://... --keep 50000 --chunk-rows 5000 --yes

# verify the floor-anchored chain afterwards
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/verify_audit_chain.py \
 db postgresql://...

--keep N is required (N >= 1); --yes is required for a real prune and is refused (exit 2) without it. The prune cuts at cutoff = MAX(seq) - keep.

The configured chain key is REQUIRED. An ephemeral chain key (the per-process random fallback when MANGO_AUDIT_CHAIN_SECRET is unset) refuses before any destructive chunk: markers/anchors/audit rows that process would write are signed with a key the live configured app rejects — the pre-fix shape could poison the chain head and turn every later privileged write into a 503. Export the secret exactly as the examples above show. The explicit --allow-ephemeral ack runs WITHOUT the configured key only on an UNANCHORED store (no checkpoint, no retention marker): it deletes the rows, writes NO signed artifact (no marker, no chained audit row), logs a CRITICAL, and is irreversible — a later configured-key verify will report the cut.

Each chunk deletes at most --chunk-rows rows (default MANGO_AUDIT_PRUNE_CHUNK_ROWS = 5000, env_int-guarded), and the chunk’s DELETE + marker advance commit together in one transaction. A crash between chunks leaves the floor at the last fully committed chunk — always a legal monotonic marker — and the next operator run converges from there. The final partial chunk still advances the marker to cutoff, so the retention line is recorded even when the window is all burnt seqs.

Locking follows the audit write path (transaction → the PG pg_advisory_xact_lock used by _lock_chain_write → the module chain lock), so a prune chunk cannot interleave with a chained audit write. The prune re-reads the marker inside each chunk transaction and refuses (RuntimeError, CLI exit 1) when:

the marker is corrupt (HMAC/parse failure), the marker moved since the run computed its plan (concurrent prune), the checkpoint is invalid, behind the chunk cutoff (the cut may never sit above the vouched tail), or ahead of the surviving tail (a truncated store — verify/restore before pruning), the marker-bound boundary row is missing or replaced, sealed rows exist at/below the signed floor (history reappeared below a lawful cut — restore/tamper).

Return value: {"pruned": N, "cutoff": cutoff, "floor": new_floor, "dry_run": bool}. With --dry-run, pruned is the number of rows the run would delete. Deleted rows are exported as mango_audit_retention_pruned_rows_total (export-only health datum; no alert/panel consumer yet).

Floor-aware verification

Audit.verify_integrity reads the signed marker before the row scan (anchor-first, like the checkpoint), so a concurrent prune cannot produce a false truncation verdict. With no marker, the historical contract is byte-for-byte unchanged.

With a valid marker at floor:

ObservationVerdict
first sealed row seq == floor + 1legal chain root (no truncated_head)
first sealed row seq <= floortyped retention_floor_mismatch
first sealed row seq > floor + 1seq_gap with missing_after = floor
marker bound a boundary row and its signature changedretention_floor_mismatch (detail = boundary_signature_mismatch)
marker floor > checkpoint seqtyped retention_floor_mismatch (inconsistent store)
missing/corrupt marker MAC or unparseable markertyped retention_marker_invalid, ok = false
missing markerexisting behavior (truncated_head if first seq!= 1)

Off-host anchor files carry their generation. An anchor exported from a v0017+ store must include "key_epoch": N in the JSON ({"seq": N, "signature": "...", "checkpoint_sig": "...", "key_epoch": N}) — the MAC is generation-bound, so a v2 anchor without its generation verifies as checkpoint_invalid. Pre-v0017 anchor files (no key_epoch) keep the legacy ring-wide v1 check unchanged.

Signatures, adjacency, key-epoch, and checkpoint truncation/rewind checks above the floor are unchanged. verify_audit_chain.py prints retained_from_seq alongside the verdict and treats a clean chain anchored to its checkpoint as ok — a floor-anchored clean chain passes, while an Unanchored chain still exits non-zero. The floor is deliberately NOT a verdict key: the cross-language verdict contract (docs/fixtures/audit_verdict_keys.json) gains no new keys. The two new reason tokens (retention_floor_mismatch, retention_marker_invalid) are Mango-only emissions; Sol’s per-file JSONL walk has no relational floor.

Backups and key warning

Back up the store WITH its chain key before pruning. After the cut the remaining chain (and the marker MAC) is verifiable only with MANGO_AUDIT_CHAIN_SECRET plus every generation in MANGO_AUDIT_CHAIN_PRIOR_SECRETS. A database restored without the matching keys reports key_epoch/signature_mismatch — honest, but not recoverable. Restore the database and its key ring as one unit; restoring an OLDER database while keeping a newer retention marker (or vice versa) is the “history reappeared below the floor” / “marker ahead of checkpoint” inconsistency and fails verification by design.

Archive store

audit_events is a DIFFERENT store from the relational audit_logs chain: Sol’s event-archive plane (sol_event_archive) POSTs archived events to Mango’s /api/mango/audit-archive, and Mango persists them there (the canonical RFC3339 timestamp string, three indexes). It has no signed chain and no floor marker, so retention is a plain AGE-based job:

# inspect the plan (no writes; no --yes needed)
python3 mango/scripts/prune_audit_events.py --db postgresql://... --days 30 --dry-run

# prune rows older than 30 days, chunked (default 5000 rows/statement)
python3 mango/scripts/prune_audit_events.py --db postgresql://... --days 30 --yes

Automatic: Mango now runs the same prune hourly (MANGO_AUDIT_EVENTS_RETENTION_INTERVAL_SECONDS, default 3600; 0 disables the loop). Each automatic run is chunk-bounded (100 chunks) so a first pass over a large backlog never monopolises the IOLoop; the operator CLI below remains the unbounded drain-to-empty surface. Window: --days N (default MANGO_AUDIT_EVENTS_RETENTION_DAYS = 30). --days 0 is the explicit archive-off posture — keep everything, write nothing. Chunking: MANGO_AUDIT_EVENTS_RETENTION_CHUNK_ROWS (default 5000) bounds every DELETE statement, so a first run over a large backlog never holds an unbounded statement/transaction open. Scheduling: wild owns the fleet cron/systemd timer; run the job at least once per retention window. Observability: /metrics exports mango_audit_events_oldest_age_seconds (scrape-time, 60s cache, from the indexed MIN(timestamp); absent on an empty archive). MangoAuditEventsRetentionStalled (warning) pages when the oldest row is older than the default window + 7 days. Backup policy: this table is part of the Mango database backup (SQLite hot copy / pg_dump, docs/backup-and-dr.md §2). A first prune is destructive and irreversible — take a backup first. Restoring an older database restores the rows; nothing else references them by sequence.

Seats vs. stores

audit_retention_days in the seat/license caps is a licensing/gating flag surfaced in Limon (see docs/seats.md); it does NOT drive Mango DB pruning. Mango retention is the operator CLI above only — never a background policy. Sol’s filesystem audit chain (audit-*.jsonl) has a separate daily sweep keyed by Sol’s audit_retention_days application setting; that is a different store with a different lifecycle.