docs: add expansion roadmap and workflow baseline

This commit is contained in:
faumaray committed 2026-11-24 02:04:38 +03:00
1 parent f1f9ba375b
commit faa8a5198d
65 files changed
+9292

No files matched your search

+155
View File
@@ -0,0 +1,155 @@
# NEW Algorithms subsystem
Status: NEW design; no Algorithms source directory/target is claimed to exist. All
tasks are **PLANNED**. Source baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
## Existing algorithms and extraction candidates
[Containers Graph](../../../include/Void/Containers/Graph.hpp) already includes BFS,
DFS, topological sorting, reachability and unweighted BFS shortest paths on its owning
directed-graph structure. [DisjointSet](../../../include/Void/Containers/DisjointSet.hpp)
uses path compression and union/rank-style bookkeeping; it remains a container with
algorithmic methods. [PriorityQueue](../../../include/Void/Containers/PriorityQueue.hpp)
maintains key-to-heap indices. [Text Diff](../../../include/Void/Text/Diff.hpp) supplies
a generic span-based Myers edit engine plus text adapters. [Math sampling](../../../include/Void/Math/Random.hpp)
uses standard ranges shuffle over an allocated index pool. These do not establish a
current common Algorithms API.
Existing [graph](../../../tests/standalone/Containers/Graph.cpp),
[disjoint-set](../../../tests/standalone/Containers/DisjointSet.cpp),
[priority-queue](../../../tests/standalone/Containers/PriorityQueue.cpp),
[diff](../../../tests/standalone/Text/Diff.cpp), and
[random](../../../tests/standalone/Math/Random.cpp) suites are migration fixtures.
Coverage reported partial parsing at PriorityQueue line 23 and Diff lines 30/96; these
ranges and the relevant implementations were read directly. Graph-derived relationships
are navigation hints, not proof that every algorithmic precondition is enforced.
## Scope and acyclic dependency decision
Algorithms is native, standard-library-first foundation under
[C-01/C-05](../ARCHITECTURE.md). It owns reusable algorithms whose explicit work budgets,
graph views or edit semantics add value beyond `std::ranges`. Do not reimplement standard
sort, binary search, transform, reductions, heaps, or a parallel execution runtime merely
for naming consistency. Containers/Text may depend on Algorithms; Algorithms imports
neither, avoiding an extraction cycle. It may use Core traits, small local expected error
enums and standard PMR supplied by the caller. Optional Functional/Memory adapters are
separate downward dependencies; no Log/Runtime/Async imports.
Checked distance/size arithmetic may use Math's narrow Numeric interface after
M-MATH-02; Math itself imports neither Algorithms nor Containers. This prerequisite
does not pull dynamic matrices or random-generation headers into algorithm APIs.
NEW proposed paths: `include/Void/Algorithms/Graph.hpp`, `Diff.hpp`, `TopK.hpp`,
`src/Algorithms/module.cmake`, `tests/standalone/Algorithms/`. No files or test commands
for them exist yet. PriorityQueue/DisjointSet ownership remains Containers; Algorithms
uses standard priority_queue/vector scratch rather than pulling the owning types back in.
## NEW graph port and result shapes
Illustrative NEW API:
```cpp
namespace Void::Algorithms {
struct WorkLimits {
std::size_t max_vertices = 65536;
std::size_t max_edges = 262144;
std::size_t max_scratch_bytes = 16 * 1024 * 1024;
};
enum class AlgorithmError { limit, invalid_vertex, invalid_weight,
overflow, cancelled, inconsistent_view, allocation_failed };
struct Topology {
std::vector<std::uint32_t> order;
std::vector<std::uint32_t> cycle; // one witness if cyclic
};
template<class IndexedGraphView>
std::expected<Topology, AlgorithmError>
topological_order(const IndexedGraphView&, WorkLimits, std::stop_token = {});
}
```
The graph view contract supplies `vertex_count()` and repeatable `out_edges(vertex)`
with dense indices [0,V); edge views supply target and weight only when required.
The caller owns immutable input through the call. Concurrent mutation is invalid;
an optional version stamp lets adapters detect changes and return `inconsistent_view`.
No references to temporary edge ranges escape. Containers supplies an adapter from
arbitrary vertex keys to dense stable indices; its mapping allocation is charged by
that adapter, not hidden from memory reports.
Use iterative BFS/DFS with visited arrays and explicit stacks, avoiding recursion depth
as input control. Topological sorting uses Kahn's indegrees and FIFO ready vertices
in input order; if not all vertices are emitted, iterative colored DFS over remaining
vertices returns a concrete cycle witness. Stable results require stable input ordering;
unordered container iteration is not secretly normalized. Dijkstra accepts finite
nonnegative weights, checked distance addition and lazy duplicate heap entries. Each
heap admission counts against scratch, including duplicates. Negative weights reject;
Bellman–Ford is outside the initial gate. An unreachable target returns an empty optional
path inside a successful result, distinct from resource exhaustion or invalid graph.
Work budgets count scanned edges and vertices before expanding scratch. Check stop at
least every 1,024 edge visits and each outer iteration. Pure result-building operations
publish only complete results. Visitor variants document already-delivered callbacks
on cancellation/failure, run without internal locks, and do not claim to undo effects.
Owned scratch allocation failure returns `allocation_failed` without a partial owning
result; exceptions from caller predicates/visitors propagate unless explicitly adapted.
No worker, scheduler or forceful callback interruption is introduced.
## NEW diff and bounded selection
The generic diff engine accepts spans, an equality predicate, edit-distance and scratch
limits, returning index ranges instead of copied payloads. Text owns line splitting,
patch escaping and human formatting. Default combined input cap is 65,536 elements,
distance cap 4,096 and scratch 16 MiB. Index arithmetic is size_t with checked conversion
where signed diagonals are needed. Trace storage reserves only after budget admission.
Hitting a limit returns `limit`; a separately named coarse-replacement strategy may be
added by Text, never silently substituted as a minimal edit script.
Myers trace reconstruction is the initial native implementation to preserve fixtures.
A linear-space divide/reconstruct implementation is a P3 capability gate with the same
deterministic tie-breaking and independent script-application tests. No claimed universal
complexity improvement ignores output size or predicate cost.
NEW streaming `top_k` retains k elements in a standard heap (default k≤1,024, maximum
65,536, 16 MiB scratch), tracks arrival index for stable tie-breaking, and reports k=0
as empty success without allocation. Caller comparator must define strict weak order.
The output policy is explicit ascending/descending and sorted after ingestion. This
supports histogram ranking and bounded diagnostics; it does not replace ordinary
partial_sort for in-memory spans. Math remains owner of probability sampling and RNGs.
## Task DAG
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-ALGORITHMS-01 | P0; extraction source/tests | Record traversal order, path/cycle and diff tie-breaking fixtures; approve one-way Containers/Text→Algorithms adapters. | astra_implementer |
| S-ALGORITHMS-02 | P1; S-ALGORITHMS-01 | Add indexed graph view, work budgets and iterative traversals/topology; stable input yields stable order and cyclic graphs include valid witnesses. | sol_implementer |
| S-ALGORITHMS-03 | P2; S-ALGORITHMS-02; M-MATH-02 | Add bounded shortest paths; negative/nonfinite weights reject, overflow reports and unreachable targets are distinct. | sol_implementer |
| S-ALGORITHMS-04 | P2; S-ALGORITHMS-01 | Extract bounded Myers engine and keep Text adapters; replay transforms source to target and all caps fail before excess allocation. | sol_implementer |
| S-ALGORITHMS-05 | P2; S-ALGORITHMS-01 | Add streaming top-k and instrumentation-free progress counters; reference sorting confirms values/ties and retained scratch stays bounded. | sol_implementer |
| S-ALGORITHMS-06 | P3; S-ALGORITHMS-02–05; measured large-diff profile | Implement linear-space diff only behind conformance/performance gate; publish isolated consumers and compare real graph/diff/top-k workloads. | astra_implementer |
## Verification, compatibility and limits
CURRENT verification is source/test inspection and the parent baseline; no new Algorithms
test or benchmark was executed. PROPOSED property tests generate bounded graphs and
compare reachability/path cost with simple exhaustive small-graph references; validate
every cycle edge and topological relation. Include self-loops, disconnected graphs,
parallel edges, zero weights, invalid targets, cancellation and view-version changes.
Diff tests compare minimal edit lengths against dynamic programming on small sequences,
then replay scripts on large/adversarial inputs. Top-k compares full standard sorting,
including repeated keys and k greater than input size. Allocation fault injection must
leave owning inputs untouched. Sanitizers check index/lifetime bugs; deterministic work
counters prove budget enforcement independent of machine speed.
[PERFORMANCE](../PERFORMANCE.md) profiles sparse/dense dependency graphs, short/long equal
prefix diffs, worst-case dissimilar spans and streaming ranking. Measure p50/p95/p99,
throughput, predicate calls, allocations, scratch peaks, RSS/CPU and build cost. External
algorithm libraries may be reference oracles in development only after separate dependency
approval; initial shipped Algorithms has no external package requirement.
[Migration](../MIGRATION.md) keeps Graph member methods and `Void::Diff` forwarding wrappers
through the major transition. Borrowed index-range results must not be confused with
the old owning copied edits. Rollback uses old wrapper implementations; no persisted
format changes are involved. New consumers need the Algorithms component declared rather
than relying on whole-library tests to supply it. See
[VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
[Containers](../modules/Containers.md), [Text](../modules/Text.md) and [Math](../modules/Math.md).
+140
View File
@@ -0,0 +1,140 @@
# Coordination subsystem plan — NEW deterministic Raft core
Status: NEW design, all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-005, R-011, R-012, R-014–R-016;
[architecture](../ARCHITECTURE.md) C-01–C-05, C-12, C-13.
## Baseline, algorithm and hard boundary
No current consensus module or tests exist; PROPOSED roots are `include/Void/Coordination`,
`src/Coordination`, `tests/standalone/Coordination`. Existing
[Resilience breaker](../../../include/Void/Resilience/CircuitBreaker.hpp) is a local
admission primitive, not leader election or fencing; source and matching graph metadata
were checked. Coordination is a native deterministic protocol with standard-library and
lower-foundation dependencies only. It imports no RPC, Discovery, Storage implementation,
Replication or Runtime. [Replication](Replication.md) owns concrete transport/persistence
adapters and application state machines. This direction is mandatory C-12.
Select fixed-membership Raft first, three or five voting nodes, majority commit, crash-stop/
recovery faults, authenticated non-Byzantine peers and stable storage. A single-node mode
is explicitly a development profile. Protocol design follows the
[extended Raft paper](https://raft.github.io/raft.pdf); timing affects liveness, while
persistence and quorum rules enforce safety. No lease-based linearizable reads, automatic
voter replacement, multi-leader writes or Byzantine tolerance are included initially.
## NEW event/action contract
```cpp
// NEW illustrative Void::Coordination shapes; no IO occurs inside Core.
struct PersistBatch { BarrierId id; DurableStateDelta delta; };
struct Persisted { BarrierId id; }; // confirms durable persistence, not merely write admission
struct Tick { SteadyInstant now; ElectionRandomSample election_sample; };
using Event = Variant<Tick, PeerMessage, Propose, ReadRequest,
Persisted, PersistenceFailed, Applied, SnapshotInstalled>;
using Action = Variant<PersistBatch, SendAfterPersist, ApplyCommitted,
ReadBarrier, RejectProposal, RoleChanged, Fatal>;
class Core {
static Result<Core> recover(FixedConfig, RecoveredProtocolState);
Result<ActionBatch> step(Event);
};
```
These are shape illustrations, not existing Variant/Result aliases. Binary owns wire
encoding primitives; Coordination owns versioned term/index/node/message types. Inputs
own message bytes; emitted actions own or pin their data until acknowledged. Each persist
action has an increasing barrier ID; only matching successful durable completion releases
dependent sends/votes/commit acknowledgements. One adapter event loop serializes `step`;
the core never calls user code or locks an external service. Time progression and election
random samples are explicit events, allowing byte-for-byte replay of histories.
Persisted state includes cluster/group identity, fixed voter list/hash, current term,
voted-for, indexed log records and snapshot's last-included index/term. Recovery validates
contiguity, snapshot boundary and monotonic terms before admitting a peer. Commit knowledge
can be recovered conservatively; applied index is supplied by the application's atomic
state and must never exceed known recoverable committed history. Contradictions fault the
group rather than trimming application state to make a test pass.
## Required state transitions and algorithms
1. Follower election timeout defaults to an injected uniform 300–600 ms; heartbeat 100 ms.
Deployments tune these from measured persistence/network delay, not from a safety claim.
Candidate increments term, votes for self and persists before requesting votes. Grant at
most one vote/term after log freshness check and durable term/vote update. Higher-term
messages cause step-down and persistence before any dependent reply.
2. AppendEntries checks previous index/term, rejects mismatch with a conflict hint and
truncates only an uncommitted conflicting suffix. Never overwrite an applied/committed
position. Persist suffix/term changes before success response. Duplicate or reordered
messages cannot regress match/commit indices. Ignore responses from old terms/rounds.
3. Leader tracks next/match per voter, sends bounded batches and advances commit only when
a majority match an entry from its current term; preceding entries then become committed.
New leader appends a no-op for its term. Proposals are not client successes until the
Replication adapter durably applies the committed command and result. Losing leadership
rejects uncommitted callers as unknown/not-leader without claiming their writes vanished.
4. For a consistent read, first commit the current-term entry. Start a fresh read context,
confirm leadership through current-term responses from a majority after that request,
record its safe read index and emit a barrier. Reply only when application applied index
reaches that index. Step-down invalidates pending read contexts. An isolated old leader
cannot serve linearizable reads from its local data. Explicit stale reads live above core.
5. Emit apply actions in contiguous committed order, bounded by adapter capacity; require
Applied(index) acknowledgement before discarding ownership. Core does not execute commands.
If apply fails, fault/pause the group; never skip an index and acknowledge later writes.
6. Snapshot messages identify cluster/config/format/index/term and bounded chunks. Core
validates boundary and requests installation; adapter atomically installs application,
dedup and applied position, durably records snapshot metadata, then acknowledges. Log
truncation waits for that durable installation; incomplete snapshots cannot displace active
state. Retain a suffix only when the included index/term matches.
The selected read and durability rules correspond to the paper's stable-state and client
interaction sections. Detailed defaults and action barriers here are NEW implementation
decisions, not an assertion that a paper alone verifies this implementation.
## Bounds and failure matrix
NEW defaults: 1 MiB command, AppendEntries ≤64 entries/2 MiB including envelope metadata,
4 in-flight batches/follower,
1,024 proposals and 64 MiB uncommitted payload budget, 256 read contexts, 4,096 queued events
and 64 MiB queued bytes. Log disk quota belongs to the adapter (initially 1 GiB/group).
When lag prevents reclamation, reject new proposals; do not remove required history without
a durable snapshot. Read/proposal deadlines use Async/Time contracts in adapters; expiry
removes caller interest, not protocol history. Core transitions are bounded by batch size;
long catch-up/snapshot work yields between chunks. Shutdown is adapter-driven: stop proposals,
finish persistence barriers and release action ownership only after completion/join.
| Fault | Protocol action / forbidden shortcut | Required evidence |
| --- | --- | --- |
| Minority partition / old leader | No new committed success or consistent local read | Partition histories with concurrent reads |
| Crash before vote/append persistence | No dependent success was sent | Crash every barrier boundary |
| Disk write/sync failure | Fatal/pause; never send a dependent affirmative reply | Inject short write and failed sync |
| Duplicate/reordered/delayed packets | Term/round/log checks; no state regression | Deterministic message permutations |
| Divergent uncommitted suffix | Conflict repair; committed prefix untouched | Election with conflicting histories |
| Snapshot interrupted/corrupt | Keep old state; reject/quarantine candidate | Chunk loss/restart/checksum mutation |
| Apply failure / state mismatch | Fault group and surface corruption | Applied-index invariant fixtures |
| Clock stall/jump / election storm | Liveness may stop; no relaxed quorum | Adversarial Tick schedules |
| Unknown peer/config/version | Reject before core mutation | Cross-cluster/spoofed node messages |
## Task DAG and evidence gates
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-COORDINATION-01 | P0; baseline | Write formal invariants, event model and deterministic test harness specification | astra_implementer |
| S-COORDINATION-02 | P1; S-COORDINATION-01, Binary/Time/Functional contracts | NEW pure types/codec/ports, replay harness; no network/storage/runtime dependency | astra_implementer |
| S-COORDINATION-03 | P4; S-COORDINATION-02 | Fixed voters, elections, append/commit and persistence barriers; model/simulation safety gate | astra_implementer |
| S-COORDINATION-04 | P4; S-COORDINATION-03 | Current-term no-op, read contexts and apply barriers; isolated-leader reads fail | astra_implementer |
| S-COORDINATION-05 | P4; S-COORDINATION-04, snapshot port defined in S-COORDINATION-02 | Snapshot boundary/recovery against a fake port; crash/suffix/corruption tests pass without a Replication dependency | astra_implementer |
| S-COORDINATION-06 | P4 later; S-COORDINATION-05, integrated fixed-group acceptance | Explicit joint-consensus membership protocol plus learners; separate proof/review and fault gate before any voter edits | astra_implementer |
CURRENT: no Coordination targets exist; no consensus execution evidence is claimed.
PROPOSED verification includes a reference state-machine model, exhaustive bounded schedules,
seeded randomized simulations, persistent replay artifacts, partitions and crash/recovery.
Check election safety, log matching, leader completeness, state-machine safety and read
linearizability on recorded histories. Separate adversarial review is required even when
tests pass; commands await target creation in [VALIDATION](../VALIDATION.md).
Measure step p50/p95/p99, actions/second, allocations, RSS/CPU, bytes retained and build
cost under [PERFORMANCE](../PERFORMANCE.md), not a universal consensus speed claim.
Migration versions protocol and persistent formats; mixed unsupported majors refuse peers.
Fixed membership is immutable after bootstrap. Rollback replays a compatible durable
format or restores an approved snapshot into a separately identified cluster; never reset
term/vote in place or reuse a node identity with an empty disk. See [MIGRATION](../MIGRATION.md),
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md) and [Replication](Replication.md).
+121
View File
@@ -0,0 +1,121 @@
# Discovery subsystem plan — NEW
Status: NEW design; all feature tasks PLANNED. Source baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-003, R-009, R-011, R-014–R-016;
[architecture](../ARCHITECTURE.md) C-01–C-05, C-11–C-13.
## Baseline and dependency direction
No Discovery source/target exists in the assigned baseline. Existing
[Net Url](../../../include/Void/Net/Url.hpp) provides endpoint parsing, not a membership,
health or service-discovery protocol; source/graph coverage matched with no recorded issue.
NEW paths are `include/Void/Discovery`, `src/Discovery` and `tests/standalone/Discovery`.
Begin with a static immutable endpoint catalog and local in-process registrations.
Do not require DNS multicast, an external agent, RPC or consensus to discover initial peers.
Discovery owns endpoint sets, revisioned snapshots, local registration lifetime and watch
semantics. [RPC](RPC.md) accepts injected endpoints; its optional Discovery integration
lives above RPC. [Coordination](Coordination.md) imports no Discovery. A later replicated
directory adapter belongs in the Replication/platform integration layer and uses separately
configured bootstrap peers. Discovered leader hints never redefine Raft membership.
## NEW native contract and algorithm
```cpp
// NEW illustrative Void::Discovery shapes.
struct EndpointRecord {
InstanceId instance; ServiceId service; Endpoint endpoint;
std::uint32_t weight; Attributes attributes;
};
struct Snapshot { Revision revision; std::vector<EndpointRecord> records; Freshness freshness; };
class Catalog {
Result<Snapshot> resolve(ServiceId, ResolvePolicy) const;
Result<Registration> register_local(EndpointRecord, LeasePolicy);
Result<Watch> watch(ServiceId, Revision after, WatchCallback);
};
```
Names above are NEW domain types; Endpoint follows Net's endpoint owner, operation options
remain Async-owned. Catalog construction is pure and creates no thread. Static configuration
is validated as a complete snapshot then atomically published; duplicate service+instance
identities, invalid authorities and unsupported metadata cause rejection of the entire
candidate, preserving the active revision. Revisions are local monotonic values with a
provider generation; they are not cluster-wide consensus indices.
Local registrations return move-only RAII handles retaining catalog state. Release removes
future snapshots. Leased registration is explicit, default 30-second TTL and renewal every
10 seconds in an optional managed adapter, measured by injected steady time. Static entries
never expire. A registration handle without a lease is valid until explicit release; zero
TTL is invalid rather than an undocumented permanent registration. Local process shutdown
removes local entries and joins admitted callbacks; destruction alone only requests stop.
Resolution snapshots immutable owned values, sorts by instance identity for deterministic
tests and excludes expired/unready entries by default. Optional stale resolution explicitly
returns freshness/provider error. Failure detection changes availability hints only; it
cannot certify uniqueness, leadership or permission. Weighted round-robin selection is an
optional client-side selector over a snapshot; affinity selection uses stable hashing
only when requested. Address refresh retains the peer's configured identity, so DNS changes
do not disable TLS expected-name checks.
Watch admission returns an initial complete snapshot followed by revisioned changes.
Changes are serialized per watch on the injected executor. If its bounded queue loses
continuity, replace pending deltas with a `resync_required` event and a full latest snapshot;
do not silently pretend all changes were delivered. Callbacks run outside catalog locks.
`cancel` stops new admission; `join` waits for already-admitted callbacks. A callback may
cancel itself, but synchronous self-join is invalid and diagnosed instead of deadlocking.
No watch callback borrows a temporary catalog buffer.
## Upper replicated directory capability
After [Replication](Replication.md) readiness, add a separate directory application with
versioned register/renew/remove commands and quorum-consistent snapshots. Bootstrap endpoints
and cluster identity remain static operator input; it cannot resolve itself into existence.
The replicated application assigns revisions from applied log positions. Lease expiry is a
leader-proposed deterministic command, never each follower independently deleting entries
from local wall clocks. Connection loss reports unavailable/stale according to caller policy.
This adapter depends on Discovery's value/watch interfaces, not the reverse. Dynamic Raft
voting membership remains a separate tested protocol, not an effect of registering an endpoint.
## Bounds and failure matrix
NEW defaults: 1,024 services, 256 endpoints/service, 10,000 total records, 16 metadata
fields/4 KiB aggregate per record, 1,024 watches with 64 events/watch and a shared 16 MiB
event budget. Reject registrations when any cap would be exceeded. Coalesce watch events
before exhausting the shared budget. Cleanup handles at most 256 expirations/turn; resolution
also filters logically expired records so deferred cleanup cannot revive them. Optional
network resolver adapter has 128 outstanding operations and a 5-second total deadline.
| Failure | Required outcome | Acceptance |
| --- | --- | --- |
| Invalid replacement config | Keep old revision; report structured diagnostics | Atomic bad/good snapshot replacement |
| Duplicate registration | conflict; do not steal the old handle's registration | Release/replace race |
| Lease renewal delayed | Expire availability hint; no claim peer is dead | Inject clock/executor delay |
| Watch queue overflow | Explicit resync, bounded retained events | Slow observer sees coherent snapshot |
| Endpoint/TLS identity mismatch | Net verification error; no downgrade | DNS/address replacement fixture |
| Catalog shutdown during callback | Stop admission then join; state retained | Callback reentrancy and self-cancel |
| Replicated directory loses quorum | Strict lookup unavailable; stale API marks revision/freshness | Partition/stale-result tests |
| Malicious metadata/cardinality | Reject before publication; no arbitrary metric labels | Max sizes and cap churn |
## Task DAG and verification
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-DISCOVERY-01 | P0; baseline | Record NEW interfaces and static bootstrap invariants; no consensus dependency | sol_implementer |
| S-DISCOVERY-02 | P1; S-DISCOVERY-01, Time/Functional contracts | Immutable catalog and local RAII registrations; conflict/expiry/atomic replacement tests | sol_implementer |
| S-DISCOVERY-03 | P2; S-DISCOVERY-02, Async scope gate | Bounded watches/selectors and managed renewal adapter; cancel/join/resync tests | sol_implementer |
| S-DISCOVERY-04 | P3; S-DISCOVERY-03, RPC/Net gates | Optional RPC endpoint adapter, observations and identity-preserving refresh; RPC package remains independent | sol_implementer |
| S-DISCOVERY-05 | P4; S-DISCOVERY-04, Replication single-group gate | Upper replicated directory, deterministic expiry commands and static bootstrap; quorum/stale contract tests | astra_implementer |
CURRENT: only the linked Net parsing surface exists; no Discovery checks ran. PROPOSED
tests model revisions, reordered renew/release, clock advancement, executor stalls and
callback overflow, then partition the upper adapter. Add targets before publishing commands;
see [VALIDATION](../VALIDATION.md), [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Measure resolve/watch p50/p95/p99, throughput, churn allocations, peak RSS/CPU, maximum
resync backlog and build cost under [PERFORMANCE](../PERFORMANCE.md).
Migration introduces provider-generation/revision schemas explicitly. Replacing a provider
publishes a full reset snapshot; clients cannot compare unrelated revision domains. Rollback
retains the static catalog and rejects incompatible provider records, without changing voting
membership or trust roots. See [MIGRATION](../MIGRATION.md) and
[DistributedApplications](../platforms/DistributedApplications.md).
@@ -0,0 +1,151 @@
# 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).
+177
View File
@@ -0,0 +1,177 @@
# IO native operations and backend plan
Status: NEW subsystem, all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
There is no existing IO module in the scoped baseline. Requirements R-003, R-006,
R-009, R-012 and R-014 apply; [architecture](../ARCHITECTURE.md) C-02–C-06 is
authoritative. Proposed source roots are NEW `include/Void/IO`, `src/IO` and
`tests/standalone/IO`; none is created by this plan.
## Source anchors and ownership
[Async Executor](../../../include/Void/Async/Executor.hpp) queues borrowed coroutine
handles today; [Task](../../../include/Void/Async/Task.hpp) owns/destroys its frame.
These require [Async's structured ownership gate](../modules/Async.md) before IO
can expose safe cancellable awaits. [System Process](../../../src/System/Process.cpp)
contains local nonblocking pipe/poll logic, and
[System FileWatcher](../../../src/System/FileWatcher.cpp) has a polling thread.
These are integration anchors, not an existing unified reactor. Current
[executor tests](../../../tests/standalone/Async/Executor.cpp) and
[process-stream tests](../../../tests/standalone/System/ProcessStream.cpp) supply
regressions when optional adapters migrate. These paths were graph-coverage checked
and important ownership/source bodies directly inspected.
IO owns native descriptors, transport readiness, partial transfer, buffers, operation
registration and backend shutdown. [Net](../modules/Net.md) owns DNS/protocol semantics,
connection reuse and TLS; IO never imports Net or Runtime. A portable contract with
an explicitly unsupported platform is preferable to pretending Linux facilities exist
elsewhere. Embedded applications inject their driver/executor/clock; Runtime is only
an optional owner of these same resources.
## NEW API sketch
Illustrative types, not compiling examples or delivered declarations:
```cpp
namespace Void::IO {
struct Transfer { std::size_t bytes; bool eof; };
struct BackendOptions { Limits limits; BackendPreference preference; };
class Driver; // explicit poll/run/stop/join
class ByteStream { // owns shared descriptor state
public:
Coro::Task<Result<Transfer>> read_some(
std::span<std::byte>, Async::OperationOptions = {});
Coro::Task<Result<Transfer>> write_some(
std::span<const std::byte>, Async::OperationOptions = {});
Coro::Task<Result<void>> close_and_join(Async::OperationOptions = {});
};
// read_exact / write_all are bounded composed operations on ByteStream.
// File::read_at / write_at / sync and socket accept/connect use the same options.
}
```
`Result` is Functional's shorthand. The sole OperationOptions type belongs to Async:
`std::stop_token` plus optional absolute steady deadline, with Time's injected clock
bound to the driver. No IO request context duplicates it. A caller holds borrowed spans
stable until the terminal result is delivered, including delayed backend cancellation
acknowledgement. An owning-buffer overload transfers Memory-owned buffer leases for
cross-component use. IO never retains a bare pointer beyond that lease.
Default one active read and one active write per stream; a second same-direction
operation returns busy rather than quietly changing ordering. Read zero indicates
EOF only when requested length is nonzero and the backend reports peer EOF; a zero-length
request succeeds immediately without probing EOF. Half-close affects one direction;
readable buffered data drains before EOF. Write success means accepted by the OS, not
received or durably stored by a peer. Transfer failures retain bytes already transferred
and native error cause. Exact/all compositions preserve progress and the original total
deadline; cancellation cannot undo transferred bytes.
## Initial Linux algorithms
Select native nonblocking sockets with level-triggered epoll, no EPOLLET. Readiness is
a hint; syscalls still handle EAGAIN, EINTR, short transfer, EOF and errors. Level-triggered
semantics avoid requiring every dispatch to drain a descriptor completely; the fairness
budget can yield while data remains ready. This follows the
[Linux epoll interface](https://man7.org/linux/man-pages/man7/epoll.7.html).
One driver thread owns interest updates and descriptor generations. Producers submit
bounded control messages and wake it through eventfd; an embedder may drive bounded
`poll_once` turns instead. Dispatch up to 64 ready descriptors and 64 KiB/direction per
descriptor per turn before yielding. Enable writable interest only with pending writes
to avoid idle busy loops. HUP/ERR still trigger final read/error inspection. Async
completion tickets transfer continuations to the supplied executor outside driver locks.
Registration token is `(slot, generation)`, not just the integer fd. Close invalidates
the slot, removes epoll interest, cancels pending operations and drains their backend
references before descriptor reclamation. Stale ready events cannot target a reused fd.
Stop callbacks enqueue retained control records; they never close a potentially reused
integer directly. Socket connect completion checks the socket error state; accept loops
obey the same fairness/admission budget. Platform-specific endpoint conversion remains
an IO/Net adapter detail until the Net endpoint contract is integrated.
Files initially use a bounded native blocking worker pool. Positional pread/pwrite
avoids shared offset races; default writes/syncs for one file are serialized in admission
order, and reads expose explicit offsets. Worker ownership retains descriptor and buffer
until the syscall returns. Cancelled queued work is removed before execution; an active
blocking syscall may continue. Deadline expiry records intent; result classification and
delivery wait for backend evidence and the end of buffer access. A sync that actually
succeeds returns success even after stop/expiry, so a higher-level commit can use that
evidence. A sync failure preserves its native cause and unknown-durability classification;
stop neither hides it nor turns it into success. Cancelled before execution is distinct
from executed with unknown effects. Do not promise hard shutdown bounds for stalled
filesystems.
## Completion state and shutdown
IO uses Async's operation control block rather than a second completion state machine.
Submission reserves global and per-descriptor quotas, attaches stop/timer registrations,
then exposes a retained backend request. Completion before suspension uses Async's
handshake. Stop/timeout requests cancellation; the operation owner classifies one result
from backend evidence under Async's single-delivery contract. Cancellation before a
syscall starts can return cancelled/timed-out with zero effects. A completed syscall
preserves its successful result or failure and byte/effect count, even after stop intent;
composed exact/all transfers may then stop before their next syscall and report cumulative
progress. Late sync success/failure must remain available to Storage/Update adapters.
Only terminal delivery is arbitrated once; no callback is delivered merely because stop
arrived while backend access or outcome classification was still pending.
Driver shutdown closes admission, cancels queued requests, asks active requests to
stop, drains readiness/control/completion lanes, joins file workers, then releases
descriptors/wake resources. It must keep the executor alive until all completion tickets
drain. `close_and_join` cannot free buffers when its own deadline expires; return an
incomplete-shutdown report through the owning driver and retain work. Blocking joins
are off-driver/off-worker operations; embedded drivers pump until their scopes join.
## Finite defaults and backend gate
Default limits per driver: 4,096 descriptors, 8,192 admitted operations including active
workers and pending completion delivery, 4,096 timers, 16 MiB owned buffer leases,
1,024 ordinary control submissions and four file workers with 256 queued file requests.
One pending read/write per stream counts toward all relevant quotas. Internal completion
slots are reserved per admitted operation. Control stop records coalesce by operation,
so cancellation cannot create an unbounded secondary queue. Reserve before allocation;
return overloaded on exhaustion. Caller-owned buffers count in operation size accounting
but remain the caller's allocation; telemetry separates owned and borrowed bytes.
Initial backend choice is fixed at driver creation. Optional io_uring is P3 work only
after epoll/file-worker conformance and measured need; it uses capability probes and the
same ownership/error model. Unsupported capability falls back before submission when
policy permits. Never retry a possibly effective write/sync on a different backend.
No libuv/Asio dependency is introduced. Existing Boost paths in Net remain until their
own interoperability/migration gate passes. Future non-Linux backends get independent
capability tables and the common operation conformance suite.
## Ordered implementation backlog
All rows are PLANNED; dependency references are capability gates where peer task IDs
are not owned by this document.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-IO-01 | P1 / Async operation ownership and Time clock gates | Portable transfer/error/driver API, buffer leases, descriptor and quota ownership | Mock backend completes/stops in every ordering with exactly one result and no borrowed-buffer escape / astra_implementer |
| S-IO-02 | P1 / S-IO-01 | Level-triggered epoll driver, wake/control path, generation-safe close and stream operations | Fragmentation/EAGAIN/EINTR/HUP/fd reuse and full queues do not lose completion or busy-spin / astra_implementer |
| S-IO-03 | P2 / S-IO-01 | Bounded positional file workers, serialization, sync and active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync success/failure after stop remains authoritative in the sole result / astra_implementer |
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, optional System/Net adapters | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
| S-IO-05 | P3 / S-IO-04; performance harness | Optional io_uring capability/backend gate and portability conformance specification | Same tests pass; denied/unsupported capability falls back only before submission; profile evidence justifies enablement / astra_implementer |
## Validation, measurements and migration
CURRENT source fixtures run through
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here, and there are no IO tests/targets today. PROPOSED implementation adds
socketpair/loopback fixtures with tiny buffers, half-close, reset during write, no-data
idle soak, stop while completion queue is full, fd reuse with stale events, immediate
completion during await registration, and stalled file-worker tests with manually
released gates. Inject stop before sync execution and during it, then release success or
failure; verify the distinct results, single delivery and retained descriptor ownership.
Use injected clocks, syscall shims and isolated filesystem fixtures;
race/lifetime sanitizer checks are specified in [VALIDATION](../VALIDATION.md).
Measure operation p50/p95/p99, loopback/file throughput, wake/syscall counts, allocations,
peak owned bytes/RSS/CPU, descriptor leaks and build cost under latency/throughput/footprint
profiles in [PERFORMANCE](../PERFORMANCE.md). No backend benchmark ran here. Existing
System and Boost Net implementations migrate through explicit adapters with equivalent
partial-transfer/error tests. A backend rollback requires draining the old driver and
creating a new one; accepted operations are never replayed. See
[MIGRATION](../MIGRATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[Runtime](Runtime.md), [IPC](IPC.md), and [DELIVERY](../DELIVERY.md).
+178
View File
@@ -0,0 +1,178 @@
# IPC framed local transport and resource isolation plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
No existing IPC source module is assumed. NEW proposed roots are `include/Void/IPC`,
`src/IPC` and `tests/standalone/IPC`. Requirements R-003, R-006, R-009 and R-014
apply; [architecture](../ARCHITECTURE.md) C-02–C-06, C-09 and C-13 governs the design.
## Existing anchors and target boundary
[System Process](../../../include/Void/System/Process.hpp) and
[Process.cpp](../../../src/System/Process.cpp) already use subprocess pipes, output
capture and synchronous streaming callbacks. They do not provide framed request/reply
IPC, peer authorization or negotiated quotas. [Async Channel](../../../include/Void/Async/Channel.hpp)
is in-process blocking synchronization, not a process channel. These paths and their
[streaming](../../../tests/standalone/System/ProcessStream.cpp)/
[channel](../../../tests/standalone/Async/Channel.cpp) tests were coverage-checked;
the relevant Process partial declarations were directly read.
IPC owns local framing, handshake, peer policy and bounded request correlation over
[IO](IO.md) streams. [Binary](../modules/Binary.md) owns encoding primitives;
[Data](../modules/Data.md) owns optional payload schemas. [RPC](RPC.md) may compose
IPC as a transport; IPC never imports RPC, Runtime, Plugin or distributed coordination.
Process supervision stays System/Runtime-owned. Using IPC for plugin isolation requires
an application protocol and restart policy; it is not an ABI-compatible dlopen adapter.
## NEW API sketch and Linux transport choice
Illustrative additions, not compiling examples:
```cpp
namespace Void::IPC {
struct Limits { std::uint32_t frame_bytes, inflight_requests, queued_frames; };
struct PeerPolicy { AllowedIdentity identity; EndpointPermissions endpoint; };
class Session {
public:
Coro::Task<Result<Message>> request(
OwnedBytes payload, Async::OperationOptions = {});
Coro::Task<Result<void>> send(OwnedBytes, Async::OperationOptions = {});
Coro::Task<Result<void>> close_and_join(Async::OperationOptions = {});
};
// listen_local(path, PeerPolicy, Limits, injected_io) -> Result<Listener>;
// adopt_pipe_pair(owned_descriptors, trusted_child_identity, Limits) -> Result<Session>;
}
```
Use pathname Unix-domain SOCK_STREAM sockets on Linux first, with IO's nonblocking
level-triggered epoll backend. A stream does not preserve message boundaries; framing
is mandatory. The listener applies restrictive socket/directory permissions and
checks kernel-reported peer credentials against explicit policy. Linux credential and
pathname behavior is described by [unix(7)](https://man7.org/linux/man-pages/man7/unix.7.html).
Credentials identify the local OS peer; the host still authorizes operations. A PID
alone is not a durable identity or permission to access every service.
Default policy allows only the configured user ID checked against reported peer
credentials, not every local account.
Create endpoints beneath an application-owned directory with mode 0700 and socket mode
0600. Refuse an unexpected existing path/symlink; never unlink an arbitrary caller path.
Stale endpoint cleanup requires verified ownership and failed connection under a serialized
listener startup lock. Abstract namespace sockets are an explicit later option because
their access-control behavior differs. Anonymous pipe-pair transport is initially limited
to descriptors created for a supervised child; it inherits the same framing and quotas
without pretending it has socket peer credentials. No shared-memory transport in P2.
## Wire format and handshake
NEW V1 framing uses a fixed 24-byte header, encoded field-by-field in big-endian order;
never send a native C++ struct or assume its packing:
| Offset / bytes | Field | Rule |
| --- | --- | --- |
| 0 / 4 | Magic | ASCII `VDIP` |
| 4 / 2 | Version | 1; reject unsupported major before payload allocation |
| 6 / 2 | Flags/type | Low byte: hello=1, request=2, response=3, error=4, cancel=5, one-way=6, goaway=7; high byte zero |
| 8 / 4 | Payload length | Excludes header; capped by negotiated limit |
| 12 / 4 | Stream ID | Must be zero in V1; streaming/multiplexed flow control is a later versioned capability |
| 16 / 8 | Request ID | Nonzero for request/response/cancel; zero for connection control/one-way |
Incremental parser states are header → validate → reserve bytes → payload → dispatch.
Handle fragmented headers, multiple coalesced frames and EOF mid-frame. Validate magic,
version, flags, length and request ID before allocation. Oversized/malformed frames close
the connection with a bounded protocol error; do not attempt unbounded resynchronization.
Only dispatch a complete frame. Payload encoding is opaque bytes unless an explicitly
negotiated Data/Binary schema is selected; general JSON acceptance never relaxes signed
StrictJson contracts.
Both peers first exchange hello frames, each at most 4 KiB, with protocol version,
capabilities, frame/concurrency limits and application-protocol ID/version. Choose the
minimum supported limits, fail required-capability mismatch and complete within a
5-second injected steady deadline. Authenticate/authorize peer before admitting user
requests. Default session is full-duplex request/reply: each side chooses monotonically
increasing nonzero IDs from its own outgoing namespace, and message direction/type
disambiguates replies. IDs are not reused during a session; exhaustion triggers goaway
and reconnect. One-way sends report only local write completion, never remote execution.
## Ownership, cancellation and quotas
Session owns its stream, parser buffers, pending request map, send queue and Async scope.
OwnedBytes retains Memory storage until IO completes; received Message owns its payload
through handler return. No string_view into a recycled parser buffer escapes. Handlers
run on the injected executor outside session/map locks. Retain correlation entries
until the single terminal result is selected, and remove them on all failure paths.
Async OperationOptions supplies std::stop_token and the total absolute steady deadline;
no IPC-specific context. Cancellation removes a queued unsent request or emits one
bounded cancel frame for an admitted request. Remote cancellation is advisory: it cannot
undo effects and requires an acknowledgement to establish remote quiescence. A locally
timed-out request can have an unknown remote outcome. Do not automatically resend it
after reconnect. Applications use idempotency keys for retryable effects. A bounded
tombstone set recognizes late responses; never complete a reused ID or deliver twice.
Defaults: 1 MiB payload/frame, 64 in-flight outgoing requests/session, 64 active incoming
handlers/session, 128 queued output frames, 4 MiB queued output bytes, 2 MiB receive
buffer/session, 256 late-response tombstones and 128 sessions/listener. Listener global
owned-buffer budget defaults 64 MiB; global permits are reserved as well as per-session
permits, preventing the product of local caps from escaping the global budget. User
admission rejects overload; optional capacity waiting is cancellable with 128 waiters.
Output control frames have a reserved 8 KiB/16-frame lane and coalesce duplicate cancels.
When handler capacity is full, reject new complete requests with overload using reserved
capacity rather than blocking all reads and deadlocking bidirectional replies. Bound
per-peer request rate to a configurable default 1,000 requests/second with burst 128;
violations receive bounded error/goaway. Waiting payload bytes and active handlers count
toward quotas. Default idle session deadline 60 seconds, header/payload progress timeout
5 seconds within the total request deadline; no byte trickle can restart that total.
V1 does not transfer file descriptors, arbitrary object references or shared memory.
Ancillary descriptor passing is a later explicitly negotiated feature with descriptor
quotas and ownership checks. Current transport scope therefore excludes confused ownership
of received file handles. Connection loss faults all pending calls with transport-lost
and known/unknown effect metadata; it does not imply a failed remote commit.
## Shutdown and backend evolution
Close listener admission, send goaway, stop new user sends/requests, drain already admitted
responses under the caller deadline, request handler stop, join callbacks and IO, then
release stream/path ownership. Joining is off the session's own handler strand unless
already drained; self-join is rejected. Incomplete shutdown retains handler/IO owners.
Peer crash mid-frame releases all reserved bytes after IO stops accessing them.
Native Unix sockets/pipes and Binary framing are selected over an external messaging
library to keep protocol and quotas Void-owned. Windows named pipes and local TCP are
future capability adapters with identical framing/error conformance and explicit peer
identity differences. Shared-memory rings need a later measured gate defining crash
ownership, atomics/layout and buffer reclamation; they are not an implicit fast path.
## Ordered implementation backlog
All rows are PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-IPC-01 | P1 / Binary codec, Async ownership and IO stream gates | Versioned codec, incremental parser and global/per-session permits | Every fragmentation/coalescing/length boundary respects quotas before allocation / sol_implementer |
| S-IPC-02 | P2 / S-IPC-01; System ownership gate | Unix listener, pathname lifecycle, credential policy and supervised pipe adoption | Wrong user/path/symlink rejected; failed startup removes only owned endpoint / astra_implementer |
| S-IPC-03 | P2 / S-IPC-02 | Handshake, request correlation, bounded handlers/cancel/tombstones and goaway | Late response/timeout/loss delivers once; saturated bidirectional sessions still process control / astra_implementer |
| S-IPC-04 | P3 / S-IPC-03; Runtime/Plugin process-host specification | Joined shutdown, isolated-worker reference protocol and diagnostics | Worker crash faults pending calls without replay; retained payloads/handlers drain within ownership rules / sol_implementer |
| S-IPC-05 | P3 / S-IPC-04; measured transport need | Portable transport capability specification and optional descriptor-passing design gate | Common conformance on each supported backend; unsupported identity/feature never silently downgrades / astra_implementer |
## Validation, performance and migration
CURRENT aggregate source-regression command:
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun; no IPC tests exist today. PROPOSED checks need NEW fixtures: frame-byte
fragmentation/fuzzing, maximum/overflowing length, duplicate ID, invalid hello, slow
header, peer death after effect before reply, cancellation before/after send, request
flood/global cap, bidirectional overload, unauthorized credentials, stale socket path,
callback throw and shutdown with live response buffers. No real credentials enter
fixtures or traces. Use isolated user/path fixtures where the test environment permits.
Measure round-trip p50/p95/p99, frame throughput, allocations/copies, peak RSS/CPU,
descriptor count, queue occupancy and build cost under [PERFORMANCE](../PERFORMANCE.md).
No performance claims or benchmark runs accompany this plan. There is no legacy IPC
API; System process-stream output remains text until explicitly adapted to a framed
worker. Wire upgrades negotiate before requests; reject incompatible version, retain
old reader fixtures and reconnect only after draining. No automatic request replay
on protocol/backend rollback. See [MIGRATION](../MIGRATION.md),
[VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[RPC](RPC.md), and [DELIVERY](../DELIVERY.md).
+164
View File
@@ -0,0 +1,164 @@
# NEW Memory subsystem
Status: NEW design; no Memory source directory or target exists in the inspected
foundation inventory. All tasks are **PLANNED**. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
## Existing capabilities to reuse
[Containers ObjectPool/FixedPool](../../../include/Void/Containers/Pool.hpp) manage typed
objects; [BufferPool](../../../include/Void/Containers/BufferPool.hpp) recycles power-of-two
vector buffers. Their leases/deleters currently reference pool objects. These are
Containers APIs, not existing Memory resources. Their
[pool](../../../tests/standalone/Containers/Pool.cpp) and
[buffer-pool tests](../../../tests/standalone/Containers/BufferPool.cpp) provide fixtures
for later adapters. [Core Scope](../../../include/Void/Core/Scope.hpp) can supply lifetime
guards above a low-level resource without becoming an allocator implementation.
These source files were read; coverage reported no recorded graph gaps. No current
resource-accounting or allocator-performance claim is inferred from their existence.
## Owner, dependency and backend decisions
Memory owns allocation facilities under [C-01/C-04/C-05](../ARCHITECTURE.md). Select native
bounded arenas, tracking/budget resources and fixed-block free lists on top of standard
`std::pmr::memory_resource`. The foundation needs only the standard library. Typed object
pools, small vectors and lease semantics remain in Containers. Do not pull Containers,
Runtime, IO, Log or platform allocators into Memory. System may later provide an OS page
resource adapter above this contract; Memory must not require mmap or huge pages.
No replacement global operator new, process allocator interposition or mandatory
jemalloc/mimalloc backend is part of the initial design.
NEW proposed paths: `include/Void/Memory/Resource.hpp`, `Arena.hpp`, `BudgetResource.hpp`,
`BlockPool.hpp`, `src/Memory/module.cmake` and `tests/standalone/Memory/`. Their creation
is future feature work, not an artifact claimed by this documentation task.
## NEW API shape
Illustrative proposed declarations:
```cpp
namespace Void::Memory {
enum class AllocationError { invalid_alignment, size_overflow, exhausted,
upstream_failure, live_allocations };
struct ResourceStats {
std::size_t requested_live, committed_live, peak_committed;
std::uint64_t allocations, failures;
};
class BudgetResource : public std::pmr::memory_resource {
public:
explicit BudgetResource(std::size_t byte_limit,
std::pmr::memory_resource& upstream);
std::expected<void*, AllocationError>
try_allocate(std::size_t bytes, std::size_t alignment) noexcept;
ResourceStats stats() const noexcept;
// PMR virtual allocate/deallocate/equality overrides supplied by implementation.
};
class Arena {
public:
explicit Arena(std::span<std::byte> initial, std::size_t maximum_bytes,
std::pmr::memory_resource& upstream);
std::expected<void*, AllocationError> try_allocate(std::size_t, std::size_t) noexcept;
std::expected<void, AllocationError> reset();
};
}
```
Keep the compact enum allocation-free; Functional owns its optional error adaptation.
PMR `allocate()` throws `std::bad_alloc` on exhaustion as its standard contract requires;
`try_allocate` translates upstream allocation failure to the enum and does not allocate
diagnostics. Programmer misuse (wrong owner, byte size or alignment on deallocation)
is a contract violation with debug diagnostics, not silently ignored successful cleanup.
Resources compare equal only when their deallocation ownership domains are interchangeable.
## Allocation algorithms and ownership
BudgetResource admits committed bytes atomically before asking upstream. Charge requested
bytes plus resource-controlled alignment/header overhead, guard addition against overflow,
and undo the reservation if upstream fails. Current and high-water counts use the same
definitions. Standard upstream hidden allocator overhead/RSS is measured separately;
a resource limit does not falsely bound all process memory or allocations by arbitrary
user callbacks. Deallocate is noexcept and updates counters after returning memory to the
same upstream owner. Optional event observers receive compact records after bookkeeping
and outside locks; no dependency on a logging/export backend exists.
Arena uses checked aligned bump offsets in owned slabs. Initial profile: 64 KiB slabs,
maximum 16 MiB per arena, power-of-two geometric growth up to 1 MiB/slab. An empty initial
span requests the first owned slab lazily; a fixed-buffer mode has no upstream fallback.
Alignment must be a nonzero power of two; over-aligned requests use an appropriately
aligned slab and charge padding. Zero-byte allocation reserves one addressable byte,
making its accounting explicit. Reset invalidates all raw pointers; it is legal only
after clients release their objects/leases. The arena does not discover destructors of
raw allocations. A separate typed scope records destructors in reverse construction
order within a bounded metadata budget (4,096 registrations default).
Arena checkpoints contain resource identity, generation, slab and offset. Rewind accepts
only a current checkpoint with no surviving typed allocations after it; generation
validation rejects stale checkpoints. Do not imply rewind undoes externally visible
side effects. `reset()` on an arena with registered live leases returns `live_allocations`.
Bare raw-pointer clients obey the documented precondition; no runtime can prove every
raw pointer has gone away.
BlockPool preallocates slab metadata and uses a free-index list for fixed-size aligned
blocks. Default cap: 4,096 blocks and 16 MiB committed bytes, whichever is reached first.
Free/recycle performs no allocation. A single-thread resource is the default; a NEW
synchronized wrapper serializes admission/free and snapshots stats. Do not advertise
lock-free allocation. Idle trimming is explicit and never releases outstanding blocks.
Large-object fallback is opt-in, charged to the same budget and owner.
Borrowed `memory_resource*` must outlive every allocation, PMR container, final backend
completion and destructor using it. NEW `SharedResource` retains a stationary resource
control block for owning cross-component leases; it does not extend the lifetime of a
separately borrowed upstream. Containers' owning pool leases retain that state, while
embedded callers may choose documented borrowing. Runtime holds its resources through
stop-admission → cancel/drain → join → destroy-objects → destroy-resources. Memory owns
no threads and cannot itself cancel outstanding application work.
## Admission and performance policy
Aggregate resources may be nested (request within service within process). Charge every
owned allocation to each relevant parent once; avoid counting an arena slab both as its
own internal allocation and a duplicate child request in the same reported total.
Expose requested bytes and committed slab bytes separately. Cancellation/failure paths
must release reserved capacity even when construction above Memory throws.
Budget exhaustion reports before partial object construction. Callers may explicitly
wait for capacity through Async, but Memory never blocks on an executor or starts a
reclaimer thread. Zero cap allows no positive allocation. Unlimited policy is a named
tag, not zero. Sensitive erasure belongs to Security's buffer type: Memory reuse is not
a promise that prior bytes are scrubbed.
## Task DAG
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-MEMORY-01 | P0; existing pool inventory; shared C-04/C-05 | Define requested/committed accounting and resource lifetime fixtures; enumerate pool migrations without changing their APIs yet. | astra_implementer |
| S-MEMORY-02 | P1; S-MEMORY-01 | Add resource/budget/PMR contracts and failure-safe admission; zero/exact/overflow and concurrent cap tests show no leaked reservation. | sol_implementer |
| S-MEMORY-03 | P1; S-MEMORY-02 | Implement fixed/growing arenas, generation checkpoints and typed destructor scopes; over-alignment, failed growth and stale rewind tests pass. | sol_implementer |
| S-MEMORY-04 | P1; S-MEMORY-02 | Implement bounded block pool and synchronized wrapper; recycle allocates zero and trimming never touches live blocks. | sol_implementer |
| S-MEMORY-05 | P2; S-MEMORY-03–04; Containers lease contract | Add SharedResource and adapt typed pools without a reverse dependency; retained leases safely release after front-end owner destruction. | astra_implementer |
| S-MEMORY-06 | P3; S-MEMORY-05; Runtime shutdown gate | Validate embedded/managed teardown and allocator workload profiles; installed Memory-only consumer links with no runtime/backend packages. | sol_implementer |
## Validation, migration and rollback
CURRENT source tests above cover existing pools only; no Memory test or benchmark exists
or was run. PROPOSED checks require the NEW target/suites and supported toolchain:
allocation-failure injection at every upstream call; alignment 1 through over-aligned
types; SIZE_MAX arithmetic; zero-byte requests; destructor ordering; generation wrap;
cross-owner misuse diagnostics; concurrent admission/free; and shutdown with outstanding
leases. ASAN/UBSAN validate storage lifetime, TSAN the synchronized resource; invariants
also need deterministic counters and free-list model tests.
Profiles compare std::pmr defaults, bounded arena, fixed block and synchronized wrappers
for request parsing, coroutine/frame storage and buffer churn. Report p50/p95/p99,
allocations, throughput, committed/requested peaks, RSS/CPU and build cost under
[PERFORMANCE](../PERFORMANCE.md). Separate fresh-page cost from warmed recycle cost.
No allocator-speed claim is made in advance.
[Migration](../MIGRATION.md) introduces Memory independently, then replaces pool internals
behind tested Containers adapters. Caller-supplied PMR pointers remain explicitly borrowed;
no migration silently promotes them to owned. Rollback restores old pool implementations
and package selection after draining all new-resource allocations. Never free through
another allocator or unload a plugin generation while its resource/deleter is still used.
See [VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
[Containers](../modules/Containers.md) and [Runtime](Runtime.md).
+124
View File
@@ -0,0 +1,124 @@
# Messaging subsystem plan — NEW
Status: NEW design; all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-009, R-011, R-012, R-014–R-016;
[architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-11–C-13.
## Baseline and ownership
No current Messaging directory, broker or delivery guarantee is claimed. Existing
[Net WebSocketSessions](../../../include/Void/Net/Server.hpp) is a connection registry,
not durable messaging. Its graph parse gaps at 207/211/214 were read directly; source
does not imply a wire transport. Proposed roots `include/Void/Messaging`, `src/Messaging`
and `tests/standalone/Messaging` are NEW. Messaging owns delivery state, queue/group
semantics, acknowledgements and retry policy. [Storage](Storage.md) owns durable batches;
[RPC](RPC.md) owns remote envelopes; [Replication](Replication.md) optionally supplies a
replicated queue state machine. None depends back on Messaging.
Select native queue/delivery logic with a single-node durable Storage adapter first.
Transport remains optional. An in-process ephemeral channel is explicitly nondurable;
it must not use the same success label as durable publish. An external broker adapter
is a later capability gate with its own conformance matrix, not the initial backend.
## NEW API and delivery contract
```cpp
// NEW illustrative Void::Messaging shapes; Result/Task/options follow C-02/C-03.
enum class PublishDurability { memory, durable };
struct Message { MessageId id; OwnedBytes payload; Headers headers; };
struct Delivery { Message message; Receipt receipt; std::uint32_t attempt; };
class Queue {
Task<Result<PublishReceipt>> publish(Message, PublishDurability, OperationOptions);
Task<Result<Delivery>> receive(ConsumerGroup, OperationOptions);
Task<Result<void>> ack(Receipt, OperationOptions);
Task<Result<void>> nack(Receipt, RetryDelay, OperationOptions);
};
```
Durable delivery is explicitly at-least-once. Message IDs are application-visible;
receipts additionally identify queue, group and delivery generation. Ack means the queue
durably recorded processing acknowledgement, not that the external world changed exactly
once. Consumer effects followed by a crash before ack can run again. An application may
atomically write effects plus an inbox dedup record only when both share one supported
Storage batch; an email, payment or arbitrary RPC is outside that atomicity boundary.
Outbox recipes store a business mutation and outbound message in the same local batch,
then publish/retry by stable ID. They do not create cross-system transactions.
Initial durable model is FIFO work queues per consumer group with competing consumers.
Order is enqueue sequence within a queue, not completion order when concurrency >1.
Single-active-consumer mode provides ordered processing only if the application waits
for ack before the next delivery; retries block that group's head in this mode. Parallel
mode can complete out of order. Pub/sub uses named groups, each with independent offset,
retry and retention state. There is no global order across queues/groups.
Native state machine: Pending → InFlight(receipt-generation, visibility deadline) →
Acked, or Pending after nack/visibility expiry, or DeadLetter after exhaustion. Publish
durably inserts payload, sequence and initial group records before returning durable
success. Receive persists delivery generation/attempt before exposing the receipt.
Ack is a conditional atomic state change matching the current receipt. Old receipt:
stale_receipt; repeat ack of the same acknowledged receipt: successful idempotent result.
Nack/ack races serialize in writer order. An abandoned Delivery is not implicitly acked.
Visibility defaults to 30 seconds, extension explicit up to 5 minutes per delivery.
Use injected monotonic timers while running. On restart all prior InFlight records become
eligible for redelivery with a higher generation; old worker receipts cannot acknowledge
the new attempt. Retention expiry uses recorded civil instants and an injected clock;
clock-health failure pauses expiry rather than discarding potentially live messages.
Retry: five delivery attempts total, full jitter base 1 second/cap 60 seconds, injectable
randomness. DLQ insertion and source removal are one atomic batch in the same store.
If DLQ is full or unavailable, keep the message and block/drop no data; expose stuck count.
## Bounds, shutdown and operational failures
NEW defaults: message ≤768 KiB, headers ≤8 KiB/32 fields, 1,024 queues, 32 groups/queue,
64 in-flight deliveries/group, 1,024 waiting receives/module and 64 MiB transient payload
budget. Persistent quota defaults to 1 GiB, including retry/DLQ/group metadata. Durable
publish identity outcomes retain 24 hours and at most 100,000 IDs; at capacity reject new
publish, never silently evict an identity still within its contract. Older IDs outside
the retention contract can be published again, so application dedup remains necessary.
Logical retention defaults to seven days and requires an explicit policy for unread
messages: the initial policy blocks further publish at quota, rather than expiring unread
work silently. Operators may explicitly choose lossy expiry in a separately named mode.
Stop admission → wake/cancel pending receives → drain active consumers for 10 seconds →
persist remaining visibility state → join owned tasks. A callback receives an owning
message handle until it returns; no payload is reclaimed while a delivery owns it.
Observers run outside queue/storage locks with bounded labels and no payload/secret logging.
| Trigger | Required behavior | Gate |
| --- | --- | --- |
| Publish sync fails / reply lost | Error or unknown outcome; stable ID permits inspection/retry | Crash at insert/sync/reply boundaries |
| Consumer effect then process dies | Redeliver; duplicate expected | Inbox/outbox sample proves stated boundary |
| Visibility expires / old ack arrives | New generation; stale ack cannot remove newer work | Controlled timer/receipt histories |
| Poison message | Retry bound then atomic DLQ move | Attempt counter survives restart |
| DLQ or queue quota full | Stop affected admission; retained work remains durable | Disk full and retention pressure |
| Cancellation during ack | Ack may have committed; query by receipt | Lost-reply and duplicate-ack cases |
| Partition in replicated mode | Minority cannot durable-publish/ack | Quorum adapter tests |
| Unknown schema / corrupt payload | Quarantine/report; no acknowledgement as processed | Corruption and consumer-version tests |
## Task DAG and validation
| ID | Phase / dependencies | Implementation and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-MESSAGING-01 | P0; baseline | Record NEW boundary and build-independent delivery model fixtures | sol_implementer |
| S-MESSAGING-02 | P1; S-MESSAGING-01, Async/Time/Binary contracts | Typed IDs/receipts, native state model and bounded ephemeral channel; deterministic cancel/order tests | sol_implementer |
| S-MESSAGING-03 | P3; S-MESSAGING-02, Storage durable batches | Durable queues, visibility generations, retries/DLQ and recovery; crash injection preserves acknowledged state | astra_implementer |
| S-MESSAGING-04 | P3; S-MESSAGING-03, RPC/Security gates | Remote publish/receive/ack and inbox/outbox examples; no blanket exactly-once assertion | sol_implementer |
| S-MESSAGING-05 | P4; S-MESSAGING-04, Replication single-group gate | Replicated queue adapter; leader change/lost replies preserve at-least-once and ack state | astra_implementer |
| S-MESSAGING-06 | P4; S-MESSAGING-05 | Partitioned queues/group operations and operational tooling; per-queue ordering explicit, no cross-shard atomic publish | astra_implementer |
CURRENT: no Messaging executable or test target exists. PROPOSED verification adds state
model enumeration, receipt race tests, crash/restart fault injection, poison/DLQ pressure,
slow consumers and minority partitions. Use [SQLite's crash-test methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior)
as a model for persistence faults, not a claim of SQLite compatibility. Future targets
and commands follow [VALIDATION](../VALIDATION.md) and
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Measure publish durable latency, receive-to-ack p50/p95/p99, redelivery lag, throughput,
allocations, peak RSS/CPU, retained disk and build cost under [PERFORMANCE](../PERFORMANCE.md).
Migration versions persisted receipt/state records and drains old consumers before changing
semantics. Export retains message IDs, groups, attempts and DLQ reasons. Rollback must keep
old format readers and receipt fencing; it cannot make previously delivered effects disappear.
See [MIGRATION](../MIGRATION.md), [Scheduler](Scheduler.md) and
[DistributedApplications](../platforms/DistributedApplications.md).
+166
View File
@@ -0,0 +1,166 @@
# Observability — optional hooks, bounded metrics and traces
Status: NEW subsystem design; all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`; there is no Observability module/source directory
or exporter at this revision. R-005/R-009/R-012 and [C-01–C-05/C-11](../ARCHITECTURE.md)
define the layering and lifetime obligations.
## Existing evidence and ownership boundary
[Log.hpp](../../../include/Void/Log/Log.hpp) provides a process-wide logging facade;
[Entry.hpp](../../../include/Void/Log/Entry.hpp) owns log record data, and
[FieldScope](../../../include/Void/Log/Field.hpp) provides thread-local structured fields.
These are useful integration points, not existing metrics/tracing context propagation.
[Logger.cpp](../../../src/Log/Logger.cpp) snapshots fields/scopes for async delivery.
[Log](../modules/Log.md) retains all delivery, sink, saturation and flush ownership.
Observability owns instrumentation identities, metric aggregation, trace/span context and
export adapters. Its lowest layer is a standard-library-only optional hook surface with no
Net, Runtime, Log or Async imports. Proposed NEW paths are `include/Void/Observability/Hooks.hpp`,
`include/Void/Observability/Context.hpp` and `src/Observability/`; proposed component separation
is hooks/context, aggregation, then optional exporters. [Dependencies](../DEPENDENCIES.md)
and [build/distribution](../BUILD-AND-DISTRIBUTION.md) own final packaging validation.
Higher modules may inject these hook objects. Foundation headers must still compile and
link without a telemetry backend or runtime. Async propagates an owning context carrier
through an optional adapter; it must not import a concrete tracer or exporter. Log's context
bridge lives above both modules so neither imports the other. Managed Runtime composes
resources; it never becomes a dependency of the hook definitions.
## NEW hook and context shape
Illustrative NEW interfaces in `Void::Observability`, not existing compilable APIs:
```cpp
struct TraceContext {
std::array<std::byte, 16> trace_id;
std::array<std::byte, 8> span_id;
std::uint8_t flags;
};
class ContextSnapshot; // immutable owning trace context + bounded baggage
struct MetricPoint; // pre-registered instrument id, bounded attributes, value
struct ObservationHooks {
void* state;
void (*record)(void*, const MetricPoint&) noexcept;
};
class HookLease; // retains callback owner until admitted calls drain
class Span; // move-only handle, one end transition
Result<Span> start_span(ContextSnapshot parent, SpanSpec);
Result<ExportReport> flush(ExportOptions);
```
The raw function table is a synchronous borrowing view: it never outlives its HookLease.
The configured context retains that lease, and detach has a distinct drain operation.
Hook callbacks must be nonblocking/noexcept; adapter boundaries catch foreign exceptions,
increment bounded failure counters and quarantine a broken callback. A null hook performs
no allocation or backend initialization. Registration is explicit, not done lazily per
user-supplied label value on a hot path.
Trace IDs are opaque values generated through the application's approved random/id source,
not from raw addresses. ContextSnapshot captures values at operation admission. A lexical
thread-local scope is a convenience view only: scheduled work owns a snapshot and restores
the previous context on entry/exit, including exceptions. A context scope cannot remain
installed on a worker across coroutine suspension. Async's resume adapter sets it for each
resume, or code passes the snapshot explicitly. Never retain a pointer to another thread's
TLS, request object or stack buffer.
Span has one terminal end; repeated end is harmless and counted diagnostically. A child
can finish after its parent because it owns IDs, not a parent Span pointer. Destroying an
unended local handle ends it with Abandoned unless ownership was explicitly moved. Remote
context is untrusted metadata: validate lengths/encoding, reject all-zero required IDs, cap
baggage, and never use it as an authorization identity. A protocol propagation adapter belongs
above Net/RPC; compliance with a named wire standard requires a later conformance task and
does not alter the lightweight in-process representation.
## Metrics, tracing and export algorithms
Instrument registration freezes name, unit, kind and label schema. The same name with a
different schema is an error. Counters are monotonic unsigned totals with checked/saturating
overflow plus a diagnostic flag; gauges are last-value samples with timestamp; histograms
use configured fixed bucket boundaries (default request-duration buckets from 100 µs
through 10 s plus overflow). No per-event dynamically expanding sketch is required initially.
Thread-local bounded shards aggregate updates; collection snapshots/swaps shards and merges
outside producer locks. A collector must retain shard ownership while a worker exits.
Use cumulative metric snapshots for the first exporter, so retrying export need not double
add a delta. Process/registry epochs distinguish restarts and reset counters. Instrument and
label IDs come from a bounded registry; never use request IDs, raw URLs, user names or keys
as metric labels. Route templates, fixed operation names and bounded error categories are
the selected defaults. Cardinality overflow records a dropped-series counter under one
pre-registered overflow series, not a newly labelled series per rejected value.
Tracing initially uses parent-based head sampling. Root sampling defaults to one in 100,
implemented from a stable trace-ID hash so descendants agree without a global lock. Export
only completed sampled spans; a separate bounded diagnostic event path may record failures
without retaining every unsampled request. Tail sampling is explicitly deferred to
S-OBSERVABILITY-06 because it changes memory/decision horizons. Span durations use Time's
steady clock; exported civil timestamps use a sampled civil/steady correspondence and do
not control deadlines.
Collector/exporter startup is explicit. Native aggregation and a local callback/text snapshot
exporter come first; an optional interoperable remote exporter is a later adapter over Net.
No external telemetry SDK is mandatory. An exporter owns immutable batches; transport retries
are bounded and may duplicate remote trace records, which have stable IDs. The subsystem
does not claim exactly-once delivery. Export failure must never recursively emit into the
same telemetry path; counters and a separate optional emergency diagnostic hook suffice.
## Concrete limits and shutdown
| Resource | NEW default / failure behavior |
| --- | --- |
| Registry | 256 instruments, 1,024 series/instrument, 4,096 series globally; reject excess registration/series with fixed counters. |
| Attributes | Eight metric labels, 32 span attributes, 128-byte keys, 256-byte values; reject invalid identity labels, truncate opted-in diagnostic text with a marker. |
| Context | 16 baggage items and 2 KiB total; immutable owned copy at admission; baggage is not automatically exported or logged. |
| Trace state | 1,024 active spans, 8 MiB active-span memory, 32 events/span and 8 KiB/span maximum; exhausted sampled admission returns an inert context-preserving handle with loss count. |
| Completed data | 8,192 spans and 16 MiB including active export batches; reject newest completed data on saturation with loss accounting. |
| Aggregation | 32 MiB total registry/shard/histogram storage; 32 registered producer shards, fallback to a shared bounded shard when exhausted. |
| Export | One active batch, 256 spans/512 KiB batch, two retries within five seconds; default metrics interval ten seconds, trace flush interval one second. |
Storage for default bucket counts is included in aggregation limits. All strings, queues,
callback-held batches and copied metadata count toward the appropriate byte budget, not
just record counts. Backend transport memory has its own Net budget; composition reports
the sum. Configuration cannot accidentally set zero to mean unlimited.
Admission stops first at shutdown; owned task contexts/spans drain with their tasks, then
final metric collection and export flush run before exporter/clock/executor destruction.
Default flush budget is five seconds. Timeout reports unsent/dropped counts and retains
resources for admitted backend activity until its completion; it does not free buffers under
an in-flight send. A failure to export does not roll back the business operation. Embedded
users drive collection/flush explicitly; no hidden background thread is created by a span.
## Implementation tasks
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-OBSERVABILITY-01 | P1; Memory/Time/Functional contracts | Freeze lightweight hook/context headers and no-backend consumer; null hooks allocate nothing and bring no Runtime/Net/Log dependency. | astra_implementer |
| S-OBSERVABILITY-02 | P2; S-OBSERVABILITY-01, Async admission ownership | HookLease, detach/drain, context snapshots/resume adapter and span lifetime; callbacks cannot touch freed owner/TLS after request completion. | astra_implementer |
| S-OBSERVABILITY-03 | P2; S-OBSERVABILITY-01/02 | Bounded metric registry, shards and histograms; cardinality storm stays within limits and overflow/reset totals are visible. | sol_implementer |
| S-OBSERVABILITY-04 | P2; S-OBSERVABILITY-02/03 | Head sampling, completed-span queue, callback/text exporter and flush; slow exporter cannot grow total memory or stall producers. | astra_implementer |
| S-OBSERVABILITY-05 | P3; S-OBSERVABILITY-04, Net/Runtime/Log adapters | Managed lifecycle, interoperable remote export and protocol context adapter; compliance fixtures and ownership tests pass without dependency cycles. | sol_implementer |
| S-OBSERVABILITY-06 | P3; S-OBSERVABILITY-05, measured profile | Optional bounded tail sampling with fixed trace/byte/time horizons; accept only with explicit eviction semantics and measured benefit. | astra_implementer |
| S-OBSERVABILITY-07 | P4; S-OBSERVABILITY-05, distributed platform contracts | Replica/term/commit lag instruments using bounded identities; telemetry outage cannot block majority commit or become an authority for leadership. | sol_implementer |
## Verification, performance and migration
CURRENT: no Observability tests exist. Adjacent Log snapshot tests cover only logging;
[validation](../VALIDATION.md) is the baseline evidence authority. PROPOSED after
S-OBSERVABILITY-01–04 creates/discovers tests:
`<configured-build>/tests/VoidTests --filter '^observability_'`. Test detached callback
drain, queued work after TLS destruction, coroutine migration, nested scope restore,
duplicate span end, zero/invalid remote IDs, clock discontinuity, exiting producer shards,
cardinality attack, slow/failing/reentrant exporter and timeout with in-flight buffers.
Use deterministic schedules and allocation counters, then supported sanitizers/stress.
Apply [performance](../PERFORMANCE.md)'s common samples/confidence/regression rules to
null hooks, unsampled spans, counter increments, histogram contention, collection and export.
Report p50/p95/p99, throughput, allocations, total peak/retained RSS/CPU and build cost,
with dropped observations and export failures included. No instrumentation overhead target
is asserted before measured baselines.
[Migration](../MIGRATION.md) first adds optional adapters; existing Log fields retain their
meaning and are not automatically converted into metric labels. New consumers explicitly
pass ContextSnapshot at admission. Telemetry configuration has schema versions and unknown
required fields fail validation; disabling exporters is a reversible operational rollback
that leaves null hooks safe. This is not a stable cross-toolchain C ABI until separately
versioned through C-09. Cited Log sources have graph coverage checks and direct inspection;
all metrics, trace/export behavior and conformance/performance results remain proposed.
+130
View File
@@ -0,0 +1,130 @@
# RPC subsystem plan — NEW
Status: NEW design only; all feature tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-009–R-016;
[architecture](../ARCHITECTURE.md) C-02–C-06, C-07, C-11–C-13.
## Starting point and package boundary
No current RPC source directory or target is claimed. Existing
[Net client](../../../include/Void/Net/Http.hpp) and
[router/session abstractions](../../../include/Void/Net/Server.hpp) are building blocks,
not RPC transport, dispatch or schema negotiation. Scoped coverage checks identify parse
gaps in these headers (Http 112/115, Server 207/211/214); those declarations were read
directly. New source roots `include/Void/RPC`, `src/RPC`, and `tests/standalone/RPC` are
PROPOSED and require implementation-time build ownership.
RPC depends downwards on [Net](../modules/Net.md), [IO](IO.md),
[Async](../modules/Async.md), [Data](../modules/Data.md) and [Binary](../modules/Binary.md).
It does not import Coordination, Discovery, Replication or platform hosts. Endpoint
selection is injected; a Discovery adapter belongs above RPC. Authentication hooks take
Security-owned immutable principals; no socket is a principal merely because TLS succeeded.
Choose native Void envelope/dispatch logic with HTTP/1.1 POST unary transport first;
WebSocket multiplexed streaming follows Net conformance. Initial backend is the selected
Net transport, with Boost/native parity inherited from Net. No gRPC compatibility claim
and no new protobuf dependency are implicit.
## NEW contracts and concrete wire design
```cpp
// NEW illustrative Void::RPC shapes; not currently available APIs.
struct MethodId { std::uint64_t service; std::uint32_t method; };
struct CallContext { RequestId id; PrincipalView principal; OperationOptions operation; };
class Client {
Task<Result<OwnedBytes>> call(MethodId, OwnedBytes, OperationOptions);
Task<Result<DuplexCall>> open_stream(MethodId, OperationOptions);
};
class Server {
Result<Registration> bind(MethodDescriptor, Handler);
Task<Result<void>> shutdown(OperationOptions);
};
```
Task/options are Async-owned; Result is C-02 shorthand. RPC owns MethodDescriptor,
request/correlation IDs, status mapping and call handles. Shared binary encoding and
schema primitives are referenced from Binary/Data, not reimplemented here. Registration
retains handler/provider ownership; destruction unregisters future admission and offers
an explicit drain operation for already admitted calls. Borrowed views expire on callback
return; handlers retaining data must take ownership.
Wire v1 is versioned length-delimited Binary encoding, explicit network byte order:
four-byte magic `VRPC`, u16 major/minor, u32 header length/total frame length, u8 frame
kind/flags, u16 reserved (zero), 128-bit call ID, u64 service ID, u32 method ID/schema
version/remaining timeout milliseconds, u16 metadata count and length-delimited metadata.
The total length includes the fixed header, metadata and payload; validate overflow and
minimum length before subtracting. Reserved flags and required unknown fields fail closed.
No native struct dump, pointer or std::string layout crosses the wire. Header ≤16 KiB,
64 metadata entries; payload ≤4 MiB/frame. Unknown major/required fields fail negotiation;
minor optional fields are length-skippable. Initial unary POST uses one envelope under
`/void-rpc/v1/call`, with an envelope response carrying domain status. Transport HTTP errors
and RPC domain errors remain distinguishable. Data owns schema compatibility rules;
numeric method IDs are explicit checked manifest assignments, not unstable reflection order.
Streaming uses WebSocket subprotocol `void.rpc.v1`: OPEN, DATA, CREDIT, HALF_CLOSE,
CANCEL and TERMINAL frames. One ordered sequence per direction/call; at most one terminal
frame, at most 128 calls/connection. Initial credit 256 KiB/direction; each acknowledged
consumed byte replenishes credit. Data frames ≤64 KiB; control frames have a separate
bounded 64 KiB reserve so saturated data cannot prevent CANCEL/TERMINAL. Half-close stops
that sender only. On disconnect every unfinished stream returns transport_lost; no hidden
resumption. Schema negotiation and method permission happen before handler admission.
Client dataflow: acquire budget → resolve injected endpoint → encode → Net send → decode
bounded envelope → terminal result. Server: bounded decode → protocol/schema validation →
authenticate/authorize → method admission → handler scope → encode result → release. User
handlers and hooks execute outside dispatch locks. Relative timeout travels across machines;
receivers create a local steady deadline, clamped to server max 30 seconds. Each forwarder
subtracts its elapsed time, never sends a steady-clock timestamp from another process.
Caller deadline includes connection/admission and all frames. Expiry cancels the server scope
but cannot undo an application commit. The peer may complete after the caller loses its reply.
## Bounds, retry and failure matrix
NEW defaults: 1,024 client calls, 256 executing server calls, 512 waiting, 64 MiB queued
payload budget, 8 MiB aggregate retained payload/call. Reject before parsing/allocating an
oversized frame. Metadata disallows secrets in tracing labels; trusted identity metadata
is authenticated by the transport/hook, never accepted from an arbitrary caller field.
Retries default off. A method may declare read-only/replay-safe, or require an explicit
application operation ID and durable dedup contract. A correlation call ID alone provides
no exactly-once processing. Stop propagation is best effort; client cancellation completes
only when local backend access ends. Graceful shutdown rejects new calls, drains for 10
seconds, cancels remaining scopes, joins then releases registrations and transports.
| Fault | Result / resource action | Required test |
| --- | --- | --- |
| Unknown method/schema/major version | Typed protocol status; no handler invocation | Mixed-version fixtures |
| Bad length / malformed metadata | Protocol error; close if frame boundary uncertain | Fuzz/truncated frame corpus |
| Handler error/exception | Mapped sanitized status; exactly one terminal result | Throws before/after suspension |
| Unauthorized request | Denied before method dispatch | Spoofed identity and role tests |
| Queue/credit exhaustion | Overload or explicit cancellable capacity wait | Slow stream consumer RSS bound |
| Deadline/cancel races with reply | One local outcome; remote commit may be unknown | Terminal-vs-cancel permutation tests |
| Lost reply after durable write | Unknown outcome; caller queries/retries by domain ID | Replication adapter fixture |
| Connection/provider shutdown | Stop/join owned scopes; no handler or buffer use after release | Unregister and reconnect races |
## Ordered work and acceptance
| ID | Phase / dependencies | Scope and evidence gate | Recommended role |
| --- | --- | --- | --- |
| S-RPC-01 | P0; baseline Net inventory | Record transport and schema prerequisites; independent package/dependency fixture plan | sol_implementer |
| S-RPC-02 | P1; Async/IO/Data/Binary contracts, S-RPC-01 | NEW envelope/status/schema manifest and deterministic codec; limits/fuzz/round-trip fixtures pass | astra_implementer |
| S-RPC-03 | P2; S-RPC-02, Net HTTP server/client gate | Unary transport and ownership-safe dispatch; deadlines/errors/authorization and consumer checks | sol_implementer |
| S-RPC-04 | P3; S-RPC-03, Net WebSocket gate | Streaming credit/half-close/cancel protocol; no memory growth under stalled consumers | astra_implementer |
| S-RPC-05 | P3; S-RPC-03, Security/Observability gates | Host adapters, bounded observations and version migration; embedded and managed modes pass | sol_implementer |
| S-RPC-06 | P4; S-RPC-05, Replication protocol fixtures | Consensus traffic adapter conformance, duplicate/reorder/lost-reply coverage; RPC remains independent of Coordination | astra_implementer |
## Validation and migration
CURRENT checks belong to the linked Net modules; no RPC tests or runner exist. PROPOSED
codec property/fuzz tests, loopback client/server tests, independent language byte fixtures,
handler-lifetime races, credit starvation and partition proxies precede implementation
acceptance. Register future targets before using command templates in
[VALIDATION](../VALIDATION.md) / [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Measure unary small/large payload, persistent connection and concurrent streams; report
p50/p95/p99, throughput, allocations, RSS/CPU and build cost via
[PERFORMANCE](../PERFORMANCE.md), including overload and cancellation latency.
Rollout negotiates envelope/schema before methods become ready. Support old+new major
listeners side by side during migration; never reinterpret frames after a failed decode.
Rollback stops new-major admission, drains calls and preserves old schema readers. Handler
side effects require domain-level forward/rollback policy. See [MIGRATION](../MIGRATION.md),
[Replication](Replication.md) and [NetworkedApplications](../platforms/NetworkedApplications.md).
+156
View File
@@ -0,0 +1,156 @@
# 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<Result<CommitReceipt>> submit(RequestIdentity, OwnedBytes command, OperationOptions);
Task<Result<ReadView>> read(ReadPolicy, OperationOptions);
Task<Result<RequestOutcome>> inspect(RequestIdentity, OperationOptions);
Task<Result<void>> shutdown(OperationOptions);
};
class StateMachine {
Result<ApplyBatch> 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).
+191
View File
@@ -0,0 +1,191 @@
# Runtime explicit managed composition plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Requirements R-005, R-009, R-010, R-012 and R-014 apply.
[Architecture](../ARCHITECTURE.md) C-01–C-05, C-09 and C-11 controls layering.
NEW proposed roots are `include/Void/Runtime`, `src/Runtime` and
`tests/standalone/Runtime`; no host or runtime is implemented in this planning package.
## Existing ingredients and boundary
There is no current managed Runtime module. Existing
[Async ThreadPool](../../../include/Void/Async/ThreadPool.hpp),
[EventBus](../../../include/Void/Async/EventBus.hpp), and
[System FileWatcher](../../../include/Void/System/FileWatcher.hpp) create their own
workers in their respective owning forms. [Fsm Engine](../../../include/Void/Fsm/Detail/Engine.hpp)
can own a worker or be pumped. [ServiceRegistry](../../../include/Void/Service/Registry.hpp)
has lifecycle callbacks but no managed execution composition. These source paths were
coverage-checked and key behavior read directly; FileWatcher's partial declaration
was directly inspected. Existing
[executor](../../../tests/standalone/Async/Executor.cpp),
[watcher](../../../tests/standalone/System/FileWatcher.cpp), and
[orchestrator](../../../tests/standalone/Service/Orchestrator.cpp) tests are integration
anchors, not Runtime tests.
Runtime depends on [Async](../modules/Async.md), [IO](IO.md), Time and Memory facilities.
Async/IO/Time/Memory never depend on Runtime. Optional adapters compose Service,
Configuration, Plugin, Scheduler, Log and Observability without making them mandatory
runtime dependencies for small consumers. Foundation constructors do not acquire
threads, sockets or a process-wide runtime. No singleton `Runtime::current()` fallback
is part of this design.
## NEW public shape and embedded composition
Illustrative, not available declarations:
```cpp
namespace Void::Runtime {
struct Options {
std::uint32_t cpu_workers;
std::uint32_t file_workers;
RuntimeLimits limits;
ShutdownPolicy shutdown;
};
class Host { // owns managed resources
public:
static Result<Host> create(Options); // validates, starts no workers
Result<void> start(); // explicit startup transaction
Async::Executor& executor();
IO::Driver& io();
Coro::Task<Result<ShutdownReport>> shutdown(Async::OperationOptions);
};
// NEW EmbeddedResources borrows executor, IO driver, Time clock and Memory budget.
}
```
Runtime Options are resource policy, not a duplicate operation context. Every cancellable
operation takes Async::OperationOptions. Time owns injected monotonic/civil clocks;
Memory owns allocation/budget contracts; Observability supplies optional lightweight
hooks. Runtime stores owners for managed resources and validated references for borrowed
ones, with no implicit lifetime extension of arbitrary external objects.
An embedded application constructs Async scopes and an IO driver directly, then passes
them to module factories. It may use NEW EmbeddedResources convenience views, but modules
consume their own low-level ports, not a mandatory Runtime header. A managed Host exposes
the same ports. A test host uses fake Time, ManualExecutor and a mock IO backend. Normal
constructors remain inert; start is explicit and errors return before publication.
## Startup algorithm
Use a lifecycle graph of explicit resources, with required/optional dependencies and
deterministic topological ordering. Default core order: validate limits/capabilities →
establish signal handling on the designated owner thread → allocate budgets and queues →
start CPU executor → start IO driver/file workers → start optional service/admission
adapters → report ready. SignalWatcher is created before worker threads as required by
[its contract](../../../include/Void/System/SignalWatcher.hpp), and is destroyed on
the same creating thread after workers join.
Each start step returns a retained cleanup action. A failed step aborts its partial
resources and unwinds previously successful starts in reverse dependency order.
Callbacks and service readiness checks execute outside lifecycle graph locks; a
serialized lifecycle strand prevents concurrent start/shutdown transactions. Start
is valid once per Host instance; retries after failure use a fresh Host after cleanup,
avoiding partially restarted resources. Host ready means all required admissions can
work, not merely that worker threads were created.
Configuration integration prepares a complete immutable resource/settings generation
before Host publication. A failed reload keeps current resources. Increasing pool
size can be prepared; shrinking retires workers after their admitted tasks drain.
Changes that cannot be staged reversibly require a controlled restart. Runtime never
applies half of a Configuration transaction.
## Shutdown and failure ownership
States: constructed → starting → running → stopping_admission → draining → joining →
stopped; failed_start and shutdown_incomplete retain cleanup ownership. Shutdown is
idempotent; callers join one retained result rather than issue competing stop paths.
1. Close external admissions/listeners/schedule admission and freeze new lifecycle
publication. Existing accepted calls retain their resources and generation pins.
2. Ask high-level applications/services to drain for a default 5-second grace within
the caller's total steady deadline. Observe dependency order: stop dependents first.
3. Request stop on remaining application/module work scopes and their timers,
subscriptions and queued IO. Shutdown-owned cleanup/export scopes are separate and
retain bounded internal admission. Continue driving IO/executor completions so
cancellation can finish; do not stop workers needed to join their children.
4. Join drained business scopes and their IO/plugin activities. Retain reactor, CPU/file
workers, clock, callbacks and provider generations needed by final cleanup/export.
5. Stop remaining telemetry producers, collect final metrics, then flush, close and join
observation/logging adapters in dependency order. A flush deadline reports unsent/lost
data and requests cooperative cancellation, but all admitted backend activity must
still quiesce. Expiry of the total shutdown budget returns shutdown_incomplete with
exporter owners and their execution resources retained; a later join continues them.
6. Only after cleanup/export callbacks and backend references retire, stop reactor and
CPU/file workers and release budgets/descriptors/signal masks in reverse creation
order. Observation failure cannot suppress cleanup or convert a failed operation
into success. A timed-out flush is not evidence that its resources are releasable.
Default total shutdown observation budget is 30 seconds, shortened by caller options.
Expiry produces `shutdown_incomplete` containing pending owner IDs/counts and phase;
the Host remains in joining with resources retained. It can be waited again or the
application can choose explicit process termination. There is no forced thread kill,
buffer release or dlclose. Borrowed resources must outlive final cleanup, not merely
the first timed-out shutdown call. Destruction blocks to join only on an allowed
off-worker owner thread; on a runtime worker, callers must await shutdown before
destroying Host. Self-join misuse is detected as a programmer error. Process-level
hard-stop policy belongs to the application, not a hidden destructor timeout.
Uncaught task exceptions reach explicit scope/error sinks. Default failure policy
requests stop for the owning component and marks it not-ready; it does not terminate
all unrelated components unless the host's declared critical-resource policy requires
that. Core driver failure closes admission and starts supervised shutdown. Error sinks
cannot recursively allocate unbounded work to report overload.
## Default accounting and backend rationale
Use native standard threads plus the selected IO epoll/file-worker backend. Default one
reactor, CPU workers = min(8, max(1, hardware_concurrency())), four file workers, 4,096
admitted CPU tasks, 8,192 IO operations, 256 queued file requests, 1,024 timers, 256
optional services and 256 MiB owned dynamic resource budget. Zero workers/limits are
invalid unless a documented embedded mode supplies the corresponding resource.
Global budget permits are shared by submodules: adding their local caps never creates
permission to exceed the host cap. Count running work, queued completions, prepared
reload generations and retained buffers. Thread stacks, kernel buffers and borrowed
memory are reported separately from allocator-controlled bytes; RSS is not falsely
claimed to be capped by the 256 MiB allocator budget. Reserve terminal/control capacity
when admitting work. Rejection is explicit; optional async waiting has bounded waiters
and uses the same stop/deadline. Native affinity/priority tuning is P3 opt-in after
measurements, not required for correctness.
## Ordered implementation backlog
Every row is PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-RUNTIME-01 | P1 / Async ownership, IO driver, Time/Memory ports | Inert Host options, borrowed/owned resource graph, dependency validation | No constructor starts workers; invalid bounds/cycles fail before external admission / sol_implementer |
| S-RUNTIME-02 | P2 / S-RUNTIME-01; System signal gate | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
| S-RUNTIME-03 | P2 / S-RUNTIME-02 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
| S-RUNTIME-04 | P3 / S-RUNTIME-03; Service/Configuration transaction gates | Optional managed adapters, transactional resize/reload and embedded examples | Same workload runs embedded/managed; failed resource prepare keeps active generation / sol_implementer |
| S-RUNTIME-05 | P3 / S-RUNTIME-04; profile harness | Latency/throughput/footprint presets, inspection and tuning gates | Limits remain invariant per preset; measured p99/RSS/build cost reported with environment / astra_implementer |
## Validation and migration
CURRENT aggregate source-regression command:
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here; no Runtime executable/target is present. PROPOSED tests require NEW
Host: start failure at each node, stop during startup, concurrent repeated shutdown,
task creating a child while admission closes, file syscall held past deadline, full
completion queue, borrowed driver teardown ordering, observer throw, signal arrival
during start, and held plugin pin at shutdown. Hold a remote export in flight while
business admission closes, expire its flush and total shutdown deadlines, and assert
shutdown_incomplete retains IO/workers/buffers. Release the backend, join again and
assert exporter destruction precedes executor teardown, with no new business admission.
Run tests with isolated process signals
and deterministic clocks; avoid real sleeps for lifecycle ordering assertions.
Measure start/ready/shutdown p50/p95/p99, task and IO throughput, allocations, retained
owners, peak RSS/CPU/thread count and build cost using [PERFORMANCE](../PERFORMANCE.md).
The managed preset is accepted only after embedded equivalence and no implicit-thread
consumer checks pass under [VALIDATION](../VALIDATION.md). No measurements ran here.
Migration is opt-in: existing thread-owning components keep versioned constructors;
new factories accept explicit ports. A future reference host in
[NetworkedApplications](../platforms/NetworkedApplications.md) or
[ReloadableApplications](../platforms/ReloadableApplications.md) calls create/start,
not a global bootstrap function. Rollback drains the managed host before restoring
legacy ownership; two owners must never drive the same executor/descriptor. See
[MIGRATION](../MIGRATION.md), [DEPENDENCIES](../DEPENDENCIES.md), and
[DELIVERY](../DELIVERY.md).
+181
View File
@@ -0,0 +1,181 @@
# Scheduler timers, calendar jobs and persistence plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
No current Scheduler source directory is part of this baseline. NEW proposed roots:
`include/Void/Scheduler`, `src/Scheduler`, `tests/standalone/Scheduler`.
Requirements R-009, R-011, R-014–R-016 apply. Follow
[architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-10 and C-12.
## Baseline and subsystem boundary
[Fsm Engine](../../../include/Void/Fsm/Detail/Engine.hpp) already has local timer IDs,
event-wait deadlines and a worker; [Engine.cpp](../../../src/Fsm/Engine.cpp) implements
them. [Async Executor](../../../include/Void/Async/Executor.hpp) provides manual
progress, while [Time Stopwatch](../../../include/Void/Time/Stopwatch.hpp) uses a
steady clock. None supplies durable jobs, calendar recurrence or persisted occurrence
acknowledgement. These paths were coverage-checked and relevant timer/executor source
read directly. [Fsm event](../../../tests/standalone/Fsm/Events.cpp) and
[executor](../../../tests/standalone/Async/Executor.cpp) fixtures are reuse anchors;
there is no existing Scheduler test target.
[Time](../modules/Time.md) owns injected clocks and civil/calendar conversions;
[Async](../modules/Async.md) owns timer-wait completion, scopes and OperationOptions;
[Scheduler](Scheduler.md) owns job definitions, occurrence admission and dispatch;
[Fsm](../modules/Fsm.md) owns workflow execution. Scheduler does not become Async's
timer backend dependency. In-memory scheduling is usable without Storage/Runtime;
durability is an explicit [Storage](Storage.md) adapter, with
[Sqlite](../modules/Sqlite.md) an independently specified optional implementation of
the same persistence port. It is never a hidden substitute for native Storage.
## NEW APIs and recurrence policies
Illustrative contracts, not delivered declarations:
```cpp
namespace Void::Scheduler {
struct OccurrenceId {
JobId job; std::uint64_t revision; std::uint64_t sequence;
};
enum class Misfire { skip, coalesce_latest, catch_up_bounded };
enum class Overlap { forbid, queue_one, allow_bounded };
struct JobSpec {
JobId id; std::uint64_t revision;
Schedule schedule; // once, fixed-delay/rate, calendar
HandlerId handler; std::vector<std::byte> payload;
Misfire misfire; Overlap overlap; RetryPolicy retry;
};
// add(spec, options) -> Task<Result<JobRevision>>;
// remove(job, options) -> Task<Result<void>>;
// handler(OccurrenceId, payload, Async::OperationOptions) -> Task<Result<void>>;
// close_and_join(options) -> Task<Result<ShutdownReport>>;
}
```
Async OperationOptions is the only operation cancellation/deadline type. JobSpec has
separate persistent scheduling/retry policy, not a persisted std::stop_token. Time's
injected clock drives a monotonic min-heap ordered by due time then occurrence sequence.
Callbacks run on the injected executor outside heap/store locks. A root scope owns
all dispatcher/handler children and their shutdown.
One-shot delay uses monotonic time in memory; durable one-shot stores an intended UTC
instant plus its occurrence sequence. Fixed-rate recurrence advances from intended
schedule time, not completion time; fixed-delay advances only after a completion record
commits. Civil schedules store a timezone ID, timezone-data version policy and intended
local slot, with Time resolving it to UTC. Default DST gap policy skips nonexistent
local slots; fold policy chooses the first occurrence only. Explicit twice-fold policy
includes the fold index in the persisted slot identity. Unknown zone or unavailable
required timezone data is a configuration error, never silent UTC fallback.
Initial calendar grammar is five fields (minute/hour/day/month/weekday) with explicit
lists/ranges/steps; day and weekday constraints both apply. This is a documented
cron-like grammar, not a claim of compatibility with every cron implementation.
Seconds, arbitrary scripts and natural-language schedules are later named extensions.
Default misfire coalesces to the latest due occurrence; catch_up_bounded admits at most
100 missed occurrences per job per recovery pass, preserving remaining cursor state.
Default overlap forbids concurrent execution for one job; queue_one retains the latest
pending slot. allow_bounded requires an explicit per-job concurrency cap.
## Durable state machine and at-least-once delivery
Initial persistent mode has one scheduler process owning the store namespace through
an exclusive local ownership lock. A second process fails startup; there is no implied
cross-host lease/election. Job envelopes contain format version, handler identity,
payload schema, revision and recurrence policy. Occurrence records contain ID, intended
slot/UTC time, pending/running/completed/dead status, attempt number, next retry instant
and bounded diagnostic category. Store adapter operations are atomic conditional batches.
1. In one durable batch, create due occurrence records with unique IDs and advance the
job's materialization cursor. Reserve occurrence capacity before moving the cursor.
OccurrenceId sequence is allocated in that transaction; retries retain the same ID.
A unique `(job, revision, civil-slot, fold)` index prevents duplicate materialization
after wall-clock rollback. ID is never generated from current wall time alone.
2. Atomically mark pending → running with attempt identity, then dispatch only after
that record is durably acknowledged. Queue saturation keeps it pending; it does not
falsely mark delivery complete. Handler admission options cover queue wait and run.
3. Handler success writes completed durably before releasing durable occurrence state.
Failure writes a retry/dead transition. Exponential backoff defaults 1 second to
5 minutes, multiplier 2, injected full-jitter RNG, maximum five attempts. Stop during
host shutdown preserves pending/running recovery intent and does not consume a retry
merely because the process is stopping.
4. After crash/restart, running records without a terminal acknowledgement return to
pending with the same OccurrenceId. The handler may already have applied its effect.
This is at-least-once execution, including successful effects whose acknowledgement
was lost. Expose `unknown_outcome` for failed/lost persistence acknowledgement and
inspect before automatic retry when the store outcome is unknown.
Exactly-once external effects are not promised. A handler passes OccurrenceId as an
idempotency key, or atomically commits its application mutation and dedup record in
the same Storage transaction/batch where supported. Network calls/email/process launches
need downstream idempotency or compensation. A scheduler completion record alone cannot
make those effects transactional. Storage mutation and scheduler applied state may share
a batch only through an explicitly supported common-store adapter, never by assuming
two unrelated databases commit atomically.
Editing a job increments revision; old running occurrences retain their handler/payload
snapshot and policy. Default update atomically records an old-revision invalidation
watermark with the new revision. This logically cancels unstarted old occurrences;
bounded background batches reclaim them without exceeding the 1 MiB batch cap. Claim
checks that watermark in the same conditional batch as pending → running, so an edit
cannot race a stale dispatch. Remove records a job tombstone, closes new admission,
requests stop for active handlers and optionally joins; a remove timeout does not claim
active effects were undone. Calendar timezone-data changes require explicit reschedule policy and keep
already materialized slot identities. Large wall-clock jumps trigger bounded rescan;
monotonic handler deadlines do not jump with the civil clock.
## Bounds, shutdown and backend decisions
Defaults: 10,000 job definitions, 100,000 retained occurrence records, 64 KiB payload,
16 MiB aggregate loaded payloads, 256 ready dispatches, 32 active handlers, one active
handler/job, 100 catch-up slots/job/pass, 64 retries processed/turn and 1 MiB durable
batch. Count running records against retention. Completed history retention is seven
days within the count cap; when pending/running state fills the cap, reject new jobs
and pause materialization without advancing cursors. Do not delete unacknowledged work.
Dead records require explicit operator acknowledgement/export before pruning by policy.
Heap entries are lightweight IDs; payloads load under a separate byte budget. Persist
next-due indices to avoid loading the entire store on each tick. Bound per-turn work
and yield to other Async tasks. Errors distinguish invalid rule, unsupported timezone,
overload, persistence failure, unknown outcome, handler failure and cancellation.
Observation hooks report lag, duplicate attempts, retry/dead counts and retention pressure
without labels per arbitrary job ID by default.
Shutdown stops materialization/dispatch, requests handler stop and joins the root scope
before closing persistence. A deadline produces incomplete shutdown with live owner IDs;
it never abandons frames or erases running records. Native heap/calendar composition is
selected over an external scheduling framework. Distributed dispatch is P4 only: a
Coordination/Replication adapter must provide committed ownership epochs/fencing and
deduplication; local lock semantics are not stretched into distributed correctness.
## Ordered implementation backlog
All rows are PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-SCHEDULER-01 | P1 / Async scopes/timers and Time clock gates | In-memory heap, one-shot/fixed schedules, explicit admission and joined handlers | Fake-clock tests prove ordering, overlap bounds and cancellation without sleeps / sol_implementer |
| S-SCHEDULER-02 | P2 / S-SCHEDULER-01; Time calendar gate | Calendar grammar, DST/misfire/catch-up and stable occurrence identities | Gap/fold/backward/forward clock cases yield documented slot IDs with bounded work / sol_implementer |
| S-SCHEDULER-03 | P2 / S-SCHEDULER-02; Storage durable conditional-batch gate | Persistence port, versioned records, exclusive ownership, recovery cursor and attempts | Crash at every acknowledgement boundary neither loses admitted occurrence nor claims exactly-once effects / astra_implementer |
| S-SCHEDULER-04 | P3 / S-SCHEDULER-03; Fsm checkpoint/Runtime gates | Workflow handler adapter, updates/removal, retention and operator inspection | Restart retries same ID; failed revision update leaves old policy intact; cap pauses without cursor loss / astra_implementer |
| S-SCHEDULER-05 | P4 / S-SCHEDULER-04; Coordination/Replication fencing gates | Separate distributed ownership/dispatch adapter | Partitioned former owner cannot commit current ownership work; duplicates remain explicitly deduplicated / astra_implementer |
## Validation, performance and migration
CURRENT aggregate regression command for reused modules:
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here. PROPOSED Scheduler checks need NEW targets and persistence fixtures:
crash after cursor/claim/effect/completion sync, lost success reply, corrupted record,
disk full, duplicate handler callback, delayed cancellation, full retention, job edit
during running attempt, DST fold/gap, timezone revision, wall-clock reversal, and
coalescing millions of missed slots under the per-pass cap. Use Time injection and
crash subprocesses; do not infer persistence from in-memory tests.
Measure dispatch-lag and durable-admission p50/p95/p99, jobs/second, recovery throughput,
allocations, peak RSS/CPU, store size and build cost under [PERFORMANCE](../PERFORMANCE.md).
No measurements ran here. There is no old Scheduler API to preserve; retain Fsm's
local timer adapters while adopting Async clocks. Persisted formats receive explicit
version readers and offline validate/upgrade tooling before incompatible changes.
Keep original store/checkpoint until upgraded validation succeeds; rollback after new
handler effects follows application idempotency/compensation, not record deletion.
See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
[DEPENDENCIES](../DEPENDENCIES.md) and [DELIVERY](../DELIVERY.md).
+304
View File
@@ -0,0 +1,304 @@
# Storage — original durable key-value engine
Status: NEW design; all implementation tasks below are PLANNED. Source baseline:
`main` at `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`. No Storage source directory,
format, target, or test runner exists at this baseline. R-007/R-008 and
[architecture C-02–C-05, C-08, C-12](../ARCHITECTURE.md) govern this plan.
## Boundary and selected implementation
Build an original engine with an append-only WAL, ordered memory index and immutable
sorted table files. SQLite remains the distinct [Sqlite integration](../modules/Sqlite.md).
There is no SQL parser, SQLite file compatibility, or database-server dependency here.
Native format/recovery code uses [Binary](../modules/Binary.md) field encoders; Storage
owns the framing, native CRC32C helper and checksum fixtures.
[IO](IO.md) supplies file and synchronization operations. Initial synchronous operations
also work without Runtime. Async adapters own their jobs and use Async's operation options;
they never perform blocking file work on an event-loop thread.
Adjacent existing persistence evidence is
[VersionStore](../../../src/Update/VersionStore.cpp), whose activation journal and durable
health marker are application-specific, and
[Sqlite.cpp](../../../src/Sqlite/Sqlite.cpp), which delegates transactions to SQLite.
Neither is an existing generic storage engine. New paths are PROPOSED:
`include/Void/Storage/`, `src/Storage/`, `tests/standalone/Storage/`; the NEW target is
`Void::Storage`. Replication ports belong above this engine, avoiding a Storage→Coordination
dependency. [Dependencies](../DEPENDENCIES.md) is the package-edge authority.
Initial deployment is one process holding an exclusive database-directory lock, with one
serialized writer and concurrent readers. Read-only access from another process is not
promised while the writer is open. Local filesystems with working file/directory sync and
atomic same-directory rename are required for durable mode; `Engine::open` returns
UnsupportedCapability without mutation when these are unavailable. A successful fsync
cannot compensate for a device that lies about flushes.
## NEW API sketch and consistency contract
Illustrative declarations, not compiling examples; `Result` is the C-02 shorthand.
Storage owns all domain types below. Operation options are owned by [Async](../modules/Async.md).
```cpp
namespace Void::Storage { // NEW
using Sequence = std::uint64_t;
enum class Durability { Sync, Buffered };
enum class Outcome { NotCommitted, Committed, Unknown };
struct Limits; // concrete defaults below
struct OpenOptions; // directory, durability, limits, allocator, IO ports
struct CommitReceipt { Sequence sequence; Durability durability; };
struct WriteFailure { StorageError cause; Outcome outcome; };
class Batch; // owning key/value bytes, puts, erases, preconditions
class Snapshot; // move-only pin of a committed sequence and source versions
class Cursor; // move-only ordered iterator retaining its Snapshot
class Engine {
public:
static Result<Engine> open(OpenOptions);
Result<Snapshot> snapshot();
std::expected<CommitReceipt, WriteFailure> write(Batch, Durability);
Result<OwnedValue> get(const Snapshot&, ByteView key) const;
Result<Cursor> scan(Snapshot, ScanBounds) const;
Result<void> checkpoint();
Result<void> sync();
Result<void> close();
};
}
```
`ByteView`, `OwnedValue`, `ScanBounds`, `StorageError`, and `Batch` are NEW Storage
interfaces, using standard byte spans/vectors and Binary encoding internally. Key order
is unsigned-byte lexicographic order, independent of locale. Empty keys and empty values
are distinct from absence. Erase writes a tombstone. A batch forbids duplicate mutation
keys, allows at most one precondition per key, and evaluates all conditions against the
latest committed state in writer order before any change. Conditions are absent,
version-equals, or exact-value-equals. Versions are sequence numbers, not value hashes;
delete/reinsert cannot pass an obsolete version check. Conflicts return NotCommitted.
One commit sequence covers the entire batch. Snapshot reads see the highest version no
greater than their captured sequence; no partial batch is ever observable. This is atomic
conditional batching, not arbitrary snapshot-isolated read/write transactions. A caller
that reads then writes must supply the read version as a precondition to prevent lost
updates. For an idempotent request, condition on absence of an application deduplication
key and write its result in the same batch as business mutations. The application owns
that key's retention; after eviction, replay safety is no longer implied. Replication uses
the same batch for application state, deduplication and applied-log position (C-12).
`get` returns an owning value; cursor output owns a bounded page. No public reference into
a mutable map or mapped file outlives its pin. Half-open scan bounds `[begin, end)` and a
prefix helper share the byte comparator. Each page has a last-key continuation within
the same snapshot, never a fresh snapshot per page. Closing a cursor releases its pin.
Snapshots are process-local and not serializable capabilities.
## Writer, visibility and failure state machine
1. Admit the entire batch by operation/byte budget. Own all input bytes; validate lengths
and conditions. Reserve memory for every index mutation and its version metadata before
emitting WAL bytes. Reject an exhausted sequence counter rather than wrapping it.
2. Under the writer strand, assign the next sequence, encode BEGIN, operations, COMMIT,
and append in order with short-write/EINTR handling. There is no interleaving between
batches in the initial engine. Cancellation before append returns NotCommitted.
3. In Sync mode, sync the WAL and all newly created recovery dependencies. Publish the
prepared index changes and committed sequence under a short visibility lock, with no
fallible allocation in this publication step. Only then acknowledge durable success.
Readers capture the sequence and source-version set under that same lock.
4. In Buffered mode, acknowledge after complete WAL append and index publication, clearly
indicating weaker durability. A later `sync()` establishes a durable prefix. A Sync
write also syncs all earlier buffered batches; later durable success must never depend
on an earlier unpersisted batch.
5. Any write/sync failure after append starts returns Unknown unless non-commit can be
proved. The engine enters RecoveryRequired, stops writes, and retains the last published
view for existing readers. Reopen/recovery decides which complete batches exist.
It must not retry the append, reuse the tentative sequence, or report rollback solely
because sync failed. Allocation failure before append is NotCommitted.
An async cancellation/deadline after append cannot revoke a commit. It returns the receipt
when the commit becomes known, or a WriteFailure with Unknown; exactly one result is delivered
after backend access ends. `close()` stops admission, joins admitted writes, syncs buffered
state when requested by policy, and reports outstanding pins as Busy. Snapshot/control-block
ownership keeps resources alive after an Engine handle is dropped; destructors cannot turn
an unreported sync failure into a durability guarantee. Embedded callers explicitly drive
maintenance; managed Runtime schedules it and joins it before releasing IO.
The async adapter follows Async's domain-result classification, not a first-stop-wins
replacement result. Conformance cases are explicit: stop before append → NotCommitted;
stop while sync is pending → retain the operation without delivering yet; sync succeeds
after stop → finish infallible index publication and return CommitReceipt; sync fails
after append → Unknown and RecoveryRequired unless non-commit can be proved. Stop and
deadline expiry cannot skip required publication after successful persistence or produce
a second notification when the backend later retires.
## V1 WAL format and recovery protocol
This is a selected NEW format specification to implement and freeze with golden fixtures,
not a claim that files already exist. All integers are little-endian with checked unsigned
length arithmetic. No raw C++ structs, host padding, native pointers, or native `size_t` are
written. Storage's CRC32C uses polynomial `0x1EDC6F41` (reflected `0x82F63B78`), reflected
input/output, initial register `0xFFFFFFFF`, final xor `0xFFFFFFFF`, and little-endian
checksum storage. The golden ASCII `123456789` check is `0xE3069283`; these parameters
are independently documented in [Cyphal specification appendix A.2](https://specification.opencyphal.org/Cyphal_Specification.pdf).
Storage owns those tests, including empty input, incremental updates and full-record
fixtures. CRC detects accidental corruption and is not authentication. Header CRC covers
the bytes preceding its own field (60 segment-header bytes or 32 record-header bytes).
| Structure | Required fields and validation |
| --- | --- |
| Segment header | 8-byte magic `VOIDWAL1`, major/minor u16, header size u32, database UUID 16 bytes, segment id u64, previous segment id u64, first candidate sequence u64, flags u32, header CRC32C u32. V1 header size is 64 bytes. Reject opening unknown required flags or major versions without mutation. |
| Record header | Magic u32, total record length u32, type u16, record version u16, flags u32, batch sequence u64, ordinal u32, payload length u32, header CRC32C u32. Header size 36 bytes; validate header CRC before trusting any allocation length. |
| Record trailer | CRC32C u32 over the complete header and payload, then repeated total length u32. Length includes the 36-byte header and 8-byte trailer; padding is not used. |
| BEGIN payload | operation count u32, total operation-payload bytes u64; these are bounded by admission limits. Ordinal zero. |
| PUT/ERASE payload | key length u32, value length u32, then raw bytes; ERASE requires value length zero. Ordinals 1 through operation count. Preconditions are evaluated before logging and are not re-evaluated during redo. |
| COMMIT payload | operation count u32, total operation-payload bytes u64, aggregate CRC32C u32 over the ordered BEGIN and operation records including their trailers. Ordinal count+1, same sequence. |
The writer never splits a batch across segments; rotate first if it would exceed the
64 MiB segment target. A maximum-sized batch fits in one segment. Register and durably
publish the new segment in the manifest before accepting writes to it. This avoids a
durable receipt whose only WAL is an undiscoverable orphan. Do not preallocate logical
EOF with indistinguishable zero records in V1.
Recovery obtains the exclusive lock, validates CURRENT and its manifest, then table metadata,
then manifest-listed segments in id order. Database UUIDs, segment chain, record ordinals,
sequences, sizes and checksums must agree. Buffer one bounded batch while scanning; apply
only after a matching COMMIT and only above the manifest's checkpoint sequence. Reject
sequence gaps/duplicates among batches that need redo. COMMIT presence establishes recovery
visibility, even if the caller never received an acknowledgement.
Only an incomplete header/body at physical EOF of the final active segment, or a valid
BEGIN/operation suffix without COMMIT, is treated as an uncommitted tail. Preserve diagnostic
offsets, truncate that tail to the last complete batch, and sync before resuming writes.
A complete record with a bad checksum, malformed length, unexpected type or broken sequence
is Corruption, including at EOF: a fully sized torn write cannot reliably be distinguished
from later media damage. Fail closed and require explicit offline salvage into a different
directory; never skip damaged bytes and continue. Earlier/closed segments permit no tail
exception. Recovery interruption is safe because redo is deterministic and only tail
truncation mutates the old WAL. Test crash during that truncation and its sync.
## Checkpoints, manifest and compaction
Minimal CURRENT/manifest handling belongs to P1 alongside WAL recovery, before any durable
receipt is possible. Under the exclusive directory lock, initial creation persists the
database identity and first segment header, writes/syncs a manifest with no tables and
checkpoint sequence zero, then publishes/syncs CURRENT and the containing directory.
Only then may write admission open. Segment rotation reuses that publication protocol to
register the new segment while retaining every older segment needed for recovery; no
batch enters it before publication is durable. A crash before a valid CURRENT exists
cannot have an acknowledged batch and normal open reports incomplete initialization;
it never adopts the highest orphan manifest. Fault tests cover each creation and rotation
boundary. P2 extends this already working protocol with tables/checkpoint generations.
P1 keeps an ordered `std::map` of keys with version chains, guarded by short read/write
index locks. Reads copy data under a lock; cursors seek afresh by last key, so no tree
iterator survives mutation. P2 freezes a memtable at sequence S and starts a new mutable
one. A snapshot pins the active/frozen sources and table version set; publication replaces
sources without invalidating existing pins. This selected simple index provides a reference
before a future native tree optimization is justified by profiles.
NEW table files contain a versioned header/UUID/table id, sorted blocks of
`(key, descending sequence, put-or-tombstone, value)`, a sparse key/offset index, and a
checksummed footer naming every block, range and sequence interval. Default blocks target
32 KiB; a record larger than that occupies a dedicated bounded block. The maximum physical
block is bounded by the 4 MiB value limit plus key/header overhead. Index offsets and key
ordering are validated; each read verifies block CRC. The whole-file digest/checksum in
the manifest protects identity and metadata, while lazy block verification bounds open cost.
The offline verifier reads every block. V1 uses no compression or mmap requirement.
Manifest generations are immutable, checksummed files listing table ids, lengths, key/sequence
ranges, replay segments, checkpoint sequence, comparator identity and minimum reader/writer
format versions. CURRENT contains a generation name, generation number, database UUID and
checksum. Publication ordering is mandatory:
1. Write table temporary files in the database directory; finish checksums; sync each file.
2. Rename each to its unique immutable final name; sync the containing directory.
3. Write and sync a new manifest temporary file, rename it, and sync the directory.
4. Write and sync CURRENT.tmp, atomically rename it to CURRENT, then sync the directory.
5. Publish the new in-memory source set. Only now can old WAL/table files become retirement
candidates. Remove them only after all pins release, and sync directory deletions.
A crash before CURRENT publication leaves the old manifest authoritative and new files
orphaned; after it, every named dependency is already durable. Unknown CURRENT publication
outcome stops maintenance and requires recovery, without deleting either generation's inputs.
Do not select the highest manifest filename on recovery: it may be an uncommitted candidate.
A missing/corrupt CURRENT or referenced file is Corruption, not permission to discard newer
acknowledged data. Offline repair is separately authorized and writes a new destination.
Initial checkpoint produces a complete table view through S; all WAL through S is removable
only after that view is durably selected. Incremental compaction in P2 merges at most four
overlapping immutable runs per job using a min-heap ordered by key/version, with one output
file open at a time and 64 MiB target outputs. Keep all versions newer than the oldest live
snapshot and the newest at/below it. A tombstone may be discarded only when every older
overlapping run is included and no pinned reader needs it. Old pinned source sets stay
readable even after a replacement manifest is durable. Compaction never mutates input files.
Cancellation between blocks discards unreferenced temporary outputs; after manifest selection
it completes bookkeeping rather than undoing publication.
## Defaults and performance gates
| Budget | Initial default and exhaustion behavior |
| --- | --- |
| Key/value/batch | 4 KiB key, 4 MiB value, 16 MiB encoded batch, 1,024 mutations and 1,024 conditions; reject before WAL. |
| Pending writes | 64 admitted batches and 64 MiB total including active writer input/encoded copies; nonblocking overload by default. |
| Memtables | 64 MiB active target, 256 MiB total live index/version budget including frozen and pinned memory; reserve at admission, pause writes when maintenance cannot reclaim. |
| Read resources | 128 snapshots, 128 cursors, 1 MiB normal scan page/1,024 rows; a larger single value is reported as PageTooSmall unless caller opts into a page up to 8 MiB. |
| Retention/cache | 1 GiB obsolete pinned-file budget, 32 MiB block cache, 16 MiB compaction workspace; count actual bytes and allocator overhead. Never invalidate live snapshots to meet a budget. |
| Disk | 4 GiB WAL hard cap, at most 32 active runs, compaction output reserve checked before work; backpressure writes if pins or disk space prevent progress. |
| Maintenance | One compactor; 8 MiB work slices, check stop/deadline between blocks; 64 MiB/s optional default managed rate limit, injectable clock. |
Limits are configurable finite values; zero is invalid unless a field explicitly permits
zero. Persistent data size itself is governed by a configured volume quota and free-space
reserve. Bound manifest/table-index metadata too: 64 MiB per manifest, 65,536 table entries;
larger databases require a later format/capability gate, not unbounded open allocations.
Long-lived snapshots can stall write admission; expose oldest pin age, retained bytes and
compaction debt through optional [Observability](Observability.md) hooks.
[Performance](../PERFORMANCE.md) profiles compare point reads, mixed read/write, sequential
scan, hot-key churn, large values, and slow-reader compaction. Measure Sync and Buffered
separately: p50/p95/p99 including admission and sync, throughput, write amplification,
allocations, peak RSS/CPU, disk use, recovery time and build cost. Do not claim a speedup
or durability from an in-memory benchmark. A native index replacement is gated on measured
benefit with identical format/consistency tests, not part of the initial core.
## Ordered implementation backlog
All rows are PLANNED; phases follow [delivery](../DELIVERY.md). External dependencies name
capabilities owned by their area plans rather than inventing their task identifiers.
| ID | Phase / dependencies | Implementation scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-STORAGE-01 | P0; Binary encoding, IO durability contracts | Freeze format fixtures, invariants and fault-injectable file port; reject overflow/unknown versions and show exact crash points. | astra_implementer |
| S-STORAGE-02 | P1; S-STORAGE-01, Functional errors, Memory bounds | Implement single writer, byte comparator, conditional batches and pinned in-memory snapshots; model tests prove atomicity, conflicts and ordered scans. | astra_implementer |
| S-STORAGE-03 | P1; S-STORAGE-02 | Directory lock, minimal CURRENT/manifest bootstrap and durable WAL-segment registration, append/sync/recovery; crash initial creation and rotation, preserve every acknowledged Sync batch, reject partial batches and expose Unknown after failed sync. | astra_implementer |
| S-STORAGE-04 | P2; S-STORAGE-03 | Extend the existing manifest protocol with immutable tables/checkpoints; crash every table/checkpoint publication step and recover the selected generation without lost committed data. | astra_implementer |
| S-STORAGE-05 | P2; S-STORAGE-04 | Bounded incremental compaction, retention, scans and quotas; a pinned snapshot survives replacements and stalls safely under budget pressure. | astra_implementer |
| S-STORAGE-06 | P3; S-STORAGE-05, Async/Runtime ownership | Async adapters, backup pin/export, verify/restore tools, diagnostics and benchmark profiles; tools cannot mutate a live directory without its lock. | sol_implementer |
| S-STORAGE-07 | P3; S-STORAGE-06, Data schema evolution | Optional document and secondary-index layer; update document/index keys atomically, rebuild into a new namespace, define optimistic conflict semantics explicitly. | astra_implementer |
| S-STORAGE-08 | P4; S-STORAGE-06, Replication contracts | Atomic application/dedup/applied-position adapter and versioned snapshot export; restart never re-applies a committed external side effect by implication. | astra_implementer |
## Validation, migration and rollback
CURRENT: no Storage tests or target exist. Existing baseline commands and their known
environmental failures are in [validation](../VALIDATION.md); they are not Storage evidence.
PROPOSED, after S-STORAGE-03 adds/discovers `storage_` tests in the normal test build:
`<configured-build>/tests/VoidTests --filter '^storage_'`. Angle-bracket paths are command
templates. S-STORAGE-03 and subsequent durability tasks require an isolated filesystem
fault harness and subprocess crash runner, including initial CURRENT creation and WAL
rotation; do not substitute clean shutdown tests for power-loss simulation.
Required tests enumerate every short write, failed fsync, rename and directory sync; truncate
every WAL byte offset; corrupt each header/record/table/manifest field; reorder or discard
unsynced writes; interrupt recovery; repeat recovery twice. Model checking compares all
committed batches and snapshots against an ordered reference map. Include delete/reinsert,
precondition races, empty values, binary keys, sequence exhaustion, cross-page scan stability,
retention pressure and disk-full compaction. SQLite's
[crash-test methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior)
motivates the injected-filesystem campaign; it does not validate this new engine.
Format major versions reject incompatible writers/readers. Additive minor features require
feature bits and explicit capability negotiation; never reinterpret old bytes. Upgrades use
read-old/write-new export into another directory, verify counts/checksums and a consistent
snapshot, then perform an operator-controlled directory selection with old data retained.
Backups pin a manifest, tables and necessary WAL prefix until their copy is complete and
verified; copying only tables from a changing directory is not a backup. Rollback selects
the verified old directory only before accepting new writes, or requires explicit data
reconciliation afterward. [Migration](../MIGRATION.md) owns release policy; richer isolation,
encryption-at-rest and multi-process writers require separate named capability gates.
Evidence: graph coverage was checked for the cited adjacent implementation files and their
source inspected. New Storage behavior is entirely proposed; no build, crash test, benchmark
or production durability result is claimed by this document.
+156
View File
@@ -0,0 +1,156 @@
# NEW Unicode subsystem
Status: NEW design; no Unicode source directory/target is claimed to exist. All tasks
are **PLANNED**. Baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected
2026-11-24. Selected initial data version: **Unicode 17.0.0**, intentionally pinned,
not a promise to track a moving latest release.
## Existing behavior and why a separate owner is needed
[Text Str](../../../include/Void/Text/Str.hpp) provides byte-oriented trimming/casing;
[Html](../../../include/Void/Text/Html.hpp) appends UTF-8 for entity values. General
[Json](../../../include/Void/Data/Json.hpp) and restricted
[StrictJson](../../../include/Void/Data/StrictJson.hpp) each handle string escapes.
These are local capabilities, not a current complete Unicode normalization, property,
segmentation or error-policy contract. [Text encoding tests](../../../tests/standalone/Text/Encoding.cpp)
and [StrictJson tests](../../../tests/standalone/Data/StrictJson.cpp) are compatibility
inputs. Graph coverage marked Json lines 243/1090 partial; the flagged ranges and relevant
string handling were read directly. No existing parser is replaced merely by introducing
this subsystem.
## Dependency and backend choice
Under [C-01/C-07](../ARCHITECTURE.md), choose **Unicode→Text**, with Text staying byte/ASCII
only. The optional integration header belongs to Unicode; Text never includes Unicode.
Unicode may use Core traits and standard PMR resources; no locale engine, ICU, Runtime,
network access, dynamic data download or hidden worker is required. Data may explicitly
use a Unicode validation adapter, but signed StrictJson acceptance remains frozen until
its owner separately approves any security change. Normalization is never an automatic
step in signature verification, URL decoding, filesystem authorization or key equality.
Use native UTF scanners and generated immutable lookup tables. Pin upstream input URLs,
version, license notices and SHA-256 hashes in a NEW reviewed data manifest; actual hashes
are obtained from downloaded files during implementation, not invented in this plan.
Check reviewed compact generated tables into source so ordinary builds need no Python
or download. A separately invoked deterministic generator reproduces them byte-for-byte.
The [17.0.0 UCD directory](https://www.unicode.org/Public/17.0.0/ucd/ReadMe.txt) identifies
the final versioned data. Unicode upgrades are explicit behavioral migrations.
NEW proposed paths: `include/Void/Unicode/Utf.hpp`, `Normalize.hpp`, `Segment.hpp`,
`Properties.hpp`, `TextAdapters.hpp`, `src/Unicode/module.cmake`,
`src/Unicode/generated/`, `tools/unicode/` and `tests/standalone/Unicode/`. Generator,
manifest and generated sources require exclusive ownership in their future task; this
document does not authorize parallel workers to regenerate shared files.
## NEW UTF API and exact error policy
Illustrative proposed declarations, not existing compiling examples:
```cpp
namespace Void::Unicode {
enum class UtfPolicy { reject, replace_one_unit };
enum class UtfErrorKind { invalid_lead, invalid_continuation, overlong,
surrogate, out_of_range, incomplete, limit,
cancelled, allocation_failed };
struct UtfError { UtfErrorKind kind; std::size_t offset; };
struct Scalar { char32_t value; std::size_t begin, end; };
struct UtfLimits {
std::size_t max_input_bytes = 16 * 1024 * 1024;
std::size_t max_output_bytes = 16 * 1024 * 1024;
std::size_t max_scalars = 4194304;
};
std::expected<std::vector<Scalar>, UtfError>
decode_utf8(std::string_view, UtfPolicy = UtfPolicy::reject, UtfLimits = {});
std::expected<std::u16string, UtfError>
to_utf16(std::string_view, UtfPolicy = UtfPolicy::reject, UtfLimits = {});
std::string_view data_version() noexcept; // "17.0.0"
}
```
Default reject fails at the first invalid unit, reports the byte offset for UTF-8 or
code-unit offset for UTF-16, and publishes no partial owning result. Reject overlong
encodings, isolated continuation bytes, encoded surrogate values, values above U+10FFFF
and truncated tails. UTF-16 accepts paired surrogates only. UTF-32 accepts scalar values
only. Noncharacters are valid scalar values unless a separate application policy rejects
them; U+0000 is valid data and never an implicit terminator.
`replace_one_unit` is deliberately named: on malformed UTF-8 consume one byte and emit
U+FFFD; on malformed UTF-16 consume one code unit. Retry the next unit independently.
Thus an invalid multi-byte sequence can emit multiple replacements. This is an explicit
repair profile, not an unstated maximal-subpart claim. In streaming mode incomplete tails
are retained until finalization, not repaired at each chunk boundary. A valid BOM is
decoded as U+FEFF; stripping it is a separate option at document boundaries. Endianness
for UTF-16 bytes is explicit in Binary's adapter, not inferred from host representation.
Provide an allocation-free scalar iterator/view with the same policy and error offset,
plus into-span transcoding returning consumed/produced counts. Views borrow input and
must not outlive it. Stateful decoders retain at most three UTF-8 bytes or one UTF-16 high
surrogate. Defaults cap input/output at 16 MiB and scalar output at 4,194,304; expansion
checks precede reserve. Callers may supply stricter caps. Optional stop checks occur at
least every 4 KiB; already delivered iterator/callback values remain observed on stop.
## Normalization, casing and segmentation
Implement NFD/NFC first, then NFKD/NFKC with the same tables. Decompose recursively via
an explicit bounded stack, reorder by canonical combining class stably, and compose with
the versioned composition exclusions and Hangul rules. These forms and their conformance
tests are specified by [UAX #15 revision 57](https://www.unicode.org/reports/tr15/tr15-57.html).
Do not assume concatenating two normalized chunks is already normalized. The streaming
normalizer retains the uncommitted combining sequence and only emits stable prefixes.
Initial combining-sequence cap is 1,024 scalars; overflow returns `limit`, never inserts
new characters or truncates silently. Input/output and scratch defaults are 16 MiB/16 MiB/
4 MiB, with cumulative charging across stages.
Properties expose general category, combining class, whitespace and simple casing as
table queries. Full default case folding and root-locale casing use explicit APIs; full
casing may expand output. Context-sensitive rules follow the pinned data; Turkish/Azeri
tailoring is an explicit locale option, never inferred from the process locale. Casefold
and normalization are distinct operations. Search-key helpers must name the exact pipeline
(for example NFKC then casefold then NFC) and carry a version/policy identifier for
persisted indexes. Unicode alone is not a spoofing or authentication defense.
Segmentation starts with extended grapheme boundaries, then default word/sentence
boundaries from [UAX #29 revision 47](https://www.unicode.org/reports/tr29/tr29-47.html).
Emit byte ranges into the original validated UTF-8; no copied strings by default. Grapheme
boundaries are not terminal column width. Segmentation state handles regional indicators,
combining marks and emoji ZWJ sequences across chunks. Defaults cap one retained cluster
at 1,024 scalars and boundary output at 1,048,576 entries; return `limit` on excess.
Locale word dictionaries, collation and IDNA are deferred behind separate named capability
gates, not silently approximated by the first subsystem.
## Ordered implementation tasks
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-UNICODE-01 | P0; upstream versioned UCD and current Text/Data fixtures | Record exact data inputs, license, hashes and generated-file ownership; reproducible generation works offline from reviewed inputs. | astra_implementer |
| S-UNICODE-02 | P1; S-UNICODE-01 | Add strict/one-unit-repair UTF scanners and span transcoders; every malformed sequence and chunk split matches the documented policy and offsets. | sol_implementer |
| S-UNICODE-03 | P2; S-UNICODE-01–02 | Add immutable properties and default/full casing; pinned case-fold/special-casing vectors and expansion limits pass. | sol_implementer |
| S-UNICODE-04 | P2; S-UNICODE-03 | Implement normalization and streaming stable-prefix behavior; full pinned NormalizationTest corpus passes and long combining sequences fail boundedly. | astra_implementer |
| S-UNICODE-05 | P2; S-UNICODE-03–04 | Implement grapheme then word/sentence boundaries; pinned break-test corpora and cross-chunk emoji/RI cases pass. | sol_implementer |
| S-UNICODE-06 | P3; S-UNICODE-02–05; Text/Data adapter gates | Ship explicit adapters, versioned search-key example and installed consumers; Text-only linkage excludes tables and StrictJson fixtures remain unchanged. | sol_implementer |
## Validation, version changes and rollback
CURRENT evidence covers only existing Text/Data source/tests. No Unicode conformance,
generator, sanitizer or benchmark was run. PROPOSED suites include exhaustive scalar
encode/decode round trips, independent invalid UTF vectors, all split boundaries,
NormalizationTest, GraphemeBreakTest, WordBreakTest and SentenceBreakTest from the pinned
version. Round trips alone cannot prove rejection rules. Reproduction checks compare
generated bytes twice in clean temporary directories and verify the reviewed manifest.
Fuzz chunking, output exhaustion and stop paths; preserve the original input on owning
operation failure. An optional external engine can be a development oracle only after
dependency approval and matching its Unicode version; it is not the shipped backend.
Measure ASCII/mixed-script/combining-heavy throughput and latency, table text/rodata size,
allocations, peak RSS/CPU and build cost under [PERFORMANCE](../PERFORMANCE.md), including
p50/p95/p99. Bound rejection work separately from normal text and report table-version
changes; do not promise smaller/faster than external engines without measurement.
[Migration](../MIGRATION.md) adds Unicode opt-in without changing Text byte semantics.
An upgrade records changed properties/boundaries, re-runs all corpora and builds old/new
persisted search-key indexes side by side. Retain original text and the old policy ID
until cutover is verified. Rollback selects the old tables/index; merely downgrading the
binary cannot recover overwritten keys. No signed payload is normalized during migration.
See [VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
[Text](../modules/Text.md), [Data](../modules/Data.md) and [Binary](../modules/Binary.md).