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.

Event store durability — segment contracts

The event backbone’s durable-file surfaces share one ordering and atomicity contract. This document is the operator/design reference; the contract is pinned by the named tests (the doc↔code parity is gated by ci/event_store_ordering_doc_lint.py + its lint-contract test).

Scope: the memory WAL (sol_memory_wal), the event-lane spill (sol_sync_event), and the ordering siblings that consume the same discipline (chat history, workflow compensation markers, decomposition ids). The event log itself (per-aggregate seq under a write lock, terminality-aware compaction, ack-before-delete archive, outbox-gated restore — –) stays as documented in the phase ledger; its retention and staging rules are pinned below.

Cluster scope

The event store is node-sharded by design: every Mnesia event table is created {disc_copies, [node]} — a single-node replica list — and nothing replicates. Each store allocates its own seq under its own aggregate locks, so there is no cross-node seq plane and therefore no cross-node split-brain hazard by construction. “The cluster’s audit trail” is N independent shards with independent seq spaces; a consumer that switches nodes sees gaps/overlaps in since_id cursors — treat every since_id cursor as NODE-BOUND (persist it with the node it was read from and never replay it against a different node). Global event views are out of scope until a consumer exists. This also makes event append batching (the group-commit successor) strictly local write coalescing — no cross-node coordination can ever be required.

Segment naming and the replay-order guarantee (memory WAL)

The memory WAL keeps one framed append-log segment per flush window under <mnesia dir>/memory_wal/, named

seg--.log

Contract: replay order == lexical name order == creation order. The ms field is not the wall clock — it is a monotonic clamp:

ms_minted = max(wall_clock_ms, seg_last_ms + 1)

seg_last_ms is threaded through the WAL gen_server state (the WAL is the single segment writer) and is floored at init from the timestamp field of the existing segment names. Consequences:

a backward wall-clock step (NTP correction, manual change) cannot invert durable ordering — a segment recovered at boot-2 always replays before any segment minted at boot-2; a far-future-named segment keeps every later mint sorted after itself; unique_integer([monotonic, positive]), zero-padded, tiebreaks same-ms legacy names by creation order too; the same-ms name collision class (unique integers reset per VM) is dead: the clamp pushes the new mint past the recovered name.

No migration is required: old names parse and participate in the init floor as-is (unparsable names floor at 0).

Ops in a segment are appended before the enqueue ack (page-cache durable); fsync runs at flush cadence and terminate, so power loss is bounded to the last fsync. A WAL process crash replays the scoped segment set at init, in name order.

Pinned by sol_memory_wal_order_SUITE (backward_clock_step_replays_insertion_order, far_future_segment_orders_before_new_mint, same_ms_burst_orders_deterministically, restart_same_clock_two_segments, legacy_store_adopts_and_preserves_name_order).

Clock-step behavior (operator note)

Under a clock step the segment names stop tracking wall time for a while (mints clamp forward from the last name instead of following a stepped- back clock). This is by design: name order is creation order, not clock order. Names resume tracking the wall clock once it moves past the clamp.

Rewrite atomicity: the live-set manifest

Drops (operator-opted loss via the drop/fail policies, or overflow eviction) rewrite the segment set to exactly the surviving queue. The rewrite is atomic under process crash:

  1. the fresh segment is written to a <final>.new sibling (invisible to the *.log replay glob), fsynced, closed;
  2. it is atomically renamed into its final .log name;
  3. live.manifest — the replay-scope list, published via the tmp+fsync+rename atomic writer — is rewritten to list ONLY the new name;
  4. the old names are deleted last.

The manifest is the atomic scope switch: a crash before step 3 replays exactly the pre-rewrite set (the renamed-but-unlisted file is swept at init); a crash after it replays exactly the post-rewrite set (the old files are unlisted and swept). There is no interleaving that replays both sets — the pre-fix fresh-write/delete-after order double-counted surviving ops and resurrected operator-dropped ops.

The manifest is maintained on every lifecycle change: a new active segment adjoins itself before its first acked append, a rewrite publishes step 3, a full-flush retire clears the list, and init prunes listed-but-missing names, sweeps unlisted .log orphans and leftover .new/.tmp. temps. A store without a manifest (legacy or fresh) adopts its full .log set as the truth and writes the initial manifest, so the fallback never re-engages after the first boot.

Pinned by sol_memory_wal_order_SUITE (rewrite_crash_before_publish_replays_pre_set, rewrite_crash_after_publish_replays_post_set, orphaned_temps_swept_at_init).

Event retention: terminality, dispositions, and the per-aggregate cap

sol_event_compactor deletes an expired event only when its aggregate’s projection cannot regress on a rebuild. The predicate is retention terminality, which is broader than a terminal status:

Task: completed | failed | cancelled | timeout and every timestamp older than the cutoff. Server-side cancel/drop paths write a terminal projection event (task.failed for cancels; task.dropped is projected as failed) so a cancelled view is not stuck non-terminal. Worker: crashed | killed | spawn_failed and old. Session: closed and old. Model: the terminal statuses (stopped | failed | start_failed | prepare_failed), plus the never-terminating product statuses in_use | discovered | prepared | preparing whose last activity (started_at / last_used_at) is older than the cutoff. Remote providers emit inference.complete but no model.stopped; this idle age-out is the provable terminal path for them. started stays live. unknown statuses/timestamps keep the event (the safe direction).

Per-aggregate hard cap. Even a never-terminating aggregate cannot grow the log without bound: an event at or below event_sequence.seq - event_retention_per_aggregate_cap (default 10000, 0 = off) is compacted regardless of the view, counted as event_retention_cap_forced_total, and a CRITICAL line is emitted. Boot replay is therefore bounded by the cap per aggregate family.

Metrics. The scrape-time gauge family sol_event_store_nonterminal_{task,model,worker,session}_aggregates and sol_event_store_retained_nonterminal_aggregates exposes the aggregates retention cannot yet release. sol_event_retention_over_budget_total (the event_retention_max_rows volume budget, default 1,000,000 since ) is ENFORCED: over-budget passes derive a volume cutoff and reap the oldest rows through the same terminality-aware walk; the per-aggregate cap remains the per-family hard bound.

Compaction staging: bounded backlog, O(1) scrape

The staging dump (sol_event_compactor_staging.dump) is the durable copy of compacted events whose archive ack has not been confirmed.

Backlog counter. Every staging mutation writes sol_event_compactor_staging.count (atomic temp+fsync+rename): the number of staged events NOT yet acked (dump length minus the durable drain cursor). staging_backlog/0 reads only this counter — a Prometheus scrape never decodes the dump. A previous dump without a counter falls back to one decode and is reconciled on the next recovery/staging write. Drained-recovery gate. When recovery actually STALLS (the archive ack failed — not merely a chunk-budget stop on a healthy archive), new compaction pages are gated for that pass and counted as compaction_staging_backlog_gated_total. With the archive down, the staging backlog therefore stays at the single page that failed, not one page per pass. Hard cap. staging_backlog_max_events (default 20000, 0 = off) refuses a staging append above the cap (staging_backlog_cap_total); the events stay in Mnesia — the safe direction. Recovery keeps its ordering contract. The drain cursor (sol_event_compactor_staging.cursor) is unchanged: windows are acked in order, the cursor advances after each confirmed window, and a crash between the ack and the cursor write re-posts only the in-flight window (content-id idempotency). A corrupt/torn dump is cleared loudly; it is unrecoverable data by definition. Telemetry pagination. telemetry_event compaction now walks select continuations page-by-page (no full expired-id list). The stored tuples are tagged telemetry_event, so the match spec is built on that tag — the previous #sync_event{} head matched nothing.

Lane-spill recovery (event store)

The event-lane spill (admitted-but-unexecuted events, one segment at <mnesia dir>/event_lane_spill/lane_spill.log) replays at boot: the unretired records are rewritten to a <spill>.new sibling (append + fsync + close) and then atomically renamed over the segment before any admission runs. A crash before the rename leaves the original file untouched (idempotent re-read next boot); a crash after it leaves the complete rewritten set. The unretired set never exists only in RAM.

On a rewrite failure (disk error) the original segment is untouched and the events are re-admitted from RAM against the intact segment — the durable copy stays the crash-truth until the executing workers retire their records.

Commit-verdict retirement. A spilled admission is retired only after its event transaction COMMITTED. The lane worker casts {commit_spill, RecId} (the store appends a {committed, RecId} frame to the segment) and then {retire_spill, RecId}. The worker DOWN fallback retires only records in the committed set; a worker that dies pre-commit — or whose transaction aborts — leaves the record unretired and counted (event_lane_spill_uncommitted_retained_total), so the boot replay re-admits it. The replay’s check-before-insert dedupes the kill-after-commit-before-marker window (the event id is derived from the RecId), so the marker can never cause a loss or a duplicate.

Pinned by sol_sync_event_lane_spill_SUITE (lane_spill_survives_store_kill, lane_spill_replay_snapshot_crash_keeps_admissions).

Ordering siblings

The same ordering discipline applies to the store’s ordering neighbors:

Chat history (sol_chat_history): messages order by {timestamp, seq, msg_id}, where seq is a per-session monotonic counter allocated at write time. Wall-clock ms alone permutes same-millisecond messages (the table is ordered_set on the random msg_id). Legacy pre-seq rows (arity migration at init) are backfilled at the same migration: the scan assigns stable seqs in {timestamp, msg_id} order — the historical best-order, since the msg_id tiebreak is the only surviving order evidence for same-ms legacy rows — bounded by a budgeted paged scan (default 50000 rows, chat_seq_backfill_budget); a budget-truncated remainder keeps the msg_id tiebreak and converges at the next boot (numbering continues from the store’s max seq, so no collisions). Every row written after the migration allocates max+1 and therefore sorts after all legacy rows. Pinned by sol_chat_history_tests (same_ms_history_ordering_test, store_path_same_ms_order_test, seq_schema_migration_test, seq_backfill_budget_truncates_and_converges_test). Decomposition ids (sol_coordinator): the caller-process decomposition path mints decomp-<ms>-<monotonic-padded-unique> — same-millisecond decompositions can no longer collide and silently replace the registry entry (the gen_server path’s counter was already collision-free). Pinned by sol_coordinator_routing_tests (new_decomp_id_same_ms_burst_unique_test). Compensation markers (sol_workflow_manager): every failed marker write (aborted transaction, raised failure, invalid args) bumps workflow_compensation_marker_failed_total — the marker is load-bearing (a lost marker lets recovery re-run an unwind), so the failure is observable. Pinned by sol_workflow_manager_restart_tests (compensation_marker_abort_counted_test, compensation_marker_success_not_counted_test, compensation_marker_invalid_args_counted_test).

Residual (accepted)

A torn/corrupt MID-segment frame still truncates that segment’s suffix silently (sol_durable_file frame decoder returns the intact prefix; no per-frame CRC). Torn tails from crash-mid-append are the expected case and are handled correctly. Revisit per-frame checksums if segment sizes grow. Op-sequence frames ({op, Seq, Op} with dedupe-by-seq replay) remain the optional successor hardening; the manifest made them unnecessary for the rewrite window.