Files

152 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# DistributedStorage subsystem plan — NEW
Status: NEW design; all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-007, R-008, R-011, R-012, R-014–R-016;
[architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-12–C-14.
## Baseline and selected backend
There is no DistributedStorage source directory, client, shard manager or transaction
coordinator at this baseline. NEW proposed roots are `include/Void/DistributedStorage`,
`src/DistributedStorage`, `tests/standalone/DistributedStorage`. Existing
[Net client](../../../include/Void/Net/Http.hpp) is only a future transport precursor;
its coverage gaps 112/115 were checked directly. Neither networking nor the existing Sqlite
module establishes distributed storage. The new design composes [Storage](Storage.md)'s
original engine and [Replication](Replication.md)'s deterministic application host.
Choose native key-value service logic. Local data format, WAL, conditional batches,
snapshots and compaction remain Storage-owned. Consensus remains Coordination-owned;
Replication supplies adapters. DistributedStorage owns key routing, replicated KV commands,
client semantics and later shard movement. It neither exposes SQL nor claims SQLite file
compatibility. SQLite WAL itself requires same-host shared state; putting a WAL database on
a shared network filesystem is not this replication design. See [SQLite WAL restrictions](https://sqlite.org/wal.html).
## First deliverable: one fixed replicated group
```cpp
// NEW illustrative Void::DistributedStorage shapes.
struct Version { GroupId group; LogIndex index; std::uint32_t mutation; };
struct ReadResult { OwnedBytes value; Version version; AppliedPosition observed; };
struct WriteOptions { RequestIdentity identity; OperationOptions operation; };
class Client {
Task<Result<ReadResult>> get(Key, ReadPolicy, OperationOptions);
Task<Result<CommitReceipt>> write(ConditionalBatch, WriteOptions);
Task<Result<ScanPage>> scan(ScanCursor, ScanLimits, ReadPolicy, OperationOptions);
};
```
RequestIdentity/ReadPolicy/CommitReceipt refer to Replication-owned types, conditional
batches and snapshot views to Storage-owned types, and OperationOptions to Async. The Version
shown is a NEW distributed identity, not an assumed Storage version representation. Initial
service has one group and no hidden routing indirection. All writes, deletes and compare/
version predicates serialize in Raft command order. Conditional failure is a committed,
deduplicated result with no partial mutation; a retry returns that same failure/result.
Readers use quorum-confirmed ReadPolicy by default. Stale-local is a separately requested
result with observed position; no cache can silently weaken the policy.
Batch admission validates key/value sizes, identities and precondition syntax before
logging. Committed apply checks predicates against the latest state, computes mutations
and emits one Storage batch containing application state, application result, dedup and
applied-log position. This is atomic within the group. It is not arbitrary client-side
read-modify-write isolation. Get → compute → write requires a version predicate to detect
concurrent updates. Multi-operation batches are all-or-none within one group only.
Scan starts after a fresh read barrier and pins one local Storage snapshot. Cursor binds
group, snapshot ID, route epoch, last key, limits and expiry with integrity protection from
Security; it is opaque and server-owned state remains bounded. All pages use that same
snapshot. Losing its serving node expires the cursor; client restarts explicitly, rather
than getting a mixed-version continuation under the old cursor. One-page scans need not
retain a cursor. Initial cursor TTL is 30 seconds; empty pages cannot extend it forever.
## Resource, failure and operations contract
NEW defaults: key ≤4 KiB, value ≤768 KiB, batch ≤128 mutations/1 MiB for the complete
encoded command including metadata, fitting Replication's command limit;
1,024 writes/group with Replication's 64 MiB/group and 256 MiB/host aggregate limits.
Reads: 256 active/512 waiting; scans: 64 pinned snapshots/group, page ≤1,000 records or
1 MiB, 64 MiB aggregate pinned-version retention budget. Storage pressure can reject new
scans; existing pins live until completion/expiry or explicitly reported cancellation.
Disk defaults inherit Replication's 1 GiB/group development quota; operators size actual
volumes using measured data+WAL+snapshot+compaction headroom. No claimed production capacity.
Default operation deadline 10 seconds; client retries preserve the same session/sequence.
The client follows at most three authenticated not-leader hints within that total deadline;
it never treats an arbitrary redirect as authority to change cluster identity.
| Fault | Behavior | Evidence |
| --- | --- | --- |
| Conditional conflict | Atomic no-mutation result, deduplicated | Competing compare-and-set histories |
| Timeout/lost response after write | Unknown outcome; inspect/retry same identity | Crash after apply before response |
| Minority leader / stale route | No consistent reads or write success; authenticated hint only | Partition and stale leader clients |
| Node dies during scan | Cursor expired/unavailable; no mixed snapshot | Fail serving node between pages |
| Disk full / compaction or pin pressure | Explicit overload/storage fault before unsafe acknowledgement | Quota with long scans and writes |
| Corrupt recovery/snapshot | Group unavailable and quarantined; never return fabricated empty values | Byte mutation/recovery faults |
| Client cancel at commit | One local result; durable outcome still inspectable | Cancel/commit race |
| Incompatible command schema | Reject admission or stop group; never partially apply | Mixed-version command fixtures |
Shutdown stops client admission, drains/cancels reads and scan pins, joins group operations,
then closes the native Storage generation. Cancellation is not distributed rollback. Internal
keys are reserved and unreachable from user keyspace; authorization scopes tenant/key prefix
before routing. Observations label group/shard/method only within cardinality budgets and
never include raw user keys or values.
## Later gate: sharding and rebalance
Do not start sharding until single-group crash/linearizability/snapshot acceptance passes.
Select ordered range shards so scans have a defined traversal order. An upper replicated
metadata group stores range boundaries, owning group IDs and monotonic route epochs.
Bootstrap metadata endpoints are static; metadata is not a prerequisite for the one-group
service. Requests carry shard/epoch; stale epochs return a versioned route hint. Clients
validate nonoverlap/coverage and cache bounded snapshots. Metadata-group loss blocks route
changes; known unaffected ranges can continue only under their current ownership epoch.
Move a range with a freeze-and-copy protocol first, accepting bounded unavailability:
commit `freeze(range, epoch)` in source group → wait for applied barrier → create a pinned
snapshot including all data and retained dedup outcomes → copy/verify/install into destination
as inactive → commit metadata activation of destination at epoch+1 → destination records
activation proof and admits writes → source retains a tombstone/redirect. Old source never
unfreezes autonomously. Before metadata activation an explicit abort may restore source;
after activation complete forward, never roll back by enabling both. Destination checks a
quorum-confirmed metadata proof and persists it before serving, even after restart.
Retain source data until destination durability and metadata acknowledgement are confirmed,
all relevant snapshot pins have ended and a configured seven-day recovery retention elapses.
Transport cancellation only pauses copy. Session IDs include origin group; moved retained
results are consulted before re-executing a retry, including retries arriving at the old
source. Stop writes for any range whose ownership proof is ambiguous. Split/rebalance reuses
the same state machine and journaled phases. Default: one range move/host, 16 MiB/s and 1 MiB
chunks, with required copy headroom validated before freeze.
Cross-shard batches are rejected before mutation. A scan across multiple shards returns
per-shard snapshot positions and explicitly lacks a single global snapshot. Cross-shard
transactions, global serializability and automatic exactly-once external effects are
unimplemented and outside this gate; adding them requires a new architecture/acceptance
contract. Do not disguise partial multi-shard progress as a transactional batch.
## Task DAG and validation
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-DISTRIBUTEDSTORAGE-01 | P0; baseline | NEW KV/identity/consistency contract and history-checker scenarios | astra_implementer |
| S-DISTRIBUTEDSTORAGE-02 | P1; S-DISTRIBUTEDSTORAGE-01, Storage conditional batch contracts | Deterministic KV application with atomic result/dedup/applied batch; local model fixtures | astra_implementer |
| S-DISTRIBUTEDSTORAGE-03 | P4; S-DISTRIBUTEDSTORAGE-02, Replication fixed-group acceptance | Single-group client/server, quorum reads, durable replies; crash/lost-reply histories pass | astra_implementer |
| S-DISTRIBUTEDSTORAGE-04 | P4; S-DISTRIBUTEDSTORAGE-03 | Snapshot scans, quotas, backup/recovery tooling and compatibility; pressure and cursor failure tests | sol_implementer |
| S-DISTRIBUTEDSTORAGE-05 | P4 later; S-DISTRIBUTEDSTORAGE-04, integrated single-group gate | Range metadata, route epochs and ownership proofs; no overlapping owners in model histories | astra_implementer |
| S-DISTRIBUTEDSTORAGE-06 | P4 later; S-DISTRIBUTEDSTORAGE-05 | Freeze/copy/activate rebalance and split; crash at every phase, cross-shard batch rejection | astra_implementer |
CURRENT: no subsystem tests/commands exist. PROPOSED verification uses a sequential KV model,
linearizability checking with unknown outcomes retained, repeated process kills, disk faults,
partition schedules, duplicate identities and exhaustive selected move crash points. Persistence
faults follow [atomic-commit testing methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior),
without claiming the original engine shares SQLite's implementation. Targets must precede
commands; see [VALIDATION](../VALIDATION.md), [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Measure read/write/CAS/scan p50/p95/p99, throughput, allocations, RSS/CPU, disk/write amplification,
recovery and movement pause, plus build cost through [PERFORMANCE](../PERFORMANCE.md). Benchmark
single-group correctness before shard scaling. Migration versions commands, route tables,
cursor and snapshot formats; drain obsolete cursors. Rollback accepts only readable durable
formats and completed ownership proofs, never enables a frozen source after activation.
Backups capture each group and declared metadata positions; a multi-group backup is not a
global transaction snapshot. See [MIGRATION](../MIGRATION.md) and
[DistributedApplications](../platforms/DistributedApplications.md).