Phase 1 high availability: primary, warm standby, witness¶
Crate oliviadb-enterprise/crates/oliviadb-ha (proprietary); engine hooks in the open oliviadb-core
(Db::set_commit_tap, Db::apply_replicated, Db::set_visible_limit /
Db::visible_ts). Binaries: oliviadb-ha-node (a data node or the witness over mutual TLS),
oliviadb-ha-sim (the simulator).
Roles¶
- Primary: serves reads and writes; ships every local commit of its replicated trees (agent memory's durable and session classes) to the standby.
- Standby: applies the shipped commits (same versions, same batches) and acknowledges once they are synced. Layer-1 data is not shipped: the standby applies the same IMS change stream itself; layer-1 positions are source times, the same on both nodes.
- Witness: holds
(epoch, primary, shipping mode)on disk and the primary's lease.
Guarantees¶
- Durable class, semi-synchronous. A durable write is acknowledged only when the
standby has it synced. After
t_syncwithout that, the write is answered "outcome unknown" (see below), an alarm is counted and the primary refuses further durable writes (retryable: they are not done) until the standby has caught up. There is no automatic switch to asynchronous shipping: only the operator switches, and the switch is recorded at the witness before the primary acknowledges anything without the standby. Switching back takes effect locally at once and is recorded at the witness only once the standby holds every durable write. - Outcome unknown. "Retryable" means "not done, safe to send again": every
retryable refusal (not primary, lease lapsed, standby behind, writes frozen) comes
before the write is committed. A write that is committed on the primary and then not
confirmed (the standby's acknowledgement does not arrive within
t_sync, the primary loses the role first, or the local commit or its sync fails) is answeredWriteResult::Unconfirmed(oliviadb-ha-node:R <n> unknown <reason>; memory:MemError::Unconfirmed/StateError::Unconfirmedwith the version; network API: 504outcome-unknown, not retryable, withversion,docs/network-api.md). The write stays on the primary: it becomes visible once a standby holds it (a late acknowledgement), and it survives a failover only if the standby got it. A client reads before it sends such a write again; resending blindly could apply it twice (an insert sent again conflicts, 409). REMEMBER keeps its step's idempotency record also when its writes are not confirmed, and a REMEMBER of the same step replays that result once they are; its 504 is therefore retryable. The record of a step with durable writes is written in the same commit as those writes (durable class,tenant|I|step, its decisions sealed under the episode's keys), so a standby that holds the episode holds the record: the same step sent to the new primary after a failover replays instead of writing the episode again (open/crates/oliviadb-memory/tests/step_failover.rs); a step with session writes only keeps its record in the session class with them. Evidence: the simulator's invariant 14 (no write answered retryable is ever on any node; it catchesunconfirmed_retryable, which answers a timed-out write as retryable),tests/e2e_native.rsa_late_standby_ack_is_outcome_unknown_not_retryable(the link to the standby cut, a write answered 504 and the next 503; the link back: the first is there on both nodes and conflicts when sent again, the second is not there until sent again),tests/e2e.rs(a primary without a standby:unknown, thenretry; the first write is there once a standby is back, the second never),oliviadb-memorytests/unconfirmed.rs. - Visibility. A durable write becomes visible to other readers only once the standby
holds it (the replicated watermark:
Db::visible_ts); the writer's own call returns only after that anyway. A standby that takes over may show all it holds; a primary that restarts shows nothing new until its standby has it again. The same holds in asynchronous mode: other readers see only what the standby holds (while the standby is away they see nothing newer than what it had; the writer sees its own at once). No reader sees data a failover could lose, in either mode. - Ship after sync. A commit is shipped only once it is synced on the primary, so the standby never holds what the primary could lose in a crash. Session commits are synced and shipped in groups (every half heartbeat); the session lag (RPO) is reported: the age of the oldest session commit the standby lacks, or unbounded while the standby lacks commits older than the primary's buffer (after a restart, until it resynchronises).
- Fencing. A primary writes only while its lease is valid by its own clock: the lease
runs from the moment it sent the request, minus the drift margin. The witness grants
a new epoch to the standby only after the lease has lapsed by its own clock plus the
margin, and (unless the operator forces it) only in semi-sync mode. A primary that has
lost its lease stops heartbeating, so the standby can take over. A primary that restarts
takes a new epoch, so no fencing token
(epoch, version)of its earlier run (whose unsynced tail may be lost) is ever issued again. A standby that sees a newer epoch from a peer asks the witness before believing it; batches of an older epoch are refused (Stale). A new primary's versions continue above everything it applied (the HLC observes replicated versions), whatever its clock says. - Resynchronisation. A standby that joins a new epoch, or that lacks commits the
primary no longer buffers, gets the class's history: every stored version of every key
(
DbIter::all_versions), in version order, in chunks of about 1 MiB that end at a version boundary. It is applied version by version into a fresh tree (so reads "as of" a past version give the same answer on both nodes after a resync) and switched to atomically (a crash in between leaves the old tree; a lost or reordered chunk restarts the transfer). The need to resynchronise is persistent: it is recorded before the node takes the new epoch, so a crash in the middle never leaves a standby of the new epoch that trusts its old tree. A late or duplicated snapshot is never installed over newer state. Batches that arrive out of order are kept until what precedes them arrives. - A primary whose storage freezes (an I/O error on a log, table or manifest, or a
block that fails its checksum: the write freeze of
docs/operations.md) cannot write any more, so it gives up the role the way a dead primary does: it refuses writes at once (retryable,writes frozen on this node (...): the standby takes over; retry), sends no lease renewals and no heartbeats, and answers no requests of the standby. The lease lapses, the standby (which has not heard a heartbeat fort_fail) asks the witness, and the witness grants it the next epoch once the lease has lapsed plus the margin: another node serves writes within aboutt_lease + drift_marginof the freeze (bounded byt_lease + drift_margin + t_failand the retry intervals, invariant 13). Durable writes the frozen node acknowledged are on the standby (semi-synchronous shipping); what it committed but could not ship was never acknowledged. Once the frozen node has lost the role (its lease lapsed, or it learnt of the new epoch) it stops (oliviadb-ha-nodeexits with status 3, fail-stop); restarted on a good disk it comes back as the new primary's standby. A standby whose storage froze does not ask for promotion and stops as well. In asynchronous mode the witness grants no automatic failover (the standby may lack acknowledged writes): a frozen primary is replaced only by the operator's forced promotion, as a dead one is./readyzofoliviadb-ha-node --serveanswers 503 while the node is frozen; the status line ends withfrozentrue or false.
The layout registry on the nodes¶
The layout registry (spec/schema.md 4.2) is a replicated class of its own
(Class::Layouts), shipped semi-synchronously like the durable class: a registration is
acknowledged once the standby holds it, so a layout number is never used on the primary
before its layout is on the standby, and both nodes number layouts alike. On a node the
registry is an oliviadb_dli::registry::LayoutTree over the class's tree (MemTrees::layouts;
System::set_layout_tree puts a DL/I system's registry there): registration is admitted
only while the node may write (the gate's admission: a standby refuses, and a primary
that is blocked or has lost its lease answers retryably), and waits for the standby
(Gate::wait_layouts). Registering a layout that is already there is answered once the
standby holds the registry as it is (an earlier registration whose acknowledgement failed
is not reported as done before that). A standby promoted to primary registers through
the same class, to its own standby. oliviadb-ha-node --memory takes layout <n> <json> and
decode <n> <number> <hex> on its standard input.
Evidence: the simulator's invariant 12 (every acknowledged registration on every node
that serves afterwards under the number it was acknowledged with; no number names two
layouts), held under a mix that crashes the primary right after registrations
(AIM_LAYOUTS) and catching layouts_not_waited (acknowledged without the standby);
tests/e2e_layouts.rs (three processes: registered on the primary, decoded on the
standby, refused there; kill -9 of the primary; the new primary decodes by the same
number and, with a standby again, numbers new layouts after the replicated ones).
Agent memory on the nodes¶
oliviadb_ha::memnode (and oliviadb-ha-node --memory --master-key FILE): two more classes next to
memory's durable and session trees, both shipped semi-synchronously like the durable
class: the key store (Class::Keys: key file name to contents) and the agent-state store
(Class::State: the state_* documents).
- As a standby the node keeps the four trees. When it becomes primary it writes the key
files from the Keys tree into the key directory (the replicated truth replaces whatever
is there) and opens memory over the trees (
Memory::open_with_trees). Both nodes use the same master key (from the KMS in production). - Memory's commits reach the node through commit taps, the key store's changes through a
KeyMirror(every key created, every key destroyed and its tombstone). Memory asks the node's gate (oliviadb_memory::ReplicationGate) before writing (admit: primary, lease, not blocked), waits in its durable sync until the standby holds the durable tree up to the write and every key change made so far (wait_replicated; on timeout or loss of the roleMemError::Unconfirmed, outcome unknown: the write is done here), and shows other principals only durable records the standby holds, and only those written before the oldest key change the standby lacks (a record is useless without its key; the writer sees its own at once). An erasure therefore is on the standby (the destroyed key) before it is acknowledged. - The agent-state store works over the State tree the node hands in
(
Memory::open_with_state): its writes are admitted by the gate and acknowledged once the standby holds the State tree up to them and every key change before them (ReplicationGate::wait_state_replicated,StateError::Unconfirmedotherwise: outcome unknown); readers see the tenant's documents only as far as the standby holds them (the tree's visible limit, set by the node like the durable class's), a principal's own at once. - A primary that loses the role stops (fail-stop:
oliviadb-ha-nodeexits with status 3, a supervisor restarts it, it comes back as a standby and resynchronises): memory is never open on a standby. - Durable commits are synced in groups: the trees of the durable and session classes are opened without a sync per commit (only the key tree syncs each commit). The node syncs before it ships (the standby never holds what this node could lose), the standby before it acknowledges, and memory before it acknowledges a write: its own group commit (concurrent writers share one log sync), then the wait for the standby.
- Memory's clock never runs behind the records it holds: a node whose clock is behind the old primary's runs ahead by the difference, so facts just written are not "in the future" there (valid time).
Network API on the nodes¶
oliviadb-ha-node --memory --serve CONFIG [--peer-url URL] also serves oliviadb-server's network
API (CONFIG is its configuration file: listener, TLS, API keys or JWT). Until the node is
primary and has opened memory, every request but /healthz is answered 503 with a
retryable problem document and Retry-After: 1; /readyz is 503 too (a load balancer
sends traffic to the primary only). When the node follows a primary whose URL --peer-url
gives, the answer names it (oliviadb-primary header, primary member). On the primary,
memory's own refusals are retryable 503s as well: no standby in semi-synchronous mode
(standby behind: durable writes blocked), a lapsed lease, a lost role. The clients
(repositories oliviadb-python, oliviadb-js, oliviadb-java) take every node's URL: on a refused
connection or a retryable 503 they move to the node the answer names, else to the next
one, and retry (each node gets its turn before the retries run out; the same node after
its Retry-After). A write the primary committed but the standby did not confirm in
time is answered 504 outcome-unknown (not retryable, with its version): the clients do
not resend it; the caller reads first. REMEMBER is idempotent per step id (its 504 is
retryable), so a REMEMBER sent again after an unanswered attempt or a 504 is not doubled
(but see "Outcome unknown" for a failover in between).
The primary also applies the configuration's audit log, access profiles ("schema") and
serves the schema's native aggregates (docs/network-api.md, "Native aggregates"): their
data is in the agent-state tree, so it ships to the standby with the State class, and a
write is acknowledged once the standby holds it; their change stream gives the same
records and positions on either node (oliviadb-enterprise/crates/oliviadb-ha/tests/e2e_native.rs).
Memory's recall index is in the trees (spec memory-index.md): it is replicated with the
records it describes, in the same commits; a standby that takes over opens it as it is.
Timing¶
Timing { t_sync: 2000, t_lease: 5000, t_fail: 3000, drift_margin: 500 } (ms), all
configurable (--timing SYNC,LEASE,FAIL,MARGIN), validated at start:
t_lease > t_fail + drift_margin: the standby suspects the primary aftert_failwithout heartbeats, but the witness grants promotion only after the lease has lapsed plus the margin; a lease longer than the failure detector means a primary that is merely slow still holds its lease when the standby first asks, keeps renewing it everyt_lease / 3, and is not replaced while it is alive and reachable.t_sync < t_lease: a blocked durable write gets its answer (outcome unknown) from a primary that still holds its lease, before any failover could start.t_lease > 2 * drift_margin: the lease left after the margin is usable.
Transport¶
net::TlsNet: TCP with mutual TLS (rustls, ring provider). Each node has a certificate
from the cluster's CA whose DNS name is its node id. Inbound connections are accepted
only with a certificate valid for one of the node's configured peers, and every message
on them is attributed to that peer: the identity the witness binds an epoch to and the
one a standby checks against the witness is the authenticated one. Outbound connections
check the server certificate against the peer's id. No plain-TCP mode; net::InProc is
for tests.
Evidence¶
tests/sim.rs(release builds): 60 seeds of the simulator hold the fifteen invariants below (each seed: 60 s of simulated time, crashes with torn tails on every node, the witness crashing, the primary's disk failing, single partitions and isolated nodes, message loss, duplication, reordering and seconds-long delays, clock offsets up to ±10 min and rate errors up to ±2 %, the operator switching modes, the layer-1 change stream applied by both nodes);oliviadb-ha-sim --seeds 1000runs more.- every acknowledged durable write is on every node that serves writes afterwards;
- one writer per epoch, and all writes of an epoch precede (true time) any write of a later epoch;
- epochs never go back, no older-epoch batch is applied, tokens of a class grow within an epoch;
- no durable acknowledgement without the standby holding the write (for memory: the
durable tree up to it and every key change before it) unless the witness recorded
asynchronous mode; every durable write answered within
t_sync; - a durable value a reader saw is on every node that serves writes afterwards;
- both layer-1 copies are equal at equal source times;
- session writes lost at a failover are within the lag the old primary reported;
- the standby reads every version the primary acknowledged as the primary does (history survives resynchronisation);
- (memory) every acknowledged REMEMBER is readable on every node that serves writes afterwards (its keys included);
- (memory) an acknowledged erasure stays erased on every node that serves afterwards;
- a healthy pair converges: after 12 s without injected faults (every run has a calm spell of 20 s), the standby holds every durable commit the primary had synced 5 s before, or is still making progress (commits or resynchronisation chunks);
- every acknowledged layout registration keeps its number on every node that serves afterwards;
- a primary whose disk fails (injected now and then: every write and sync of its
storage errs until it restarts) is replaced: another node serves writes within
t_lease + drift_margin + t_fail, stretched by the clock drift bound, plus 2.5 s of slack for heartbeats, retries and message delays, counted from the freeze (or from the arrival of the last message the frozen node had sent, or from the end of any time the other node or the witness was down, the two could not reach each other, or the other node was frozen or did not know its role yet; nothing is checked if the operator chose asynchronous shipping meanwhile); a frozen node never counts as serving, and one that has lost the role stops (its disk is good again at its restart); - a write answered retryable was not done: it is on no node, then or later;
- (memory) REMEMBER is idempotent per step across failovers: clients send steps
again (recent ones most often), to whichever node serves, and no serving node
holds two episodes of one step;
and 5 also covers facts another principal saw through memory, in either shipping mode.
Memory runs (
SimConfig::memory,oliviadb-ha-sim --memory) put agent memory on the nodes: REMEMBER by two principals, reads by a third, erasures, agent-state documents put by two principals and read by a third, with the key store and the state store replicated; 9 and 5 cover the documents too (an acknowledged or seen document is on every node that serves afterwards, with that value or a later one). They use the operating system's random source for keys, so a failing memory seed replays the same schedule but not byte for byte. - Mutation checks (
tests/sim.rs): each invariant, checked alone, catches a deliberate bug: early acknowledgement (1), early grant by the witness and no self-fencing (2), accepting old-epoch batches (3), silent asynchronous downgrade and no timeout (4), exposing unreplicated writes (5), reordering a change unit on the standby (6), a lag reported as zero (7), snapshots of the newest versions only (8), a frozen primary that keeps renewing its lease and heartbeating (13), a timed-out write answered retryable (14); in memory runs: early acknowledgement (9), exposing unreplicated writes (5) and exposing them in asynchronous mode only (5). The rare windows have fault mixes aimed at them (SimConfig::aim,oliviadb-ha-sim --aim keys,resync,erase,async): key-store batches lost on the way and the primary dying while the standby lacks key changes (memory writes that do not wait for the key store: 4; records visible before their keys are on the standby: 5); durable batches lost, the primary dying with a tail the standby never got, a standby crashing in the middle of its resynchronisation (a resync mark kept only in memory: 8, about once in a thousand seeds, so in an ignored test run on demand: the primary already sends a snapshot to a standby whose history it cannot extend); erasures of subjects the standby holds and the primary dying right after one (an erasure acknowledged early: 10); the primary dying right after an agent-state put (state writes that do not wait for the standby: 9); the operator switching to asynchronous shipping soon after durable writes block and the primary crashing in that mode while the standby lacks durable commits (records visible to others in asynchronous mode before the standby holds them: 5). The aimed mixes hold every invariant with the real code (aimed_mixes_hold_every_invariant). - Found by invariant 5 and fixed: in asynchronous mode the primary showed other readers everything it had committed, including memory's durable records not yet synced (they are synced in groups) or shipped; it lost that unsynced tail when it restarted, served again, and a fact another principal had read was gone. Readers now see only what the standby holds in both modes. Memory runs resend recent REMEMBER steps more often (invariant 15), which is the schedule that showed it.
- Found by invariant 11 and fixed: a resynchronisation never finished when its chunks overtook each other or one was lost (the standby restarted it at every out-of-order chunk, and dropped chunks that came before the first one): chunks are now kept until their turn, a stalled one is asked for again and the same snapshot sent again fills the gap. With many chunks (a long history) the standby stayed behind for good and the primary's durable writes stayed blocked.
- Found by the simulator in an earlier round and fixed: a standby that crashed in the middle of a resynchronisation trusted its old tree after restarting (the resync is now recorded before the new epoch); a standby promoted before finishing a resync exposed its old lineage (nothing is visible then until its standby has it); a standby applied and acknowledged batches while receiving a snapshot that then took it back; durable records were visible before the key they are sealed with was on the standby; a node whose clock was behind showed no current facts after taking over (memory's clock now never runs behind the records it holds).
tests/e2e.rs: three processes over mutual TLS, every link through a cuttable proxy; node B's clock an hour behind and 2 % fast. kill -9 of the primary (B takes over in about 1.5 s with the test timings, with every acknowledged write; a durable write without a standby is refused, retryably, withint_sync); the killed node restarts as standby and B's tokens continue above A's; the primary cut from the witness stops serving, the other node takes over with everything acknowledged; after healing the old primary rejoins as standby.tests/e2e_memory.rs: the same three processes with agent memory. REMEMBER on the primary; kill -9; every acknowledged fact readable on the new primary by another principal (keys came along), the erased subject stays erased; without a standby REMEMBER is refused retryably withint_sync; the old primary restarts as standby (resynchronised: memory's trees and the key store); the primary cut from the witness is replaced with everything it acknowledged, and on healing stops with status 3 and comes back as a standby.tests/e2e_network.rs: two memory nodes serving the network API and OliviaDB's Python client given both URLs. The standby answers 503 naming the primary; the client, with the standby listed first, writes through the primary; after kill -9 of the primary the same client moves to the other node, reads every acknowledged fact there, and its write is acknowledged once the old primary is back as standby; an agent-state document written through the old primary is read through the new one.tests/e2e_freeze.rs: the primary's disk fails (OLIVIADB_HA_DISK_FAIL, a test hook that makes every write and sync of the node's storage fail while a file exists). The next write fails in its commit and every later one is refused at once, retryably; the status says frozen and not serving; the node exits with status 3 once its lease has lapsed (about 0.9 s with the test timings); the standby serves writes about 1.3 s after the fault (bound: lease + margin + detection + 2.5 s), with every write acknowledged before; restarted on a good disk the old primary is the new one's standby and holds its writes. With memory and the network API:/readyz503 (storage frozen, retryable) and/healthz200 on the frozen node, then the same hand-over.tests/net.rs: a certificate of the right CA that is not a configured peer, and a configured name with a certificate of another CA, get nothing through.
Open¶
- A snapshot is built in memory on the primary (all versions, sorted) before it is chunked; the history kept is what compaction kept (the GC watermark).
- A snapshot carries memory's recall index with the records (it is in the trees); the index keys' short history is what compaction kept of it.
- The witness is a single process (its state file is synced and replaced atomically); a witness restart assumes a full lease from its start.
- No certificate rotation or revocation lists; node ids are configured, not discovered.