# Replication subsystem plan — NEW adapters and state-machine host Status: NEW design; all tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24. Authority: [requirements](../REQUIREMENTS.md) R-007–R-012, R-014–R-016; [architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-11–C-13. ## Baseline and exclusive responsibility No Replication target, durable replicated log or state-machine host exists. NEW proposed roots are `include/Void/Replication`, `src/Replication` and `tests/standalone/Replication`. Existing [Net client](../../../include/Void/Net/Http.hpp) is only a transport precursor; its graph gaps at 112/115 were read directly. No reliability claim follows from that API. Replication depends on the pure [Coordination](Coordination.md) core, [RPC](RPC.md), [Storage](Storage.md), Async, Time and optional observation hooks. It owns stable-storage, transport, snapshot and deterministic application adapters. Coordination does not import Replication; RPC does not import Coordination; Storage does not import replication policy. Discovery integration is an upper adapter, with static bootstrap endpoints sufficient for initial groups. Choose native host logic and the original Storage engine as the first persistence implementation. SQLite may receive a separate later adapter with explicit transaction/durability evidence; it is not the native engine or distributed shared disk. ## NEW interface and operation identity ```cpp // NEW illustrative Void::Replication shapes; Result/Task/options follow C-02/C-03. struct RequestIdentity { SessionId session; std::uint64_t sequence; }; struct CommitReceipt { GroupId group; LogIndex index; Term term; OwnedBytes result; }; enum class ReadPolicy { quorum_consistent, stale_local }; class Group { Task> submit(RequestIdentity, OwnedBytes command, OperationOptions); Task> read(ReadPolicy, OperationOptions); Task> inspect(RequestIdentity, OperationOptions); Task> shutdown(OperationOptions); }; class StateMachine { Result prepare(CommandView, const ReadView&); // deterministic, no IO }; ``` State-machine preparation computes application mutations and a bounded result against the current version, without network, wall-clock or randomness. Needed time/random values are command fields validated before admission; replicas apply identical bytes. `ApplyBatch` uses Storage-owned batch types. Snapshot metadata includes group/cluster identity, format, fixed configuration, included index/term, application schema, checksums and dedup state. Group owns all protocol/transport tasks; handles keep context alive through join. No callback executes under group or storage mutexes, and a worker cannot synchronously wait on its own executor. Session opening is itself committed and allocates a monotonically increasing session number from durable group state. IDs include cluster identity; numbers are never reused. Initial client contract allows one outstanding sequence/session; client sends acknowledged-result floor with its next command. Persist payload digest/result for duplicates. Same ID plus different command is identity_conflict. Duplicate retained ID returns original result; sequence at/below retired floor is result_expired, never re-executed. Closed/evicted session IDs below the durable allocation high-water mark remain invalid, without unbounded tombstones. Accept only the next sequence or a retained duplicate; reject gaps and floors beyond the last completed sequence before mutation. New sessions at capacity require explicit close/administrative expiry commands. Neither a retry nor a process restart opens a fresh session implicitly for an uncertain operation. ## Durable dataflow and crash boundaries 1. Bootstrap validates static cluster/group ID, voter list and node identity. Recover Storage, protocol state, snapshot and application applied position before serving. Reusing an existing node ID with empty storage is rejected. Peer authentication maps a certificate identity to the configured node ID; endpoint discovery cannot expand voters. 2. Serialize Core events per group. A PersistBatch atomically changes term/vote and/or protocol log records in a reserved Storage keyspace, requesting durable persistence. Only a successful completion satisfies its barrier and releases dependent peer replies. Replication adapters must preserve this dependency even if the network is faster than disk. 3. Leader appends a command, replicates, and waits for the core's committed range. Apply exactly the next index. One durable Storage batch includes application mutations, command/result dedup record, session floor updates and `applied_index`/term. This atomic batch is the only successful application commit boundary; no separate index file write. 4. Notify Core Applied only after that batch's durable success. Complete the caller with its result only after majority commitment and local durable application. Losing a reply does not undo commit; inspect/retry by RequestIdentity. Cancellation stops caller interest and transport work where safe, not a committed entry. Followers may lag but apply in order. 5. Recovery starts at persisted application applied index and replays only later committed entries; never double-apply an entry already included in the atomic batch. Conflicting protocol/application positions, malformed records or missing required log dependencies fault the group and require operator recovery, not silent truncation of committed state. 6. Quorum-consistent read asks Core for a fresh current-term read context, waits for majority confirmation and for local applied index ≥ read barrier, then opens a pinned Storage view. Return its applied index/term. `stale_local` returns local position and explicit stale metadata; it cannot be advertised as a consistent read during partition. The persistence-before-reply and read-quorum requirements follow [Raft's stable-state and client-interaction rules](https://raft.github.io/raft.pdf). The atomic application/dedup/applied batch above is the chosen integration contract. ## Snapshot, recovery and resource policy Pin application state at applied index I; create a versioned snapshot containing all application and active session/dedup data through I, plus the included log term/configuration. Write chunks to an isolated candidate, verify checksums/lengths, sync data and required directory/manifest dependencies using Storage's durable publication protocol. Publish an atomic manifest tying the snapshot to its applied position before compacting log ≤I. Receiver verifies cluster, format, index/term, schema and quota, prepares an isolated Storage generation, then atomically publishes application+dedup+applied position. Crash recovery follows Storage's durably published CURRENT/generation pointer; a complete but unselected manifest is an orphan or candidate, never authority merely because its generation number is larger. An InstallSnapshot reply waits for durable publication. Never load partially replaced app state while reporting the previous applied index. Cross-file consistency is a Storage port obligation, not an assumption that rename alone persists everything. Fault methodology follows [SQLite's simulated crash tests](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior). NEW defaults: 16 active groups/host; 1,024 admitted submissions/group, 64 MiB queued command bytes/group with a 256 MiB host aggregate; 1 MiB command and 64 KiB stored result; 10,000 active sessions/group and at most one unacknowledged result/session. Per-group disk starts at 1 GiB; snapshot triggers at 64 MiB log growth or 10,000 applied entries, whichever comes first. Snapshot chunks are 256 KiB, at most two transfers/host, 4 MiB transfer buffers and 16 MiB/s default transfer rate. A slow follower catches up from a snapshot after required log compaction; do not retain infinite history waiting for it. Reserve disk headroom for candidate+active snapshots; if insufficient, reject writes and report pressure. No eviction of active dedup results to gain space. Deadlines default to 10 seconds but include all admission/replication/ apply work; a timeout may still have committed. Group shutdown stops proposals, drains durable barriers, cancels transport and joins before closing Storage. | Fault | Required behavior | Evidence | | --- | --- | --- | | Sync fails before vote/append reply | Group pauses/faults; no dependent affirmative reply | Persist/network barrier instrumentation | | Crash after application batch before caller reply | Recovery retains result and applied position; duplicate returns it | Crash at every application boundary | | Leader loses quorum/term | Stop consistent reads/new successful writes; pending outcomes may be unknown | Isolated old leader history | | State-machine nondeterminism/unsupported schema | Fault before divergent application publication | Replica result/state digest comparison | | Snapshot transfer/install interrupted | Keep active generation; retry candidate safely | Chunk loss, full disk, crash at manifest switch | | Session ID reused/conflicting payload | Expired/conflict; no duplicate mutation | Session/floor/restart tests | | Disk corruption / impossible applied index | Quarantine group; surface recovery requirement | Truncation/checksum/position fixtures | | Shutdown during admitted write | Join ownership; durable outcome remains inspectable | Stop/persist/commit permutations | ## Task DAG and acceptance | ID | Phase / dependencies | Scope and gate | Recommended role | | --- | --- | --- | --- | | S-REPLICATION-01 | P0; baseline | NEW adapter and crash-boundary specification, static bootstrap and schema ownership | astra_implementer | | S-REPLICATION-02 | P1; S-REPLICATION-01, Storage/Async/Binary contracts | Stable-storage port conformance and fake transport/clock harness; atomic state invariant fixtures | astra_implementer | | S-REPLICATION-03 | P4; S-REPLICATION-02, Coordination fixed-group gate, RPC unary | Real protocol storage/RPC adapters; durable-before-reply verified on three nodes | astra_implementer | | S-REPLICATION-04 | P4; S-REPLICATION-03, Coordination read gate | Application host, session dedup, atomic applied position and quorum reads; lost-reply/partition histories pass | astra_implementer | | S-REPLICATION-05 | P4; S-REPLICATION-04, S-COORDINATION-05 | Snapshot publish/install/recovery and rate limits; exhaustive selected crash points pass | astra_implementer | | S-REPLICATION-06 | P4; S-REPLICATION-05 | Resource/operations evidence, upper Discovery and Messaging adapters; deterministic restart and minority behavior | sol_implementer | CURRENT: no Replication checks exist or ran. PROPOSED tests combine a deterministic core simulator, faulting Storage port, real-process kills, network loss/reordering, disk faults and a linearizability checker consuming complete invocation/response histories. Check durable reply order, not only final key values. Add targets before documenting commands in [VALIDATION](../VALIDATION.md) / [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md). Measure commit/read/snapshot p50/p95/p99, throughput, allocations, peak RSS/CPU, sync time, retained disk and build cost using [PERFORMANCE](../PERFORMANCE.md). Migrations version wire, log, snapshot and application schemas independently. Enable a new command only after every voter can read/apply it. Keep old readers during a rolling phase; rollback stops admission of new commands and is permitted only when persisted formats remain readable. Restore into a new cluster identity after quorum loss requires explicit operator authorization; it cannot preserve an unsupported continuity claim. See [MIGRATION](../MIGRATION.md) and [DistributedStorage](DistributedStorage.md).