docs: add expansion roadmap and workflow baseline
This commit is contained in:
1 parent
f1f9ba375b
commit
faa8a5198d
65 files changed
+9292
No files matched your search
@@ -0,0 +1,150 @@
|
||||
# Archive — safe streaming and atomic publication
|
||||
|
||||
Status: plan; all implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
R-003/R-006/R-014/R-015 and [C-02–C-07](../ARCHITECTURE.md) apply.
|
||||
|
||||
## Existing extraction contract
|
||||
|
||||
[Archive.hpp](../../../include/Void/Archive/Archive.hpp) exposes
|
||||
`Void::Archive::extract(path, destination, ExtractionOptions)` returning an ExtractionResult.
|
||||
Defaults are 10,000 entries, 512 MiB per file, 2 GiB total and no overwrite.
|
||||
[Archive.cpp](../../../src/Archive/Archive.cpp) enables tar plus none/zstd filters through
|
||||
libarchive, rejects absolute/non-normal/traversal/backslash paths, duplicates, links and
|
||||
special entries, and checks declared and actual extracted bytes. POSIX extraction pins the
|
||||
destination directory, walks parents with descriptor-relative no-follow operations, writes
|
||||
temporary regular files, syncs them and publishes them. Windows has a different path-based
|
||||
implementation; identical race resistance is not established by the Unix source.
|
||||
|
||||
[module.cmake](../../../src/Archive/module.cmake) links Functional and LibArchive::LibArchive.
|
||||
[Tests](../../../tests/standalone/Archive/Archive.cpp) include bounded tar.zstd extraction,
|
||||
explicit directories, traversal/links, symlink parents, destination path swapping and actual
|
||||
size limits. These are regression obligations. A failed whole extraction can still leave
|
||||
earlier successfully published entries: the existing per-file workflow is not an atomic
|
||||
replacement of an entire directory tree.
|
||||
|
||||
## Backend and API completion
|
||||
|
||||
Retain libarchive as the initial tar/zstd decoder and later encoder. Void owns path policy,
|
||||
resource admission, stream adapters and publication transactions. Native directory safety
|
||||
logic is preferable to shelling out; a new tar or zstd implementation would add compatibility
|
||||
and security risk without a measured requirement. Other formats require an explicit tested
|
||||
profile; enabling every decoder by default is not part of completion.
|
||||
|
||||
NEW illustrative surface in the existing namespace; shared operation options come from
|
||||
[Async](Async.md), byte streams from [IO](../subsystems/IO.md):
|
||||
|
||||
```cpp
|
||||
struct EntryInfo; // owned normalized path, type, declared size, safe mode
|
||||
struct ReadLimits; // policy defaults below
|
||||
class Reader; // caller-driven next_entry/read_chunk/skip_entry
|
||||
class StagedTree; // owns unpublished directory and cleanup obligation
|
||||
Result<Reader> open_reader(InputStream&, ReadLimits);
|
||||
Result<StagedTree> extract_staged(InputStream&, DirectoryHandle, ExtractionOptions);
|
||||
Result<PublicationReceipt> publish(StagedTree, std::string_view new_child_name);
|
||||
Result<void> create_archive(OutputStream&, EntrySource&, CreationOptions);
|
||||
```
|
||||
|
||||
All types except existing ExtractionOptions are NEW Archive or IO-owned interfaces as
|
||||
indicated; this sketch is not a compiling example. Input/output streams are borrowed through
|
||||
completion, or moved into an owning async operation. EntryInfo never points into libarchive's
|
||||
next-header scratch buffer. Reader has one active entry; callers drain or explicitly skip it
|
||||
before advancing. Skipping still accounts for decompressed work and limits, not just stored
|
||||
bytes. The reader never materializes a complete archive by default.
|
||||
|
||||
Listing is a bounded metadata traversal and carries the same path/entry-count validation.
|
||||
An opt-in forensic listing may report rejected metadata without writing anything, but is
|
||||
not a way to authorize extraction of unsafe entries. Archive creation accepts regular files
|
||||
and directories only, sorts normalized paths, rejects duplicates, and uses reproducible
|
||||
timestamps/owners/modes when requested. It does not follow links while enumerating sources.
|
||||
|
||||
## Atomic extraction workflow
|
||||
|
||||
`extract_staged` creates an exclusive private child beneath a caller-owned parent directory,
|
||||
pins its descriptor, then extracts all content there. Default output permissions are 0644
|
||||
files and 0755 directories, retaining only the explicitly allowed executable bit policy;
|
||||
ignore ownership, setuid/setgid, device metadata and extended attributes. File paths have a
|
||||
4 KiB encoded limit, 255-byte component limit and 64 components. Reject conflicts where
|
||||
a file is required to be a parent directory, including case-collisions on a backend that
|
||||
cannot distinguish them. Do not repair malicious paths by normalizing them into acceptance.
|
||||
|
||||
On success, close/sync every file, sync created directories bottom-up, write a bounded
|
||||
completion inventory, sync the staging root, and return StagedTree. Publication creates a
|
||||
previously absent immediate child name by a no-replace directory rename on the same filesystem,
|
||||
then syncs the parent. An unsupported atomic no-replace primitive returns UnsupportedCapability;
|
||||
there is no fallback to a racy existence-check plus overwrite. Existing nonempty directories
|
||||
are never recursively overwritten under an "atomic" label.
|
||||
|
||||
Replacing an application version uses immutable version directories and a separate pointer/
|
||||
activation owner, such as [Update](Update.md)'s VersionStore. Archive does not invent a new
|
||||
update commit point. If parent sync fails after rename, PublicationReceipt/error records
|
||||
Unknown outcome and the destination/staging identity so recovery can inspect it. It cannot
|
||||
claim the published tree was rolled back. Cancellation before publication cleans only the
|
||||
owned staging tree; after publication it reports the known/unknown publication outcome.
|
||||
|
||||
All filesystem accesses stay relative to retained directory handles on the hardened Linux
|
||||
path. Untrusted siblings cannot redirect extraction by swapping parent paths. Cleanup removes
|
||||
only names created under that owned staging descriptor and never follows links. Cleanup
|
||||
failure preserves the primary error and a retryable staging identifier, rather than masking
|
||||
the original decode/write error. Startup cleanup requires an exclusive operation marker and
|
||||
age/ownership validation, not a broad deletion of directories matching a prefix.
|
||||
|
||||
## Bounds, cancellation and diagnostics
|
||||
|
||||
Retain current file/total/entry defaults. NEW streaming defaults add a 64 KiB transfer buffer,
|
||||
8 MiB aggregate path/inventory metadata, four active jobs and 16 pending jobs per explicit
|
||||
managed service, and a 1 GiB compressed-input cap. Reject zero limits as invalid except an
|
||||
explicit zero-entry policy. Actual decompressed bytes count even when the format omits or
|
||||
lies about size; checked subtraction prevents arithmetic wrap. Nesting archives is never
|
||||
automatic. High compression ratios are allowed only within absolute limits.
|
||||
|
||||
Cooperative checks happen between headers and chunks, but do not make a codec call forcibly
|
||||
interruptible. The NEW hardened untrusted-input profile uses a System-owned child job with
|
||||
128 MiB RSS and 60-second total execution defaults, plus bounded result/output channels;
|
||||
the parent holds publication authority and verifies the staged tree before publishing.
|
||||
Platforms unable to enforce that profile report the capability gap. Ordinary embedded
|
||||
trusted-input mode can call the decoder synchronously with documented cooperative limits.
|
||||
Neither mode promises that a 64 KiB IO buffer bounds the decoder's internal memory.
|
||||
|
||||
Domain errors distinguish unsafe entry, unsupported format, corrupt archive, limit exceeded,
|
||||
permission, no space, cancellation, timeout and unknown publication. Diagnostics cap path
|
||||
rendering at 4 KiB and avoid writing attacker-controlled newlines unescaped. Progress callbacks
|
||||
run outside shared locks, own their event data if retained, and are rate-limited to 10 Hz
|
||||
per job. Failure to deliver progress never changes extraction success.
|
||||
|
||||
## Ordered work
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-ARCHIVE-01 | P0; existing tests | Characterize partial-tree failure, exact accepted path/type policy and platform capabilities; preserve all existing anti-traversal tests. | astra_implementer |
|
||||
| M-ARCHIVE-02 | P1; M-ARCHIVE-01, IO stream ownership, Binary bounds | Reader/listing and chunk adapters, metadata limits and typed errors; truncated/adversarial input cannot exceed accounted limits. | sol_implementer |
|
||||
| M-ARCHIVE-03 | P2; M-ARCHIVE-02, IO directory durability | StagedTree and atomic no-replace publication; crash at each sync/rename recovers either unpublished staging or a complete published tree. | astra_implementer |
|
||||
| M-ARCHIVE-04 | P2; M-ARCHIVE-02/03, System process limits | Hardened decoder isolation, cancellation/cleanup and race fixtures; parent never publishes unvalidated/partial child output. | astra_implementer |
|
||||
| M-ARCHIVE-05 | P3; M-ARCHIVE-03, Update package contract | Reproducible creation and package inventory verification; create/extract roundtrip preserves only allowed metadata and Update retains activation ownership. | sol_implementer |
|
||||
| M-ARCHIVE-06 | P3; M-ARCHIVE-04/05, shared harness | Fuzz corpus, filesystem fault campaign and decoder performance profiles; publish capability matrix before a new format/backend is accepted. | sol_implementer |
|
||||
|
||||
P4 snapshot/package transport reuses bounded archives; a replicated snapshot's correctness
|
||||
and installation marker belong to [Replication](../subsystems/Replication.md), not tar metadata.
|
||||
|
||||
## Verification and compatibility
|
||||
|
||||
CURRENT TEMPLATE: `<existing-build>/tests/VoidTests --filter '^archive_'`, backed by the
|
||||
test names above. [Validation](../VALIDATION.md) contains actual build evidence; no rerun
|
||||
occurred here. PROPOSED after M-ARCHIVE-02–06: malformed headers/zstd, duplicate/conflicting
|
||||
paths, long names, symlink swap at each parent, partial write/disk full/sync failure,
|
||||
cancellation during decode/publication, unsafe staging cleanup, resource-killed child and
|
||||
Windows capability fixtures. Include create→extract property tests and an independent
|
||||
tar consumer when validating generated packages; fixtures must not invoke production paths.
|
||||
|
||||
[Performance](../PERFORMANCE.md) profiles many tiny files, a few large files, incompressible
|
||||
data and compression bombs within test limits. Record p50/p95/p99 completion/admission,
|
||||
bytes/s, allocations, peak RSS/CPU including decoder child, disk amplification and build cost.
|
||||
The common repetition/confidence and regression rules apply; security checks remain enabled.
|
||||
|
||||
[Migration](../MIGRATION.md) keeps `extract` as the documented incremental API. New callers
|
||||
needing all-or-nothing visibility use extract_staged→publish and handle Unknown explicitly.
|
||||
Never change overwrite defaults silently. Rollback of an unselected new workflow can retain
|
||||
legacy extraction; rollback of a published tree is owned by the consuming application.
|
||||
New formats are version/profile gated. [Build/distribution](../BUILD-AND-DISTRIBUTION.md)
|
||||
keeps libarchive optional outside Archive consumers. Graph partial ranges in the header and
|
||||
test helper were read directly; cited source/test files were checked for coverage. No new
|
||||
atomicity, fuzz, portability or measured-performance result is claimed.
|
||||
@@ -0,0 +1,212 @@
|
||||
# Async completion and structured execution plan
|
||||
|
||||
Status: PLANNED feature work. Source baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
This document implements no execution features. Requirements R-005, R-009, R-012,
|
||||
R-014 and R-016 apply; [architecture](../ARCHITECTURE.md) C-02–C-05 and C-11
|
||||
define the shared boundaries.
|
||||
|
||||
## Existing surface and gaps
|
||||
|
||||
- [Task.hpp](../../../include/Void/Async/Task.hpp) provides move-only lazy
|
||||
`Void::Coro::Task<T>` and `Task<void>`, stored exceptions, continuation transfer,
|
||||
a borrowed `handle()`, and frame destruction by the owning Task. `run()` resumes
|
||||
once and reads the result; it is not a general event-loop driver for externally
|
||||
suspended operations. [Generator.hpp](../../../include/Void/Async/Generator.hpp)
|
||||
is the separate synchronous pull generator.
|
||||
- [Executor.hpp](../../../include/Void/Async/Executor.hpp) defines
|
||||
`Void::Async::Executor::post(coroutine_handle<>)`, a single-consumer
|
||||
`ManualExecutor`, `schedule_on`, and detached `spawn`. Queues hold borrowed
|
||||
handles. Detached exceptions terminate; cancellation and joining are absent.
|
||||
- [ThreadPool.hpp](../../../include/Void/Async/ThreadPool.hpp) is in
|
||||
`Void::Concurrency`, returns futures, drains and joins workers on destruction,
|
||||
and offers blocking `submit` and rejecting `try_submit`. Its historical
|
||||
`max_queue == 0` means unlimited queued work; running work is not part of that
|
||||
queue bound. [Channel.hpp](../../../include/Void/Async/Channel.hpp) is a bounded
|
||||
blocking MPMC channel, not a coroutine channel.
|
||||
- [MpscQueue.hpp](../../../include/Void/Async/MpscQueue.hpp),
|
||||
[ParallelFor.hpp](../../../include/Void/Async/ParallelFor.hpp),
|
||||
[Observable.hpp](../../../include/Void/Async/Observable.hpp), and
|
||||
[EventBus.hpp](../../../include/Void/Async/EventBus.hpp) supply useful primitives.
|
||||
EventBus async mode starts its own worker and snapshots callbacks at publication;
|
||||
unsubscribe cannot retract those copies. Observable/Signal iterate listener
|
||||
collections directly and need a documented reentrancy/threading policy.
|
||||
- [module.cmake](../../../src/Async/module.cmake) declares LogState. Remove
|
||||
mandatory concrete logging from the target execution contract through optional
|
||||
error/observation hooks, preserving compatibility adapters.
|
||||
|
||||
[Executor tests](../../../tests/standalone/Async/Executor.cpp),
|
||||
[coroutine tests](../../../tests/standalone/Async/Coro.cpp),
|
||||
[backpressure tests](../../../tests/standalone/Async/ThreadPoolBackpressure.cpp),
|
||||
[channel tests](../../../tests/standalone/Async/Channel.cpp), and
|
||||
[async event tests](../../../tests/standalone/Async/EventBusAsync.cpp) are existing
|
||||
fixtures. They do not establish structured lifetime or cancellation correctness.
|
||||
Graph coverage was checked for scoped source; Observable line 32 was read directly
|
||||
because it is partially parsed. Important ownership conclusions use source inspection.
|
||||
|
||||
## NEW API contracts
|
||||
|
||||
The following is a design sketch, not a compiling example. Async owns the sole
|
||||
public operation-options type used by IO, Net, RPC, Scheduler and other consumers:
|
||||
|
||||
```cpp
|
||||
namespace Void::Async { // NEW additions
|
||||
struct OperationOptions {
|
||||
std::stop_token stop{};
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline{};
|
||||
};
|
||||
enum class AdmissionError { overloaded, stopped, deadline_expired };
|
||||
class TaskScope {
|
||||
public:
|
||||
Result<JoinHandle> spawn(Coro::Task<void>&& task, OperationOptions = {});
|
||||
void request_stop() noexcept;
|
||||
Coro::Task<Result<void>> join();
|
||||
};
|
||||
// Executor evolution: try_post(owned_resume_ticket) -> Result<void>;
|
||||
// schedule_on(executor, options) -> cancellable scheduling awaitable.
|
||||
}
|
||||
```
|
||||
|
||||
`Result` is shorthand under C-02; Functional owns error representation. JoinHandle,
|
||||
resume tickets, scope construction and executor evolution are NEW Async-owned types.
|
||||
An execution binding borrows the executor, Time's injectable monotonic clock, and
|
||||
optional Memory resource. Their lifetimes extend through scope join. Clock injection
|
||||
is specified in [Time](Time.md); no consumer invents another clock or request context.
|
||||
The options fields above are fixed: consumers add domain options separately. The NEW
|
||||
Time type is `Void::Time::MonotonicClock`; manual-clock tests advance it and explicitly
|
||||
drive timer progress. Backends derive OS wait durations from the injected `now()` and
|
||||
must not compare a manual deadline with the host clock's current time.
|
||||
|
||||
No deadline means no time limit, not unlimited admission. A deadline is absolute in
|
||||
the injected steady-clock domain and covers queue waiting, execution and backend
|
||||
cleanup initiation. Stop already requested or deadline already expired rejects
|
||||
admission without invoking the operation. An accepted operation keeps its cleanup
|
||||
obligations even after its deadline. Parent stop and child stop combine in an owned
|
||||
stop source; they never rely on a temporary callback registration.
|
||||
|
||||
## Frame ownership and terminal arbitration
|
||||
|
||||
1. A lazy Task owns its frame before admission. Successful scope admission transfers
|
||||
the frame into a scope-owned control block; a failed admission leaves ownership
|
||||
with the caller or returns the task through the specified move-failure adapter.
|
||||
Choose a two-step reserve-then-transfer implementation so rejection never silently
|
||||
destroys an operation the caller still considers submitted.
|
||||
2. Executor queues store a retained resume ticket, never a bare handle whose owner
|
||||
may disappear. Only the selected consumer resumes a frame; queued/running flags
|
||||
prohibit concurrent resume and duplicate enqueue. Await suspension registration
|
||||
uses an atomic handshake so completion during `await_suspend` cannot lose a wake.
|
||||
3. The control block tracks admitted, active, stop-requested, backend-released,
|
||||
terminal-recorded and continuation-delivered states. Stop/expiry records intent and
|
||||
initiates cooperative cancellation; it does not immediately fix the result of an
|
||||
effectful operation. Its owner first gathers the required completion/persistence
|
||||
evidence, then one serialized transition or compare/exchange records the domain
|
||||
result. A terminal result already recorded cannot be overwritten by a later stop.
|
||||
4. Backend acknowledgement is awaited before buffer release and continuation delivery.
|
||||
Late completion is evidence for domain-result selection as well as cleanup, even
|
||||
when stop was requested first. A side-effect-free scheduling wait can finalize as
|
||||
cancelled/timed-out at its safe abort point; a transfer error preserves observed
|
||||
bytes/effects. A committing adapter returns a known commit receipt, proven
|
||||
NotCommitted cancellation, or explicit Unknown outcome according to its domain.
|
||||
Generic Async code never rewrites those outcomes to cancellation. The domain owns
|
||||
this classification; Async imports no Storage/Update types. Duplicate notifications
|
||||
cannot deliver again. Cancellation callbacks post control messages instead of
|
||||
destroying frames, and user callbacks never run under internal state locks.
|
||||
5. Join waits for terminal delivery, all children, backend references and callback
|
||||
registrations to drain. The frame is destroyed once, after final suspension and
|
||||
all resume tickets retire. Continuation delivery uses reserved capacity so a full
|
||||
executor cannot strand already admitted operations.
|
||||
|
||||
`TaskScope` destruction requests stop and joins on a permitted owner thread. On an
|
||||
executor thread, callers must `co_await join()` before destruction; blocking a worker
|
||||
needed for progress is a detected programmer error. An embedded single-thread driver
|
||||
can pump its executor while synchronously joining. No timeout frees live frames.
|
||||
Explicit detached launch requires an owner retained through completion plus an error
|
||||
sink; it is not the default scope behavior. CPU-bound user code must poll stop or
|
||||
yield; cancellation cannot impose a hard wall-clock shutdown guarantee.
|
||||
|
||||
NEW committing adapters keep their domain operation alive through evidence collection,
|
||||
including when a lower-level IO awaitable reports cancellation with partial effects.
|
||||
For a durable write, stopping before append yields NotCommitted; stopping during sync
|
||||
leaves the result pending; successful sync and publication after stop yield the receipt;
|
||||
failed sync after append yields Unknown unless non-commit is independently proved. The
|
||||
one continuation is delivered after backend access ends in every case. These are adapter
|
||||
conformance scenarios, not an Async dependency on the native engine.
|
||||
|
||||
## Queues, channels and event delivery
|
||||
|
||||
NEW defaults: 4,096 admitted tasks per executor including running work; 1,024 child
|
||||
tasks per scope; 1,024 values per coroutine channel; 4 MiB aggregate channel payload
|
||||
budget through a supplied size-accounting policy; 1,024 subscriptions and 1,024
|
||||
admitted event dispatches. Variable payloads require a byte-accounting policy rather
|
||||
than pretending element count bounds memory. Zero capacity is invalid; an explicitly
|
||||
named unlimited policy is available only where separately documented.
|
||||
|
||||
Initial scheduling uses a bounded mutex-protected FIFO and condition/event wakeups.
|
||||
Correct admission and lifetime precede work stealing or lock-free specialization.
|
||||
Work is charged until completion cleanup, with a reserved internal completion lane
|
||||
bounded by admitted operations. Default external submission rejects on overload;
|
||||
`async_wait_for_capacity(options)` is explicit and bounded to 1,024 waiters. Blocking
|
||||
submission is an off-executor adapter. ThreadPool futures keep their old behavior
|
||||
until a versioned adapter maps rejection and exceptions explicitly.
|
||||
|
||||
Coroutine channels offer cancellable send/receive and close-with-drain; failed send
|
||||
does not consume the caller's value. Separate closed, empty, full, cancelled and
|
||||
timed-out results. ParallelFor gains explicit grain/concurrency, stop propagation
|
||||
and deterministic exception aggregation after joining started chunks.
|
||||
|
||||
Subscriptions use immutable dispatch snapshots. Removing a subscription prevents new
|
||||
admission; NEW `close_and_join` waits for already admitted callbacks. Callback code
|
||||
and error sinks run outside subscriber locks. Self-unsubscribe is supported;
|
||||
self-join is rejected. Reentrant sync Observable updates queue bounded notifications
|
||||
instead of invalidating iteration. Async EventBus accepts an injected executor and
|
||||
keeps its private-worker constructor only as an explicit compatibility convenience.
|
||||
|
||||
## Backend and performance decisions
|
||||
|
||||
Use C++ standard threads, atomics, stop tokens and coroutines; no external execution
|
||||
engine. Async has no IO or Runtime dependency. [IO](../subsystems/IO.md) supplies
|
||||
operation backends; [Runtime](../subsystems/Runtime.md) composes them. Timer ordering
|
||||
uses a stable min-heap keyed by deadline and sequence with an injected Time clock.
|
||||
Cancellation removes or tombstones a timer while retaining its operation reference.
|
||||
|
||||
Measure empty-task hops, producer contention, 1/64/1,024-byte channel values,
|
||||
ParallelFor skew, event fan-out and cancel storms. Record p50/p95/p99, throughput,
|
||||
allocations/frame, peak RSS/CPU and compile/link cost under each
|
||||
[performance profile](../PERFORMANCE.md). A fixed admitted-work bound must imply a
|
||||
flat retained-frame count after repeated cancellation; no speedup is claimed here.
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
Every row is PLANNED; role recommendations are for later root delegation.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-ASYNC-01 | P0 / current source | Characterize Task moves, external suspension, executor and subscription lifetimes; independent-header/package checks | Reproduce unsafe lifetime preconditions without invoking UB in the harness; record existing future/exception behavior / sol_implementer |
|
||||
| M-ASYNC-02 | P1 / M-ASYNC-01; Time clock and Functional error gates | OperationOptions, reserve/transfer admission, owned resume tickets, terminal state machine and domain-outcome classification | Stop/completion/expiry permutations deliver once after backend release; fake committing adapter preserves known receipt/unknown outcome after stop; fake clock controls deadlines / astra_implementer |
|
||||
| M-ASYNC-03 | P1 / M-ASYNC-02 | TaskScope, join, explicit detached owner and shutdown guards | Nested stop joins all children; rejected admission preserves ownership; no self-deadlock / astra_implementer |
|
||||
| M-ASYNC-04 | P2 / M-ASYNC-03 | Bounded executors, cancellable channels, future pool adapter, ParallelFor | Bounds include running work; producer stop and close-drain deterministic; chunk errors join / sol_implementer |
|
||||
| M-ASYNC-05 | P2 / M-ASYNC-04 | EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling | Reentrancy, callback throw and unsubscribe races leave no captured state in use after join / sol_implementer |
|
||||
| M-ASYNC-06 | P3 / M-ASYNC-05; profile harness | Profile native queues; optimize only measured hot paths; major API migration | Conformance identical across optimized path; bounded allocation and installed consumers verified / astra_implementer |
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT tests are generated into `VoidTests` by
|
||||
[tests/CMakeLists.txt](../../../tests/CMakeLists.txt). Current available aggregate
|
||||
check: `ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`.
|
||||
It was not rerun for this document; inherited baseline failures are recorded in
|
||||
[VALIDATION](../VALIDATION.md). PROPOSED tests require the tasks above: deterministic
|
||||
pause points around registration/resume/destruction; cancellation at every await;
|
||||
cross-thread posting during shutdown; full queue at terminal delivery; faulting error
|
||||
sink; infinite cooperative child; byte budget exhaustion; sanitizer lifetime/race runs.
|
||||
Use a fake committing backend to stop before append and during sync, then independently
|
||||
release successful or failed sync. Assert the sole domain result and retained ownership;
|
||||
passing a cancellation-only scheduling test does not cover these commit races.
|
||||
|
||||
Keep `Void::Coro`, `Void::Concurrency`, `Void::EventBus` and `Void::Observable` names
|
||||
visible in migration examples. EXISTING `spawn(executor, task)` becomes NEW
|
||||
`scope.spawn(std::move(task), options)` plus `co_await scope.join()`. EXISTING
|
||||
`task.run()` remains for proven synchronous completion until deprecated; general
|
||||
blocking wait uses an explicit driver adapter. Preserve old future exception and
|
||||
zero/unbounded semantics in a versioned legacy adapter, never silently reinterpret
|
||||
them. Roll back a new executor backend behind selection before submission; never
|
||||
replay accepted work. See [MIGRATION](../MIGRATION.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), and [DELIVERY](../DELIVERY.md).
|
||||
@@ -0,0 +1,148 @@
|
||||
# Binary readers, writers and codec boundaries
|
||||
|
||||
Status: planning only; all feature tasks are **PLANNED**. Baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing baseline
|
||||
|
||||
[Binary](../../../src/Binary/module.cmake) currently depends on Functional and has one
|
||||
public header, [Reader](../../../include/Void/Binary/Reader.hpp). `Void::Binary::Reader`
|
||||
borrows `span<const byte>`, tracks its position and provides seek/skip, read/peek bytes,
|
||||
integral endian decoding, copied strings and bounded subreaders. Results use
|
||||
`Void::Result::Result<T>`. Returned byte spans/subreaders do not extend input lifetime.
|
||||
Integral reads use copied storage/bit_cast, so no aligned-load or aliasing requirement
|
||||
is imposed on input. The default byte order is native; it must not silently define a
|
||||
portable file or protocol format.
|
||||
|
||||
[Reader tests](../../../tests/standalone/Binary/Reader.cpp) check big-endian reading,
|
||||
truncation leaving position unchanged, and bounded children. No writer, varint, structured
|
||||
codec, stream backend or format registry exists in this source inventory. Scoped graph
|
||||
coverage reported no recorded gaps and the full reader/test were read directly.
|
||||
|
||||
## Ownership and backend decision
|
||||
|
||||
Per [C-01/C-02/C-07](../ARCHITECTURE.md), Binary owns representation mechanics; Data owns
|
||||
values/schema/reflection, Archive owns archive layouts, Storage owns its persisted
|
||||
records and Net owns protocol frames. IO owns actual transfers. Binary never imports
|
||||
these higher modules or starts workers. Choose native span cursors plus standard byte/
|
||||
bit/PMR tools. Do not add a generic serialization dependency or put JSON schema logic
|
||||
inside a byte reader. Checksums for storage integrity remain distinct from authentication;
|
||||
no homegrown cryptographic primitive is introduced.
|
||||
|
||||
## NEW cursor and buffer APIs
|
||||
|
||||
Illustrative NEW shape in NEW `include/Void/Binary/Writer.hpp` and
|
||||
NEW `include/Void/Binary/Varint.hpp` (signatures are not existing compiling examples):
|
||||
|
||||
```cpp
|
||||
namespace Void::Binary {
|
||||
class Writer {
|
||||
public:
|
||||
explicit Writer(std::span<std::byte> output) noexcept;
|
||||
std::size_t position() const noexcept;
|
||||
std::size_t remaining() const noexcept;
|
||||
Void::Result::Result<void> writeBytes(std::span<const std::byte>);
|
||||
template<std::integral T> requires (!std::same_as<T,bool>)
|
||||
Void::Result::Result<void> write(T, std::endian order); // no wire default
|
||||
Void::Result::Result<void> writeUvarint(std::uint64_t);
|
||||
};
|
||||
struct DecodeLimits {
|
||||
std::size_t max_field_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_total_bytes = 64 * 1024 * 1024;
|
||||
unsigned max_depth = 64;
|
||||
};
|
||||
Void::Result::Result<std::uint64_t> readUvarint(Reader&);
|
||||
}
|
||||
```
|
||||
|
||||
Writer borrows mutable output and owns only its cursor; caller owns the buffer through
|
||||
all access. Every primitive validates capacity before modifying bytes or position.
|
||||
`writeBytes` supports overlapping source/output via memmove-equivalent behavior; integral
|
||||
encoding uses local fixed storage. Composite encoders validate their exact measured size
|
||||
before publication or stage into bounded scratch. A cursor checkpoint rolls back position
|
||||
only; it must not claim to restore overwritten caller bytes. An explicit transactional
|
||||
encoder stages data when strong all-or-nothing bytes are required.
|
||||
|
||||
NEW `ByteBuffer` is an owning `pmr::vector<byte>` wrapper with an explicit Memory resource
|
||||
and a default 16 MiB capacity ceiling; growth checks current size + requested bytes and
|
||||
resource admission before reserve. It does not expose stable pointers across growth.
|
||||
`freeze()` transfers owned storage without copying and makes published bytes immutable.
|
||||
A borrowed span never becomes owning merely because it came from `freeze().view()`;
|
||||
the frozen owner must remain alive. Empty output is valid; a zero ceiling permits only
|
||||
empty output, never unlimited allocation.
|
||||
|
||||
Reader adds named `readLittle<T>`/`readBig<T>`, cursor transactions for compound parsing,
|
||||
and structured domain code/offset/requested/remaining diagnostics mapped through
|
||||
Functional. Preserve current primitive truncation behavior. Unsupported endian/type
|
||||
checks happen before consuming bytes. Floats use explicitly named IEEE binary32/binary64
|
||||
codecs and capability checks (`is_iec559` and width); no long-double object serialization.
|
||||
Booleans accept only 0/1. Signed integers have an explicit two's-complement wire contract;
|
||||
padding/native object representations are never copied as a schema.
|
||||
|
||||
## Varints, strings and incremental decoding
|
||||
|
||||
Unsigned varints use seven payload bits per byte, low group first, maximum ten bytes
|
||||
for uint64. Byte ten may contain only payload bit 0; continuation there is malformed.
|
||||
Reject nonminimal encodings by default, distinguishing truncated input from overflow and
|
||||
noncanonical data. Signed varints use explicit ZigZag operations in unsigned arithmetic,
|
||||
including INT64_MIN, without signed shifts/overflow. A compatibility permissive decoder
|
||||
must be named; it cannot be selected implicitly by a signed or storage format.
|
||||
|
||||
Length-prefixed byte fields decode length, check configured field and remaining-total
|
||||
limits, check size_t conversion, then borrow/copy as requested. Strings are bytes unless
|
||||
an explicitly named UTF codec is selected by the caller. Embedded NUL is not terminator.
|
||||
Nested limits are shared cumulative budget state, so children cannot each claim a fresh
|
||||
64 MiB allowance. Decompression belongs to Archive; advertised decompressed sizes are
|
||||
not permission for Binary to allocate arbitrary memory.
|
||||
|
||||
NEW incremental decoding returns `complete(value)`, `need_more(minimum_bytes)` or a
|
||||
terminal error plus consumed-byte count. `need_more` owns any retained partial bytes
|
||||
(at most ten for a varint); it never retains a temporary input span. Field assemblers
|
||||
reserve within the same aggregate budget and report cancellation between input chunks
|
||||
through a caller-driven adapter. Cancellation does not reinterpret already emitted
|
||||
streaming output as undone. Binary owns no async operation options; IO/Async adapters
|
||||
use their shared types under C-03.
|
||||
|
||||
## Codec boundary with Data and Storage
|
||||
|
||||
The selected NEW general value codec is **VoidValueBinary V1**, owned and versioned by
|
||||
Data with an adapter using Binary. Binary supplies primitives only. Data assigns value
|
||||
tags, duplicate policy and schema envelope; Storage independently assigns WAL/checkpoint
|
||||
framing, checksums and recovery rules. Neither codec may serialize raw `Value` object
|
||||
memory. Do not add CBOR/MessagePack/Protocol Buffers compatibility claims to this native
|
||||
format. Later standards adapters need named capability tasks and conformance fixtures.
|
||||
|
||||
## Ordered tasks
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-BINARY-01 | P0; current reader | Freeze cursor, lifetime, byte-order and failure fixtures; enumerate every current consumer before deprecating native-endian defaults. | sol_implementer |
|
||||
| M-BINARY-02 | P1; M-BINARY-01; Functional error gate | Implement Writer, explicit endian primitives and structured diagnostics; truncation/unsupported operations change neither cursor nor bytes. | sol_implementer |
|
||||
| M-BINARY-03 | P1; M-BINARY-02; Memory bounded-resource gate | Add owning ByteBuffer, immutable transfer and cumulative budgets; allocation failure and capacity exhaustion preserve published storage. | sol_implementer |
|
||||
| M-BINARY-04 | P2; M-BINARY-02 | Add canonical varints/ZigZag, length fields and explicit floating codecs; golden bytes, invalid encodings and all uint64 boundaries pass. | sol_implementer |
|
||||
| M-BINARY-05 | P2; M-BINARY-03–04 | Add incremental parsing and Data adapter primitives; all chunk boundaries produce identical values and retained bytes remain within limits. | sol_implementer |
|
||||
| M-BINARY-06 | P3; M-BINARY-05; Data V1 codec gate | Publish portable format examples, fuzz targets and installed minimal consumers; differential round trips and independent golden fixtures pass. | sol_implementer |
|
||||
|
||||
## Validation, migration and resource evidence
|
||||
|
||||
CURRENT checks are the existing Reader suite and parent baseline; no build was rerun.
|
||||
PROPOSED tests include unaligned spans, empty/exact/one-byte-short output, overlapping
|
||||
writeBytes, endian fixtures independent of host, noncanonical varints, all truncated
|
||||
prefixes, INT64_MIN, NaN payload handling and nested cumulative-budget exhaustion.
|
||||
Fuzz decode plus writer replay; include malicious length values near SIZE_MAX before
|
||||
any allocation. Cross-endian emulation/targets are proposed prerequisites, not current
|
||||
compiler/platform evidence. Shared schema owners review the V1 tag and framing fixtures.
|
||||
|
||||
Measure scalar and batched cursor operations, copied versus borrowed fields, incremental
|
||||
chunk sizes and allocation counts with [PERFORMANCE](../PERFORMANCE.md): p50/p95/p99,
|
||||
throughput, peak RSS/CPU and build cost. Track scratch capacity, retained partial fields
|
||||
and owning-buffer capacity separately. No benchmark was executed for this plan.
|
||||
|
||||
[Migration](../MIGRATION.md) preserves Reader's current names through adapters and adds
|
||||
explicit endian overloads before removing ambiguous defaults in a major release. File/
|
||||
wire bytes are versioned by their owner; changing helper APIs cannot rewrite them.
|
||||
Rollback keeps old readers until new-format writes are disabled or compatibility readers
|
||||
are deployed. See [Data](Data.md), [Memory](../subsystems/Memory.md),
|
||||
[Storage](../subsystems/Storage.md), [IO](../subsystems/IO.md),
|
||||
[VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
|
||||
[DELIVERY](../DELIVERY.md) and [requirements](../REQUIREMENTS.md).
|
||||
@@ -0,0 +1,167 @@
|
||||
# Configuration schemas and transactional reload plan
|
||||
|
||||
Status: PLANNED feature work. Baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`,
|
||||
inspected 2026-11-24. Requirements R-002, R-004, R-009 and R-014 apply. Shared
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-05, C-07 and C-13 governs this plan.
|
||||
|
||||
## Existing source and behavioral boundary
|
||||
|
||||
[Config.hpp](../../../include/Void/Configuration/Config.hpp) implements
|
||||
`Void::Configuration::Config`: string-valued dotted keys, environment allowlists and
|
||||
prefixes, KEY=VALUE/INI/JSON/argument sources, last-writer overlay, sorted keys, subtrees,
|
||||
typed conversion and duration/byte-size handling. Returned string_views borrow the
|
||||
Config's storage. [Bind.hpp](../../../include/Void/Configuration/Bind.hpp) binds
|
||||
reflection aggregates, nested objects, optionals/vectors, defaults, `Key` and `Required`
|
||||
annotations. [Argparse.hpp](../../../include/Void/Configuration/Argparse.hpp) uses the
|
||||
separate `Void::Argparse` namespace, with parser and reflection-generated options;
|
||||
[Argparse.cpp](../../../src/Configuration/Argparse.cpp) implements parsing.
|
||||
[Env.hpp](../../../include/Void/Configuration/Env.hpp) wraps getenv; this plan does
|
||||
not inspect any environment values.
|
||||
|
||||
[Watch.hpp](../../../include/Void/Configuration/Watch.hpp) provides `ConfigWatch`.
|
||||
Parse/load failure preserves the last configuration, deletion preserves it, and a
|
||||
successful load replaces `m_current` before calling `on_reload` outside its mutex.
|
||||
There is no validation/prepare vote before that publication. Initial load failure
|
||||
leaves an empty configuration without a fallible factory result. A callback rejecting
|
||||
the new config cannot roll publication back transactionally today.
|
||||
|
||||
[Source tests](../../../tests/standalone/Configuration/Sources.cpp),
|
||||
[typed tests](../../../tests/standalone/Configuration/Typed.cpp),
|
||||
[binding tests](../../../tests/standalone/Configuration/BindAnnotations.cpp), and
|
||||
[watch tests](../../../tests/standalone/Configuration/Watch.cpp) establish existing
|
||||
fixtures. [module.cmake](../../../src/Configuration/module.cmake) declares Functional,
|
||||
System, Data and Time. Graph coverage is partial at declarations in Config, Bind,
|
||||
Argparse, Env and Watch; all reported ranges were read directly. Reflection behavior
|
||||
must be verified with the actual selected compiler, not inferred from graph parsing.
|
||||
|
||||
## NEW schema and immutable snapshot API
|
||||
|
||||
Design sketch, with Result shorthand from Functional and the sole shared options from
|
||||
[Async](Async.md); these names and methods do not yet exist:
|
||||
|
||||
```cpp
|
||||
namespace Void::Configuration {
|
||||
struct SourceLocation { SourceId source; std::string key; std::uint32_t line; };
|
||||
template<class T> struct Snapshot {
|
||||
std::uint64_t generation;
|
||||
std::shared_ptr<const T> values;
|
||||
std::shared_ptr<const Provenance> provenance;
|
||||
};
|
||||
template<class T> Result<Validated<T>> validate(const Config&, const Schema<T>&);
|
||||
template<class T> class ReloadController {
|
||||
public:
|
||||
Snapshot<T> current() const;
|
||||
Coro::Task<Result<ReloadReport>> reload(SourceSet, Async::OperationOptions);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Schema<T> is Configuration-owned and reuses Data's schema/value machinery. Reflection
|
||||
generates field metadata; explicit schema definitions support cross-field constraints,
|
||||
secret flags, restart-required keys, ranges, deprecations and strict unknown-key policy.
|
||||
Default unknown keys are errors in typed managed configuration; legacy Config retains
|
||||
its permissive string map. Validate a separate default-constructed candidate, collect
|
||||
at most 100 diagnostics, and publish only a complete value. Conversion errors retain
|
||||
source/key/line and machine category; secret values never appear in diagnostics.
|
||||
|
||||
Default precedence is schema defaults < declared files in order < explicitly selected
|
||||
environment variables < explicit CLI options. Each key retains winning origin and
|
||||
shadowed-origin identifiers without retaining redundant secret values. Missing, empty,
|
||||
null, malformed and removed keys are distinct. Dotted-key escaping/collision rules are
|
||||
specified before adding richer structured values: default reject an ambiguous literal
|
||||
dot versus nested JSON path collision. No fallback from malformed supplied values to
|
||||
defaults. Vectors require contiguous indexes; gaps are validation errors in NEW binding.
|
||||
|
||||
## Transaction protocol
|
||||
|
||||
Reload is serialized per controller and follows read → bounded parse → merge → typed
|
||||
bind → validate → prepare → publish → notify. The transaction has one immutable aggregate
|
||||
generation containing validated settings and prepared per-component resource views.
|
||||
Consumers acquire that aggregate once per operation, so a request cannot mix generations.
|
||||
A NEW prepare-only port can export the retained candidate view to a platform coordinator.
|
||||
For that mode, the platform's single Service/host generation publisher owns commit;
|
||||
the standalone ReloadController must not independently publish the same resource set.
|
||||
|
||||
1. Snapshot source bytes and a monotonically increasing source revision. Watch events
|
||||
coalesce; changed content during reading schedules a fresh candidate. Metadata
|
||||
debounce is only a hint. Resolve declared sources, never crawl arbitrary paths or
|
||||
enumerate the entire environment by default.
|
||||
2. Run pure validators and restart-required checks without registry/publication locks.
|
||||
Rejected fields preserve the active snapshot. A restart-required delta reports a
|
||||
pending restart; it does not partly apply the remaining fields by default.
|
||||
3. Each registered participant prepares candidate-owned resources without externally
|
||||
visible mutation. `prepare(old, candidate, options)` returns a NEW PreparedChange
|
||||
whose retained immutable view is inserted into the aggregate. Prepare may fail or
|
||||
be cancelled; disposal closes/joins its candidate work. Unregister/close joins
|
||||
participant callbacks before freeing captures.
|
||||
4. Once every prepare succeeds, check source revision, stop/deadline and the active
|
||||
generation under the short publication guard. Publish one retained aggregate pointer.
|
||||
The pointer swap is the commit point. No fallible user code, allocation, resource
|
||||
creation or callbacks are allowed in commit. An operation that needs independent
|
||||
mutable side-effect commits is not a transactional participant and must be redesigned
|
||||
or marked restart-required.
|
||||
5. Post-commit notifications are bounded observations outside locks. Callback failure
|
||||
reports a committed generation plus notification error; it does not claim rollback.
|
||||
Old resources remain pinned by old snapshots until their operations drain. A stop
|
||||
racing after commit returns committed-with-stop-observed, not a false rejection.
|
||||
|
||||
Rollback before commit disposes the candidate in reverse preparation order and leaves
|
||||
the exact old generation active. Reverting after commit is another validated transaction;
|
||||
it may fail and receives its own generation. Persistent config file changes are a separate
|
||||
System durable-replacement operation, not an implied distributed transaction.
|
||||
|
||||
## Resource limits and backend choice
|
||||
|
||||
Native parsing/binding over current Data and standard containers remains the initial
|
||||
implementation; no external configuration framework. General JSON follows Data, while
|
||||
signed release documents remain StrictJson/Update-owned and unchanged (C-07).
|
||||
Default: 1 MiB/source, 8 sources, 4 MiB merged decoded values, 10,000 keys, 4 KiB key,
|
||||
64 KiB scalar, nesting depth 32, 1,024 vector items, 64 participants and one prepared
|
||||
candidate. All source, merged, provenance and diagnostic buffers count toward the limit.
|
||||
Environment capture uses an allowlist or explicitly requested prefix and the same caps.
|
||||
|
||||
Keep at most four retained controller generations by default. If consumers still pin
|
||||
four, reject a fifth reload with `retention_limit`; never invalidate a live snapshot.
|
||||
Each participant declares a preparation resource budget; the controller cannot infer
|
||||
memory held by arbitrary callbacks. Default prepare deadline is 5 seconds using Time's
|
||||
injected monotonic clock; owned work still must drain before disposal can complete.
|
||||
Notification queue: 128 generation events with explicit coalesced-generation reporting.
|
||||
No global Runtime is created; synchronous validation is usable without workers and
|
||||
the async reload adapter uses injected Async/System resources.
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
All rows are PLANNED.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-CONFIGURATION-01 | P0 / baseline | Characterize source precedence, borrowing, initial watch failure, vector gaps and key collisions | Regression fixtures separate permissive legacy behavior from strict NEW behavior / sol_implementer |
|
||||
| M-CONFIGURATION-02 | P1 / M-CONFIGURATION-01; Data schema/error gates | Schema metadata, provenance, bounded parsing and all-or-nothing typed binding | Overflow/unknown/range/cross-field failures contain redacted origins and leave input untouched / sol_implementer |
|
||||
| M-CONFIGURATION-03 | P2 / M-CONFIGURATION-02; Async scope gate | Immutable snapshots, serialized prepare/publish protocol and fallible controller factory | Any prepare failure preserves generation; one pointer swap publishes coherent resources / astra_implementer |
|
||||
| M-CONFIGURATION-04 | P2 / M-CONFIGURATION-03; System joined watcher gate | Coalescing watch adapter, source-revision validation, joined participants | Rapid edit/delete/recreate and slow validator never publish stale or partial candidate / sol_implementer |
|
||||
| M-CONFIGURATION-05 | P3 / M-CONFIGURATION-04 | Runtime/Service integration, retained-resource accounting, migration examples | Old operation sees old settings throughout; new acquisition sees new generation; leaked pins reject reload / astra_implementer |
|
||||
|
||||
## Validation, performance and migration
|
||||
|
||||
CURRENT tests run through the aggregate command
|
||||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||||
not rerun for this documentation change. PROPOSED tests require the NEW controller:
|
||||
participant 2 fails after participant 1 allocates; cancellation immediately before/after
|
||||
swap; concurrent reload ordering; reader pin across replacement; notification throw;
|
||||
unknown key and nested name collision; secret-bearing parse error; byte/key/depth caps;
|
||||
invalid initial config; rollback cleanup that needs asynchronous join. Validate compiled
|
||||
reflection examples and installed isolated Configuration consumers at implementation time.
|
||||
|
||||
Measure reload p50/p95/p99, reader acquisition cost, parse/validation throughput,
|
||||
allocations, retained-generation RSS/CPU and compile cost under
|
||||
[PERFORMANCE](../PERFORMANCE.md). No benchmark results are asserted.
|
||||
|
||||
EXISTING `ConfigWatch::json(path, callback)` migrates to a NEW fallible controller
|
||||
factory with schema, participants and explicit executor; callback-only users get a
|
||||
notification adapter, not a veto callback after publication. Retain Config's borrowing
|
||||
and overlay API until a major-release transition; snapshot examples keep the owning
|
||||
Snapshot alive while reading fields. Failures in legacy initial load become explicit
|
||||
errors in the NEW factory. Rollback keeps the previous controller active until the
|
||||
replacement controller validates and starts. See [MIGRATION](../MIGRATION.md),
|
||||
[VALIDATION](../VALIDATION.md), [Runtime](../subsystems/Runtime.md),
|
||||
[Service](Service.md) and [DELIVERY](../DELIVERY.md).
|
||||
@@ -0,0 +1,155 @@
|
||||
# Containers completion plan
|
||||
|
||||
Status: planning only; every feature task is **PLANNED**. Baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing structures and gaps
|
||||
|
||||
[The module](../../../src/Containers/module.cmake) declares no dependencies. It already
|
||||
contains [fixed bitsets](../../../include/Void/Containers/Bitset.hpp),
|
||||
[intervals](../../../include/Void/Containers/Interval.hpp),
|
||||
[disjoint sets](../../../include/Void/Containers/DisjointSet.hpp),
|
||||
[a directed graph](../../../include/Void/Containers/Graph.hpp),
|
||||
[a trie](../../../include/Void/Containers/Trie.hpp),
|
||||
[an indexed priority queue](../../../include/Void/Containers/PriorityQueue.hpp),
|
||||
[LRU](../../../include/Void/Containers/LRU.hpp),
|
||||
[TTL/policy cache](../../../include/Void/Containers/Cache.hpp),
|
||||
[object pools](../../../include/Void/Containers/Pool.hpp),
|
||||
[buffer recycling](../../../include/Void/Containers/BufferPool.hpp),
|
||||
[rings](../../../include/Void/Containers/Ring.hpp), and
|
||||
[debug rendering](../../../include/Void/Containers/Debug.hpp).
|
||||
Namespaces follow header families (`Void::Ring`, `Void::Cache`, etc.); a unified
|
||||
`Void::Containers` naming migration must not pretend they already share one namespace.
|
||||
|
||||
`SpscRing<T,N>` exposes N−1 usable entries. `MpscRing` reserves a head position before
|
||||
construction and spins waiting for readiness. That is not a general wait-free guarantee:
|
||||
a stalled producer can stall the consumer, and throwing construction needs a defined
|
||||
reservation-repair contract. Buffer leases store a raw pool pointer; moving/destroying
|
||||
the pool with outstanding leases needs a stronger lifetime rule. Cache already accepts
|
||||
an injected steady-clock callable and supports LRU/LFU/FIFO with lazy TTL expiry.
|
||||
ObjectPool and FixedPool return deleters tied to their pool owner. These are implementation
|
||||
constraints to repair, not proof of production readiness.
|
||||
|
||||
[Existing standalone suites](../../../tests/standalone/Containers) cover each header;
|
||||
[ring](../../../tests/standalone/Containers/Ring.cpp),
|
||||
[pool](../../../tests/standalone/Containers/Pool.cpp),
|
||||
[buffer-pool](../../../tests/standalone/Containers/BufferPool.cpp), and
|
||||
[cache](../../../tests/standalone/Containers/Cache.cpp) are regression starting points.
|
||||
Graph coverage marked PriorityQueue line 23 partial; the constructor was read directly.
|
||||
|
||||
## Target ownership and backend choice
|
||||
|
||||
Under [C-01/C-04/C-05](../ARCHITECTURE.md), [Memory](../subsystems/Memory.md) owns raw
|
||||
allocation resources; Containers owns typed lifetime, handles and data structures.
|
||||
[Algorithms](../subsystems/Algorithms.md) owns reusable graph/range algorithms and
|
||||
imports no Containers. Containers graph convenience members may delegate downward.
|
||||
Standard vector/map/unordered_map/list/heap algorithms remain implementation building
|
||||
blocks. Do not build a general hash-table or tree replacement without a named workload
|
||||
and benchmark gate. Native specializations address bounded admission, stable identities
|
||||
and inline storage that current module users actually need.
|
||||
|
||||
## NEW types and selected algorithms
|
||||
|
||||
Illustrative NEW API in NEW `include/Void/Containers/StaticVector.hpp` and
|
||||
NEW `include/Void/Containers/SlotMap.hpp`:
|
||||
|
||||
```cpp
|
||||
namespace Void::Containers {
|
||||
enum class InsertError { full, allocation_failed, generation_exhausted };
|
||||
template<class T, std::size_t N> class StaticVector {
|
||||
public:
|
||||
template<class... A> std::expected<std::reference_wrapper<T>, InsertError>
|
||||
try_emplace_back(A&&...);
|
||||
std::span<T> values() noexcept;
|
||||
};
|
||||
struct SlotHandle { std::uint32_t slot; std::uint32_t generation; };
|
||||
template<class T> class SlotMap {
|
||||
public:
|
||||
template<class... A> std::expected<SlotHandle, InsertError> emplace(A&&...);
|
||||
T* get(SlotHandle) noexcept;
|
||||
bool erase(SlotHandle);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
StaticVector uses aligned uninitialized inline storage and constructs exactly `size()`
|
||||
objects. Capacity exhaustion leaves it unchanged. Throwing constructors preserve prior
|
||||
elements and propagate unless an explicit exception adapter is used. Moving an inline
|
||||
container invalidates element pointers. This supports small request metadata and
|
||||
dependency lists without forcing a heap allocation.
|
||||
|
||||
SlotMap starts with segmented slots (256 per block), a free-index list and generation
|
||||
checks. It preserves addresses of other live elements on growth, useful for graph and
|
||||
registry identities, but is not itself a service handle or ownership pin. Erase increments
|
||||
generation; retire a slot permanently on generation exhaustion to prevent ABA reuse.
|
||||
Default maximum: 65,536 live slots; include retired slots and block metadata in the byte
|
||||
budget. No pointer remains valid after its object's erase or container destruction.
|
||||
|
||||
SmallVector is a later NEW inline-then-heap specialization (default inline capacity 8)
|
||||
only after StaticVector and allocator exception safety pass. Growth defaults to at most
|
||||
4,096 elements; allow an explicit larger bound. Contiguous relocation invalidates
|
||||
references. Compare with `std::vector` plus reserve for request-header and configuration
|
||||
workloads before making it an internal default.
|
||||
|
||||
Keep SPSC admission nonblocking and reject full. Require nonthrowing transfer types for
|
||||
the NEW concurrent ring APIs and explicitly quiesced destruction. Replace the MPSC spin
|
||||
path with per-slot sequence publication and a `try_pop` that returns empty/pending/closed
|
||||
without waiting for a reserved but unpublished slot. Ordered consumption may return
|
||||
pending behind a stalled producer; no unconditional lock-free progress claim is made.
|
||||
Async owns waits, wakeups, cancellation and queue shutdown adapters. Rings own no threads.
|
||||
|
||||
Pool control blocks remain stationary; owning leases retain shared pool state through
|
||||
their final return, while explicitly borrowed pools require lease-before-owner
|
||||
destruction. Return paths allocate nothing and never throw; exhausted retention frees to
|
||||
the upstream resource. Default buffer limits: 1 MiB/request, 16 MiB idle bytes and 64 MiB
|
||||
total checked-out plus idle bytes. Size-class rounding is checked before allocation.
|
||||
Object-pool admission defaults to 4,096 live objects with explicit constructor limits.
|
||||
|
||||
## Existing capability completion
|
||||
|
||||
Cache defaults stay explicit-capacity; the NEW convenience constructor selects 1,024
|
||||
entries and a 16 MiB weight budget. Caller-supplied weight functions account for payloads;
|
||||
no pretend exact RSS bound for arbitrary `T`. TTL uses Time's clock contract, with
|
||||
zero-duration meaning immediate expiry. Eviction/expiry callbacks execute after mutation
|
||||
and outside any adapter lock. LFU tie-breaking becomes deterministic by age and its
|
||||
linear-scan cost is documented until workload evidence justifies a different structure.
|
||||
Trie adds iterative traversal, prefix result limits (256 default), and a 4 KiB key limit.
|
||||
Graph traversal takes explicit vertex/edge budgets (65,536/262,144 default). Priority
|
||||
updates preserve heap/index consistency if key copying/allocation fails; comparison must
|
||||
be stable and nonthrowing for its bounded fast path. Interval endpoints remain half-open;
|
||||
closed-to-half-open conversion checks maximum-endpoint overflow. Bitset zero-size and
|
||||
tail masking receive explicit tests. Debug formatting truncates at 256 entries/16 KiB.
|
||||
|
||||
## Ordered implementation tasks
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-CONTAINERS-01 | P0; current source | Document capacity, invalidation, thread and exception guarantees for every current structure; preserve deterministic fixtures. | sol_implementer |
|
||||
| M-CONTAINERS-02 | P1; Memory bounded-resource gate; M-CONTAINERS-01 | Repair object/buffer lease lifetime and byte accounting; owner destruction with retained leases is safe and recycle allocates zero. | astra_implementer |
|
||||
| M-CONTAINERS-03 | P1; M-CONTAINERS-01 | Implement nonthrowing ring publication and nonspinning MPSC poll semantics; delayed producer, wraparound and quiesced destruction tests pass under sanitizers/TSAN. | astra_implementer |
|
||||
| M-CONTAINERS-04 | P2; M-CONTAINERS-02 | Add StaticVector and SlotMap; capacity failure, over-alignment, constructor exceptions and stale handles leave invariants intact. | sol_implementer |
|
||||
| M-CONTAINERS-05 | P2; M-CONTAINERS-01; Algorithms graph gate; Time clock gate | Complete bounded graph/trie/priority/interval/bitset/cache APIs; deterministic fake-clock eviction and failure injection match reference models. | sol_implementer |
|
||||
| M-CONTAINERS-06 | P3; M-CONTAINERS-04; measured request-metadata profile | Add bounded SmallVector and compare reserved std::vector; publish allocation, relocation and compile-cost evidence before adoption. | sol_implementer |
|
||||
| M-CONTAINERS-07 | P3; M-CONTAINERS-02–06 | Ship compatibility aliases, independent installed consumers and workload report; no unexplained dependency or progress-guarantee regression. | sol_implementer |
|
||||
|
||||
## Validation and transition
|
||||
|
||||
CURRENT checks are the inspected suites, not new executions. PROPOSED model/property
|
||||
tests replay randomized operations against standard containers, force allocation and
|
||||
construction failure at each insertion step, and verify destructor counts. TSAN plus
|
||||
scheduled producer pauses exercise concurrency; TSAN alone cannot establish progress.
|
||||
Bounded polling tests must terminate without a producer resuming. Retained pool leases,
|
||||
moved containers, generation wrap and zero/maximum interval endpoints get dedicated cases.
|
||||
|
||||
Measure mixed cache traces, bursty ring occupancy, pool churn, prefix scans and 0–32-item
|
||||
metadata under [PERFORMANCE](../PERFORMANCE.md): p50/p95/p99, throughput, live/idle bytes,
|
||||
allocations, peak RSS/CPU and build cost. A lock-free label is not an acceptance metric.
|
||||
The [validation](../VALIDATION.md), [dependency](../DEPENDENCIES.md) and
|
||||
[delivery](../DELIVERY.md) gates precede integration into Runtime or Net.
|
||||
|
||||
[Migration](../MIGRATION.md) preserves old namespaces through deprecated aliases while
|
||||
new bounded constructors and poll results require explicit caller changes. Move raw
|
||||
allocation implementation to Memory behind old pool wrappers only after lifetime
|
||||
contracts are tested; do not create Memory→Containers. Rollback uses the old major and
|
||||
adapters without persistent state conversion. Never interchange in-memory SlotHandle
|
||||
values with serialized IDs. [Requirements](../REQUIREMENTS.md) define package scope.
|
||||
@@ -0,0 +1,141 @@
|
||||
# Core completion plan
|
||||
|
||||
Status: planning only. All feature tasks below are **PLANNED**. Baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing capability and evidence
|
||||
|
||||
[Core's declaration](../../../src/Core/module.cmake) currently declares no internal
|
||||
dependencies. Its public headers include [Bits](../../../include/Void/Core/Bits.hpp),
|
||||
[Flags](../../../include/Void/Core/Flags.hpp), [Hash](../../../include/Void/Core/Hash.hpp),
|
||||
[Scope](../../../include/Void/Core/Scope.hpp), [Lazy](../../../include/Void/Core/Lazy.hpp),
|
||||
[Counted](../../../include/Void/Core/Counted.hpp),
|
||||
[TypeList](../../../include/Void/Core/TypeList.hpp),
|
||||
[TypeMap](../../../include/Void/Core/TypeMap.hpp),
|
||||
[Variant](../../../include/Void/Core/Variant.hpp), and reflection
|
||||
[Meta](../../../include/Void/Core/Meta.hpp). These are separate namespaces such as
|
||||
`Void::Bits`, `Void::Meta`, and `Void::Scope`, not an existing `Void::Core` namespace.
|
||||
Reflection is conditionally compiled; retaining C++26 reflection remains R-002.
|
||||
|
||||
[Uuid](../../../include/Void/Core/Uuid.hpp) stores sixteen bytes, parses compact or
|
||||
hyphenated hex, generates v4 through `Void::Random`, and exposes `v5_lite` using
|
||||
noncryptographic hashes. The Math include is a real undeclared dependency to remove.
|
||||
`v5_lite` is not interoperable SHA-1 UUID v5 and must never be advertised as such.
|
||||
Its temporary string allocation and several allocating `noexcept` APIs warrant an
|
||||
exception-specification audit. Hash functions are utility hashes, not authentication.
|
||||
|
||||
[Core tests](../../../tests/standalone/Core) exercise all these header families;
|
||||
[UUID tests](../../../tests/standalone/Core/Uuid.cpp),
|
||||
[scope tests](../../../tests/standalone/Core/Scope.cpp), and
|
||||
[reflection tests](../../../tests/standalone/Core/Meta.cpp) provide baseline fixtures.
|
||||
These are inspected capabilities, not a fresh test-pass claim. Graph coverage reported
|
||||
partial parsing at Meta line 280 and Variant line 17; those ranges were read directly.
|
||||
|
||||
## Ownership and target boundary
|
||||
|
||||
[Architecture C-01/C-02/C-13](../ARCHITECTURE.md) governs this layer. Core stays native
|
||||
and standard-library-only: identity representation, bit operations, traits, lifetime
|
||||
guards, and small vocabulary helpers. It never imports Math, Functional, Memory,
|
||||
execution, logging, or crypto. Fallible Core primitives use
|
||||
`std::expected<T, local_error_enum>`; Functional supplies optional error adapters above
|
||||
Core. Allocator facilities belong to [Memory](../subsystems/Memory.md), checked general
|
||||
numeric arithmetic to [Math](Math.md), and error categorization to [Functional](Functional.md).
|
||||
|
||||
Keep the default include cost small: bit and type-list users must not instantiate
|
||||
reflection or diagnostic formatting. Split heavyweight formatting/reflection bridges
|
||||
into explicitly included headers, preserving forwarding includes for one major migration.
|
||||
Do not replace standard scope or type utilities merely to add another spelling.
|
||||
|
||||
## NEW API shapes and behavior
|
||||
|
||||
The following are illustrative NEW declarations, not compiling current examples.
|
||||
Proposed paths are `include/Void/Core/Uuid.hpp` extensions and NEW
|
||||
`include/Void/Core/CheckedBits.hpp`.
|
||||
|
||||
```cpp
|
||||
namespace Void::Uuid {
|
||||
enum class GenerateError { entropy_unavailable, invalid_source };
|
||||
// Caller-supplied URBG; deterministic tests need no global generator.
|
||||
template<std::uniform_random_bit_generator G> Uuid v4(G& generator);
|
||||
std::expected<Uuid, GenerateError> try_v4();
|
||||
// Fixed-size output excludes string allocation and null termination.
|
||||
std::array<char, 36> format_chars(const Uuid&) noexcept;
|
||||
}
|
||||
namespace Void::Bits {
|
||||
enum class BitError { invalid_range, invalid_alignment, overflow };
|
||||
template<std::unsigned_integral T>
|
||||
std::expected<T, BitError> checked_extract(T value, unsigned offset, unsigned count);
|
||||
template<std::unsigned_integral T>
|
||||
std::expected<T, BitError> checked_align_up(T value, T alignment);
|
||||
}
|
||||
```
|
||||
|
||||
`try_v4()` uses a standard entropy source locally, reports source failure, and makes
|
||||
no cryptographic-strength guarantee. Security-sensitive identifiers obtain bytes from
|
||||
Security/Crypto through the injected-generator overload; that adapter lives above Core.
|
||||
Mask version and variant only after all bytes are acquired. No hidden worker or cached
|
||||
process service is created. Keep `Uuid::Uuid` layout and string representation stable.
|
||||
The legacy no-argument `v4()` becomes a documented throwing convenience in the major
|
||||
release; remove its misleading unconditional `noexcept` rather than returning a nil ID
|
||||
on failure. An explicit legacy adapter preserves old source names during transition.
|
||||
|
||||
Checked bit operations validate offset/count without overflowing their sum. Count zero
|
||||
returns zero for extraction; a full-width mask never shifts by the width. Alignment must
|
||||
be nonzero and a power of two; overflow returns failure before arithmetic. Existing fast
|
||||
preconditioned helpers remain available with their preconditions stated.
|
||||
|
||||
Scope callbacks execute once, must not throw during destruction, and hold decayed owned
|
||||
callables unless references are explicitly wrapped. Conditional move `noexcept` must
|
||||
match the callable. `Lazy` stays single-threaded; `LazySync` uses `call_once` publication,
|
||||
including synchronized observation of `evaluated()`. A failed factory remains retryable;
|
||||
recursive access is documented as invalid and gets a debug diagnostic. Neither lazy
|
||||
wrapper promises a cancellation or reset protocol across concurrent readers.
|
||||
|
||||
TypeMap gains reference lookup without copying `std::any` values; returned references
|
||||
expire on replacement/erase/destruction. It remains a utility, not a service registry.
|
||||
Counters document wraparound and prohibit use as durable identities; an opt-in checked
|
||||
sequence reports exhaustion. Compile-time list operations get diagnostics for missing
|
||||
types and bad indices, rather than accidental template-depth explosions.
|
||||
|
||||
## Backlog and ordered implementation
|
||||
|
||||
| Task | Phase; dependencies | Intended scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-CORE-01 | P0; current source | Inventory every public header, namespace, reflection branch, exception specification and direct include; isolated Core consumer exposes the Math leak and records the compatibility surface. | sol_implementer |
|
||||
| M-CORE-02 | P1; M-CORE-01 | Implement injected UUID generation, allocation-free parse/format and fallible entropy path; preserve byte/string fixtures and remove all Core→Math includes. | sol_implementer |
|
||||
| M-CORE-03 | P1; M-CORE-01 | Add checked bit/alignment helpers and portable hash byte loading; constexpr boundary tests cover zero/full widths, maximum values and endianness. | sol_implementer |
|
||||
| M-CORE-04 | P2; M-CORE-01 | Repair guard move contracts and lazy observation; throwing/move-only factories and contended successful initialization execute/destruct exactly as specified. | astra_implementer |
|
||||
| M-CORE-05 | P2; M-CORE-01 | Add TypeMap reference access, checked sequence exhaustion and useful list diagnostics; no service/runtime dependency and no implicit copy on reference lookup. | sol_implementer |
|
||||
| M-CORE-06 | P2; M-CORE-02–05 | Publish compatibility headers and independent-header consumers; Core-only static/shared installed consumers and reflection-enabled/disabled configurations satisfy the package gate. | sol_implementer |
|
||||
|
||||
## Resource and performance gates
|
||||
|
||||
UUID parse/format and checked bits allocate zero bytes. `v5_lite` retains existing output
|
||||
fixtures but gets an allocation-free incremental implementation only if byte-for-byte
|
||||
compatibility is proved; no collision-resistance claim follows. TypeMap's NEW bounded
|
||||
constructor defaults to 256 distinct types and rejects additional admissions; explicit
|
||||
unbounded construction is separate. Lazy wrappers retain one result and one factory;
|
||||
no histories, queues, shutdown work, or background timers exist.
|
||||
|
||||
Measure fixed-size UUID batches, type-list compiler cost at 16/64/256 types, Meta formatting
|
||||
at shallow/deep aggregates, and contended first lazy access. Follow
|
||||
[PERFORMANCE](../PERFORMANCE.md) for p50/p95/p99, throughput, allocations, RSS/CPU and
|
||||
build cost. Report entropy acquisition separately from UUID masking/formatting.
|
||||
|
||||
## Validation, compatibility and rollback
|
||||
|
||||
CURRENT checks are the source suites linked above and the parent-recorded baseline;
|
||||
this planning task ran no C++ checks. PROPOSED checks require M-CORE-06 consumers and
|
||||
the supported C++26 toolchain: independent headers, ODR across two shared objects,
|
||||
sanitizers for lifetime paths, TSAN for LazySync, and fixed hash/UUID fixtures. Include
|
||||
malformed hyphens, uppercase hex, nil UUIDs, throwing entropy, bit width 0/width/width+1,
|
||||
throwing guard moves and factories that fail once then succeed.
|
||||
|
||||
Migration follows [MIGRATION](../MIGRATION.md) and
|
||||
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md). Keep `v5_lite` as a visibly legacy
|
||||
nonstandard operation; never reinterpret persisted IDs as standards-compliant v5.
|
||||
Rollback is an old-version package/header selection with the same persisted UUID bytes.
|
||||
Do not publish the new major until downstream Core-only consumers and optional
|
||||
Functional formatting bridges pass [VALIDATION](../VALIDATION.md). The
|
||||
[requirements](../REQUIREMENTS.md), [dependencies](../DEPENDENCIES.md) and
|
||||
[delivery plan](../DELIVERY.md) own cross-module scope and sequencing.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Crypto implementation plan
|
||||
|
||||
Status: planning only; all tasks PLANNED. Source baseline
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Applies [requirements](../REQUIREMENTS.md) R-004, R-006, R-012, R-014–R-016 and
|
||||
[architecture](../ARCHITECTURE.md) C-02, C-03, C-07, C-13.
|
||||
|
||||
## Existing primitive surface
|
||||
|
||||
[Crypto.hpp](../../../include/Void/Crypto/Crypto.hpp) declares `Void::Crypto::Hasher`,
|
||||
`Digest`, SHA-1/256/512 helpers, file hashing and `verifyEd25519` with fixed 32-byte public
|
||||
keys and 64-byte signatures. [Crypto.cpp](../../../src/Crypto/Crypto.cpp) uses OpenSSL EVP
|
||||
contexts with RAII. Incremental hashers are move-only; use after move/finalize is an
|
||||
error. File hashing streams a 64 KiB buffer. Ed25519 verification uses exact message
|
||||
bytes: malformed sizes are errors, well-formed invalid signatures return false.
|
||||
[module.cmake](../../../src/Crypto/module.cmake) declares Functional and OpenSSL::Crypto.
|
||||
|
||||
[Tests](../../../tests/standalone/Crypto/Crypto.cpp) cover known SHA vectors, streamed/file
|
||||
equivalence, rejected update after finalize and an RFC 8032 Ed25519 vector with modified
|
||||
message rejection. They do not establish provider-failure handling, signing, key management,
|
||||
asynchronous file cancellation or broad malformed-key coverage. Graph metadata matched
|
||||
all four linked source paths with no recorded issue; source was also read directly.
|
||||
|
||||
## Responsibility and backend decision
|
||||
|
||||
Retain OpenSSL as the initial implementation of hashes and signatures. Native preference
|
||||
means Void-owned lifetime/error/stream interfaces and no public EVP types; it does not
|
||||
authorize original cryptographic algorithms. TLS certificate and connection policy belong
|
||||
to [Net](Net.md), authentication/session/authorization workflows to [Security](Security.md),
|
||||
signed document selection and exact-byte verification sequencing to [Update](Update.md).
|
||||
Crypto must not depend on those consumers, Storage, or Runtime.
|
||||
|
||||
Keep existing verification formats intact. NEW HMAC-SHA-256 and HKDF-SHA-256 are staged
|
||||
primitive additions through EVP, with separate known-answer and misuse tests; new signing
|
||||
is Ed25519 through an owning private-key handle. SHA-1 stays available only for explicit
|
||||
legacy interoperability; new security protocols select SHA-256 or stronger. No silent
|
||||
fallback if an algorithm/provider is unavailable. Provider configuration is injected per
|
||||
context; do not mutate process-wide OpenSSL state from a library constructor.
|
||||
|
||||
## NEW API shapes, algorithms and ownership
|
||||
|
||||
```cpp
|
||||
// NEW illustrative Void::Crypto shapes; Result is C-02 shorthand.
|
||||
class PrivateKey; // move-only opaque backend state, explicit import/generate
|
||||
struct Ed25519PublicKey { std::array<std::byte, 32> bytes; };
|
||||
struct Ed25519Signature { std::array<std::byte, 64> bytes; };
|
||||
Result<Ed25519Signature> sign_ed25519(ByteSpan exact_message, const PrivateKey&);
|
||||
Result<Digest> hmac_sha256(ByteSpan secret_key, ByteSpan message);
|
||||
Result<void> hkdf_sha256(ByteSpan secret_input, ByteSpan salt,
|
||||
ByteSpan context, MutableByteSpan secret_output);
|
||||
// Optional IO adapter, not a new executor or OperationOptions definition:
|
||||
Task<Result<Digest>> hash_stream(HashAlgorithm, IOByteReader&, OperationOptions);
|
||||
```
|
||||
|
||||
Byte-span and reader names above denote proposed owner-provided shapes, not existing aliases.
|
||||
[Memory](../subsystems/Memory.md) owns resource integration. Callers may supply Security's
|
||||
secure buffer through spans; Crypto does not import the authentication module or allocate
|
||||
a general-purpose secret result type. HKDF fills the caller-owned destination, wipes it
|
||||
on failure and rejects overlapping input/output. Primitive APIs borrow inputs until
|
||||
the synchronous call returns; async adapters retain owned buffers through IO completion.
|
||||
PrivateKey has no implicit copy/export/string conversion. Import uses an explicitly
|
||||
named encoding and validates algorithm/size; public export and secret export are separate
|
||||
capabilities. Secret export requires explicit caller intent and a secure owning result.
|
||||
|
||||
Hasher state is Ready → Updating → Finalized or Failed. Backend update/finalize failure
|
||||
poisons the context until destroyed; retrying a partially effective update is invalid.
|
||||
Hash-stream reads at most 64 KiB, updates, checks stop/deadline between chunks, finalizes
|
||||
only at clean EOF and never treats a short failed read as success. Descriptor close or
|
||||
concurrent path replacement has the IO-defined result; hashing a path does not promise
|
||||
a snapshot of a concurrently modified file. Update's downloader must pin its own artifact.
|
||||
|
||||
Signature operations do not prehash/reencode Ed25519 messages implicitly. Binary/text
|
||||
decoding is outside verification; [Data](Data.md)'s StrictJson rules and exact signed
|
||||
payload bytes remain unchanged under C-07. A successful primitive verification is not
|
||||
authorization, freshness, trust-root selection or replay protection.
|
||||
|
||||
NEW defaults: stream chunk 64 KiB, optional file adapter 8 concurrent operations and
|
||||
32 waiting, 8 MiB adapter buffer budget; oversized input is processed incrementally
|
||||
where the algorithm supports it. One-shot signing/verification initially limits messages
|
||||
to 16 MiB and directs larger formats to an explicitly specified signed-manifest design.
|
||||
The NEW HKDF API caps output at 4 KiB and also enforces the backend primitive's limit;
|
||||
invalid sizes fail before mutation. Error context contains operation/provider codes, never keys,
|
||||
passwords or plaintext. Output buffers are wiped on failed secret-producing operations.
|
||||
|
||||
## Failure matrix and evidence
|
||||
|
||||
| Fault | Required behavior | Acceptance scenario |
|
||||
| --- | --- | --- |
|
||||
| Bad key/signature size | Typed invalid input, no backend use | Every length near expected boundary |
|
||||
| Wrong message/key/signature | Successful false verification | Altered bytes and independent vectors |
|
||||
| Algorithm unavailable / provider error | Unsupported/backend error; no downgrade | Inject provider failures per operation |
|
||||
| Hash context fails midway | Failed terminal state, cannot reuse | Update/finalize/move sequences |
|
||||
| File read error / cancellation | No digest success; one terminal result | Partial read then error, stop at EOF race |
|
||||
| Allocation/admission failure | Resource error before secret output publication | Budget exhaustion with no retained secret |
|
||||
| Async shutdown | Stop admission, stop/join readers, destroy contexts last | Caller buffers cannot escape completion |
|
||||
|
||||
## Task DAG
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-CRYPTO-01 | P0; baseline | Preserve existing vectors and exact-byte false-vs-error behavior; record consumers before API migration | sol_implementer |
|
||||
| M-CRYPTO-02 | P1; M-CRYPTO-01, Functional/Memory contracts | Typed size wrappers, poisoned-state/error handling and provider isolation; malformed/state tests pass | astra_implementer |
|
||||
| M-CRYPTO-03 | P2; M-CRYPTO-02 | Owning Ed25519 private key/signing, HMAC/HKDF with caller-owned output; independent known-answer vectors and no secret diagnostics | astra_implementer |
|
||||
| M-CRYPTO-04 | P2; M-CRYPTO-02, IO/Async gates | Optional hash-stream/file adapter, bounded cancellation and workload accounting; no mandatory runtime dependency | sol_implementer |
|
||||
| M-CRYPTO-05 | P3; M-CRYPTO-03, M-CRYPTO-04 | Signed-update integration fixtures, component consumers and resource profiles; exact signed bytes unchanged | astra_implementer |
|
||||
| M-CRYPTO-06 | P4; M-CRYPTO-05, distributed consumers | Snapshot/transport integrity recipes distinguish checksums, authenticated channels and trusted signatures | sol_implementer |
|
||||
|
||||
## Verification and migration
|
||||
|
||||
CURRENT checks are the linked Crypto tests in VoidTests; no build/test was rerun for
|
||||
this documentation task. PROPOSED tests add backend fault injection, independent vector
|
||||
corpora, secret lifetime tests, file mutation/short-read cases, fuzzed imports and sanitizer
|
||||
coverage. Backend-version testing follows [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md);
|
||||
the OpenSSL 3.5 [client guide](https://docs.openssl.org/3.5/man7/ossl-guide-tls-client-block/)
|
||||
informs Net TLS policy, not a claim about the currently linked version or FIPS certification.
|
||||
|
||||
Measure small-message setup separately from large streaming throughput, with p50/p95/p99,
|
||||
allocations, RSS/CPU and build cost under [PERFORMANCE](../PERFORMANCE.md). No native
|
||||
replacement is justified by speculative speedups. [VALIDATION](../VALIDATION.md) defines
|
||||
future runner prerequisites; do not invent a presently available signing target.
|
||||
|
||||
Major-release evolution adds typed overloads and consistent naming with adapters for
|
||||
existing camelCase entry points. Preserve SHA digest bytes, file semantics and Ed25519
|
||||
verification outcome distinction. Never reinterpret old signatures with a new framing
|
||||
scheme. Rollback retains readable key/algorithm formats and the previous backend adapter;
|
||||
unsupported new algorithms fail explicitly. See [MIGRATION](../MIGRATION.md).
|
||||
@@ -0,0 +1,183 @@
|
||||
# Data values, parsing and schema evolution
|
||||
|
||||
Status: planning only; feature tasks are **PLANNED**. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing source and protected profile
|
||||
|
||||
[Data](../../../src/Data/module.cmake) declares Time; its reflection/CSV headers also
|
||||
include Core. [Json](../../../include/Void/Data/Json.hpp) implements `Void::Json::Value`
|
||||
with null/bool/double/string and boxed vectors for arrays/ordered object pairs. Integer
|
||||
constructors convert to double; `as_int()` casts from it. General parsing returns
|
||||
`std::expected<Value, ParseError>` with line/column diagnostics, retains duplicate object
|
||||
pairs, provides JSON pointer access, SAX callbacks and serialization. SAX numeric
|
||||
callbacks currently receive double. Exact 64-bit integers require a representation
|
||||
change, not just a new accessor.
|
||||
|
||||
[Reflect](../../../include/Void/Data/Reflect.hpp) serializes C++26-reflected values,
|
||||
annotations, containers, variants and chrono values, and has `MigrationChain` plus
|
||||
versioned envelopes. [Csv](../../../include/Void/Data/Csv.hpp) exposes allocating Row/
|
||||
Table parsing and reflection conversion; current parse returns a Table without malformed-
|
||||
quote diagnostics. [Ini](../../../include/Void/Data/Ini.hpp) handles sections, values,
|
||||
mutation and serialization. Neither is a full configuration policy engine.
|
||||
|
||||
[StrictJson](../../../include/Void/Data/StrictJson.hpp) is a separate namespace/type:
|
||||
`Void::Json::Strict::Value` uses signed int64, ordered maps and restricted parsing.
|
||||
[StrictJson tests](../../../tests/standalone/Data/StrictJson.cpp) require exact signed
|
||||
64-bit endpoints and reject duplicates, floats, excessive nesting and lone surrogates.
|
||||
**C-07 prohibits broadening this profile through general Data improvements.** Existing
|
||||
[Update envelope parsing](../../../src/Update/Feed.cpp) uses general Json, not StrictJson;
|
||||
schema 3 parses payload bytes for readable-document comparison before verifying their
|
||||
signature. [Update](Update.md) explicitly plans moving that comparison after verification
|
||||
and preserving a versioned legacy parsing profile. Verification before payload parsing is
|
||||
the target contract; no general serializer becomes a replacement signing input. Existing
|
||||
signed documents remain compatibility fixtures.
|
||||
|
||||
[General JSON](../../../tests/standalone/Data/Json.cpp),
|
||||
[query/SAX](../../../tests/standalone/Data/JsonQuery.cpp),
|
||||
[accessors](../../../tests/standalone/Data/JsonAccessors.cpp),
|
||||
[reflection](../../../tests/standalone/Data/Reflect.cpp),
|
||||
[annotations](../../../tests/standalone/Data/ReflectAnnotations.cpp),
|
||||
[chrono](../../../tests/standalone/Data/ReflectChrono.cpp),
|
||||
[CSV](../../../tests/standalone/Data/Csv.cpp),
|
||||
[CSV reflection](../../../tests/standalone/Data/CsvReflect.cpp), and
|
||||
[INI](../../../tests/standalone/Data/Ini.cpp) are current test sources. Partial graph
|
||||
ranges Json 243/1090 and Reflect 595 were read directly. The graph's reflection call
|
||||
edges include heuristic matches; source, not those edges, establishes type behavior.
|
||||
|
||||
## Target ownership and backend rationale
|
||||
|
||||
Keep the native DOM/scanners/reflection implementation. Data owns structured values,
|
||||
general parsing policies, schema envelopes and migration; [Binary](Binary.md) owns
|
||||
encoding primitives. [Math](Math.md) owns checked numeric conversions; Data may depend
|
||||
downward on its small Numeric header. [Unicode](../subsystems/Unicode.md) is an explicit
|
||||
validation/normalization adapter, never a hidden signed-data transform. Functional owns
|
||||
common classifications and adapters for Data's path-aware domain errors. No optional
|
||||
third-party JSON engine becomes a foundation requirement. Dependencies are declared and
|
||||
independently tested, including Core and Time, under [C-01/C-07](../ARCHITECTURE.md).
|
||||
|
||||
## NEW value representation and checked conversion
|
||||
|
||||
Illustrative NEW members on `Void::Json::Value`, not current compiling API:
|
||||
|
||||
```cpp
|
||||
namespace Void::Json {
|
||||
enum class NumberKind { signed_integer, unsigned_integer, real };
|
||||
// Value backing alternatives add int64_t and uint64_t alongside double.
|
||||
// NumberKind Value::number_kind() const;
|
||||
template<class T> std::expected<T, ConversionError> number_as(const Value&);
|
||||
enum class DuplicateKeys { reject, first_wins, last_wins, preserve };
|
||||
struct ParseOptions {
|
||||
DuplicateKeys duplicate_keys = DuplicateKeys::reject;
|
||||
std::size_t max_input_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_owned_bytes = 64 * 1024 * 1024;
|
||||
std::size_t max_string_bytes = 1024 * 1024;
|
||||
std::size_t max_nodes = 1000000;
|
||||
unsigned max_depth = 64;
|
||||
};
|
||||
std::expected<Value, ParseError> parse(std::string_view, ParseOptions);
|
||||
}
|
||||
```
|
||||
|
||||
Signed integer tokens in range become int64; nonnegative integers above INT64_MAX but
|
||||
within UINT64_MAX become uint64. Integers outside both ranges fail rather than round
|
||||
through double. Decimal/exponent tokens become finite double, with conversion range
|
||||
errors reported. Arbitrary-precision decimals are outside the first value milestone;
|
||||
a later named decimal capability requires a separate representation/schema decision.
|
||||
Numeric lexemes are limited to 256 bytes. General parsing validates full grammar,
|
||||
UTF-8 and escaped scalar pairs, and rejects trailing junk. Integer `-0` becomes integer
|
||||
zero; floating negative zero retains sign and serializes as `-0.0`. Lexical preservation
|
||||
is a separate borrowed raw-document facility, not a promise of the DOM.
|
||||
|
||||
`number_as<T>` delegates exact/range logic to Numeric and adds the document path.
|
||||
Default integer-to-double conversion rejects inexactness; named lossy conversion is
|
||||
explicit. Equality compares integral alternatives exactly with signedness checks;
|
||||
integer/real equality is true only when the real is finite, integral and exactly matches
|
||||
the integer. It never first converts UINT64_MAX to double. Typed wrong-kind access
|
||||
reports an error; legacy throwing accessors remain adapters during the major migration.
|
||||
|
||||
Objects retain insertion order in vector pairs. Duplicate detection uses a temporary
|
||||
key index charged to the owned-byte/node budget. Default reject avoids ambiguous lookup;
|
||||
preserve exposes a multi-member API and requires an explicit occurrence policy for
|
||||
lookup/pointer traversal. first/last-wins are deterministic named compatibility profiles.
|
||||
Keys compare decoded bytes; normalization/case folding is never implicit. Programmatic
|
||||
construction and serialization enforce the same duplicate/finite-number rules selected
|
||||
for output. Stable pretty output is not a security canonicalization standard.
|
||||
|
||||
## Streaming, tables and ownership
|
||||
|
||||
Unify DOM and SAX grammar scanning with typed numeric events (`int64`, `uint64`, `double`).
|
||||
NEW incremental parser owns incomplete tokens, uses at most the configured 1 MiB token
|
||||
buffer, and reports consumed/need-more/completed/error states. Callback string views
|
||||
expire at callback return; an explicit owned-event mode copies within budget. Callbacks
|
||||
may stop parsing with an error/stop result. Check a supplied stop token between tokens
|
||||
and every 4 KiB inside long strings; no Async dependency or worker is introduced.
|
||||
Earlier SAX events remain observed after failure; a DOM result publishes only on full
|
||||
success. Input plus owned output, key indexes, parser stack and migration scratch all
|
||||
count toward explicit resource accounting; allocator overhead is reported separately.
|
||||
|
||||
CSV gets an incremental quoted-field state machine with exact malformed-quote offsets,
|
||||
CRLF/LF policy, delimiter selection and defaults of 65,536 rows, 1,024 columns and 1 MiB
|
||||
per field within 16 MiB input/64 MiB owned bytes. Empty final rows and embedded line breaks
|
||||
have explicit fixtures. Row conversion reports column/name/type errors, not a blanket
|
||||
nullopt. INI gets deterministic serialization, duplicate section/key policies (reject
|
||||
by default in NEW strict mode), escaped-value rules, and the same byte bounds with
|
||||
65,536 keys. Configuration owns overlays, environment expansion and secret policy.
|
||||
|
||||
Reflection decoding selects strict unknown-field rejection or an explicit ignore mode,
|
||||
honors required/default/rename annotations and uses exact numeric conversions. Depth and
|
||||
owned-byte budgets cover reflected containers too. MigrationChain validates a contiguous
|
||||
version path before applying it; run each step on owned candidate data, cap at 32 steps,
|
||||
and publish only after final validation. Migration failure never partially mutates the
|
||||
caller's original value. No claim of database transactionality follows from this local
|
||||
strong exception guarantee.
|
||||
|
||||
## NEW native binary value codec
|
||||
|
||||
Select **VoidValueBinary V1** in NEW `include/Void/Data/ValueBinary.hpp`, with no claimed
|
||||
CBOR/MessagePack compatibility. Envelope: four literal bytes `VVB1`, one flags byte
|
||||
(must be zero), then one value. Tags: 0 null, 1 false, 2 true, 3 ZigZag int64, 4 uvarint
|
||||
uint64, 5 little-endian IEEE binary64, 6 length-prefixed UTF-8 string, 7 array count plus
|
||||
values, 8 object pair count plus string keys/values. Varints are minimal. Reject nonfinite
|
||||
floats, unknown tags/flags, duplicate keys in strict mode and trailing bytes. Preserve
|
||||
array/object order; canonical signing is not part of V1. Defaults reuse Data budgets;
|
||||
validate counts before reserve. Schema transport adds a Data-owned type ID and version
|
||||
inside an explicit envelope value; RPC/Storage independently own their framing/durability.
|
||||
|
||||
## Ordered backlog
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-DATA-01 | P0; current source | Freeze general/StrictJson behavior and signed fixture boundaries; map Data includes and every numeric consumer before a representation break. | astra_implementer |
|
||||
| M-DATA-02 | P1; M-MATH-02; M-DATA-01 | Add exact signed/unsigned representation and checked access/equality; endpoints and 2^53±1 survive parse/serialize/reflection without silent rounding. | astra_implementer |
|
||||
| M-DATA-03 | P2; M-DATA-02; Functional/Memory bounded-error/resource gates | Implement explicit general JSON limits/duplicate policies and transactional DOM publication; adversarial inputs cannot bypass aggregate budgets. | sol_implementer |
|
||||
| M-DATA-04 | P2; M-DATA-03 | Share scanner with typed SAX/incremental modes; all chunk splits match DOM grammar and callbacks never retain temporary views. | sol_implementer |
|
||||
| M-DATA-05 | P2; M-DATA-02–03 | Complete reflection strictness, annotation diagnostics and bounded migration; failed version step preserves input and missing paths fail before execution. | sol_implementer |
|
||||
| M-DATA-06 | P2; M-DATA-03 | Complete CSV/INI streaming/errors/deterministic output and typed rows; quote, duplicate, field-limit and rollback fixtures pass. | sol_implementer |
|
||||
| M-DATA-07 | P3; M-BINARY-04; M-DATA-03/05 | Implement VVB1 with golden byte fixtures and versioned value envelope; unknown formats reject and resource limits match JSON. | sol_implementer |
|
||||
| M-DATA-08 | P3; M-DATA-04–07; protected Update/Security fixture gate | Publish migration and installed consumers; signed documents retain their exact acceptance profile and no signature uses reserialized bytes. | astra_implementer |
|
||||
|
||||
## Validation, migration and rollback
|
||||
|
||||
CURRENT evidence is the inspected suites and parent baseline; no build/test/fuzz run was
|
||||
performed for these documents. PROPOSED tests cover INT64_MIN/MAX, UINT64_MAX, oversized
|
||||
integers, inexact casts, malformed exponents/UTF-8/surrogates, every duplicate mode,
|
||||
deep/wide trees, escaped pointer keys, callback stop, chunk splits, allocation failure,
|
||||
CSV quote state and interrupted migration. Keep a separate protected StrictJson fixture
|
||||
set: general uint64/float/duplicate policies must not alter it. Cross-check VVB1 against
|
||||
handwritten golden bytes, not only its own round trips.
|
||||
|
||||
Workload profiles include small config DOMs, 16 MiB tables, deep rejection, integer-heavy
|
||||
messages and streaming scans. Measure p50/p95/p99, throughput, allocation count/bytes,
|
||||
peak RSS/CPU and reflection build cost through [PERFORMANCE](../PERFORMANCE.md).
|
||||
No throughput improvement or compiler support is claimed without that evidence.
|
||||
|
||||
[Migration](../MIGRATION.md) groups Value layout, number kind, default duplicate policy,
|
||||
typed SAX events and reflection strictness into the major release. Preserve old general
|
||||
parser behavior only in a named legacy adapter; StrictJson stays separate and unchanged.
|
||||
Deploy VVB1 readers before enabling writers, retain old-format fixtures/readers and never
|
||||
rewrite signed payloads in place. Rollback disables new-format writes; applications must
|
||||
retain a readable prior-format copy before persisted migration. See
|
||||
[VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
|
||||
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
|
||||
[Update](Update.md) and [Security](Security.md) for integration gates.
|
||||
@@ -0,0 +1,168 @@
|
||||
# Fsm structured workflows and checkpoint plan
|
||||
|
||||
Status: PLANNED feature work. Source baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`,
|
||||
inspected 2026-11-24. Requirements R-002, R-009, R-010, R-014 and R-015 apply.
|
||||
Follow [architecture](../ARCHITECTURE.md) C-03–C-05, C-09, C-10 and C-13.
|
||||
|
||||
## Existing source baseline
|
||||
|
||||
[Machine.hpp](../../../include/Void/Fsm/Machine.hpp) implements
|
||||
`Void::Fsm::Machine<R>`, signature/reflection-driven states, entry/exit hooks, typed
|
||||
outcomes, event waits, hierarchy/history, submachines, parallel regions, race-any,
|
||||
pause/restart/jump and JSON serialization. `serialize()` records a named state plus
|
||||
application `on_serialize` data; `restore` requires Idle and invokes `on_restore`.
|
||||
It does not save suspended coroutine stacks. `run_parallel_any` explicitly leaves
|
||||
losers running; a permanently parked loser can retain a frame until stop.
|
||||
|
||||
[StateKey.hpp](../../../include/Void/Fsm/StateKey.hpp) defines `StateKey`, `FsmError`,
|
||||
`LaunchResult` and statuses Idle/Running/Succeeded/Failed/Faulted. Machine::finished
|
||||
includes Faulted, but [Orchestrator.hpp](../../../include/Void/Fsm/Orchestrator.hpp)
|
||||
FsmHandle::finished currently checks only Succeeded/Failed. Despite its non-owning
|
||||
comment, FsmHandle stores a shared_ptr to its model; migration must clarify ownership
|
||||
from the source rather than repeat the comment.
|
||||
|
||||
[Engine.hpp](../../../include/Void/Fsm/Detail/Engine.hpp) and
|
||||
[Engine.cpp](../../../src/Fsm/Engine.cpp) contain a shared executor/event mailbox/timer
|
||||
substrate, optional owning worker and embedder pumping. Nested machines share that
|
||||
substrate. [module.cmake](../../../src/Fsm/module.cmake) declares Async, Data,
|
||||
Functional, Log and Service. NEW execution continues to depend on Async and optional
|
||||
Service access, never on managed Runtime or Scheduler.
|
||||
|
||||
Existing fixtures include [basic pumping](../../../tests/standalone/Fsm/Basic.cpp),
|
||||
[events](../../../tests/standalone/Fsm/Events.cpp),
|
||||
[parallel regions](../../../tests/standalone/Fsm/Parallel.cpp),
|
||||
[policies](../../../tests/standalone/Fsm/Policies.cpp),
|
||||
[hierarchy](../../../tests/standalone/Fsm/Hierarchy.cpp),
|
||||
[history](../../../tests/standalone/Fsm/History.cpp), and
|
||||
[serialization](../../../tests/standalone/Fsm/Serialize.cpp). These remain regression
|
||||
inputs. Graph coverage was checked; Parallel/Direct constructor gaps were directly
|
||||
read. Source inspection establishes the terminal-status and race-loser gaps.
|
||||
|
||||
## NEW execution and supervision contract
|
||||
|
||||
Design sketch; additions are not available APIs:
|
||||
|
||||
```cpp
|
||||
namespace Void::Fsm {
|
||||
struct Checkpoint {
|
||||
std::uint32_t format_version;
|
||||
std::string machine_type;
|
||||
std::uint32_t application_schema;
|
||||
std::uint64_t transition_sequence;
|
||||
Json::Value state; // stable state IDs + app data
|
||||
};
|
||||
// Machine additions:
|
||||
// run(execution_binding, Async::OperationOptions) -> Task<Result<Outcome>>;
|
||||
// request_checkpoint(options) -> Task<Result<Checkpoint>>;
|
||||
// restore_checkpoint(const Checkpoint&) -> Result<void>; // Idle only
|
||||
// post(Event, options) -> Result<void>; // bounded admission
|
||||
// terminal(Status) -> bool; // one shared predicate
|
||||
}
|
||||
```
|
||||
|
||||
Execution binding borrows Async executor/scope and Time clock contracts. Keep it
|
||||
Fsm-specific binding data, not another cancellation/deadline context; all public
|
||||
operations use `Async::OperationOptions`. Machine state runs on one logical strand.
|
||||
Cross-thread posts enqueue owned event envelopes; only that strand mutates active
|
||||
state, timers, waiters and transition history. Service lookups return owning handles
|
||||
retained across await, per [Service](Service.md).
|
||||
|
||||
Machine has a root Async scope and each entered state has a child scope. Exit first
|
||||
closes state-event admission, requests child stop, joins child work, removes waiters
|
||||
and timers, then runs bounded exit cleanup and enters the next state. No queued
|
||||
resume targets a destroyed state. A failed exit cleanup faults the machine after
|
||||
joining all remaining scopes. Stop has a separate completion reason; the first
|
||||
version retains existing Status values and adds `termination_reason` rather than
|
||||
silently treating cancellation as application success or introducing unreviewed enum
|
||||
values. Terminal predicate includes Faulted everywhere.
|
||||
|
||||
Parallel-all joins every child before producing the outcome tuple; a system fault
|
||||
requests sibling stop and joins before returning the fault. Parallel-any selects one
|
||||
winner on the machine strand, requests stop for all losers and awaits their joins
|
||||
before returning the winner. Simultaneous-ready ties use child declaration order in
|
||||
the same dispatch turn. Application Failure remains a typed outcome and can win a
|
||||
race; system Fault remains a separate supervisory failure. Stop/deadline uses Async's
|
||||
one-terminal arbitration. A noncooperative loser delays completion and is reported;
|
||||
its frame is never abandoned to meet a latency target.
|
||||
|
||||
Supervision policies are explicit: default stop-on-fault; optional bounded restart
|
||||
with Time-driven backoff, maximum three restarts per 60-second window, and 1,024
|
||||
supervised machines. A faulted child is terminal in handles/counts/waits. Release
|
||||
finished models from active supervision while acquired handles retain immutable
|
||||
termination evidence and any still-required cleanup ownership. User observer callbacks
|
||||
run outside orchestration locks; their exceptions report observer errors independently
|
||||
from the machine's committed transition.
|
||||
|
||||
## Checkpoint algorithm and state compatibility
|
||||
|
||||
Checkpoints capture state boundaries: after the prior state's child scope and exit
|
||||
cleanup finish, before the next state's entry causes new effects. A parked state may
|
||||
offer an explicit application safe point that drains child work and serializes its
|
||||
resume label. No arbitrary suspension point is implicitly restartable. A request
|
||||
that cannot reach a boundary before its deadline fails without copying a live frame.
|
||||
|
||||
On the strand, freeze event consumption, assign a transition sequence, copy application
|
||||
data and stable state paths/history into a bounded candidate, validate its schema,
|
||||
then release the freeze. Optional queued events are persisted only through an explicit
|
||||
registered serializable event schema and acknowledgement sequence; default checkpoint
|
||||
excludes the mailbox and requires producer replay/deduplication. Relative monotonic
|
||||
timers are application intent with restart policy, never raw process clock readings.
|
||||
|
||||
Default checkpoint contains format version, machine identity, application schema,
|
||||
stable state IDs and transition sequence. State IDs are declared durable names, not
|
||||
compiler type-name spellings. Restore validates all IDs/schema/limits into a private
|
||||
Idle machine and commits its prepared state once; invalid data or migration exceptions
|
||||
leave it unchanged. Resume executes state entry from the selected boundary. Application
|
||||
side effects require idempotent occurrence/operation IDs or an external transaction;
|
||||
checkpointing does not promise exactly-once effects. [Scheduler](../subsystems/Scheduler.md)
|
||||
owns durable job occurrences; Fsm owns their workflow state.
|
||||
|
||||
## Bounds and backend rationale
|
||||
|
||||
Initial implementation remains native C++ coroutines/reflection and reuses Async
|
||||
structured scopes. No external workflow engine. Default mailbox 1,024 events/4 MiB,
|
||||
256 deferred events, 1,024 timers, 128 live child regions, hierarchy depth 32, 256
|
||||
retained transitions and checkpoint 4 MiB. Event types must provide payload accounting
|
||||
for variable data. Overload is returned before enqueue; reserved control messages
|
||||
ensure stop/checkpoint can progress under user-event saturation. Control capacity is
|
||||
bounded by live scopes and requests, not an unbounded priority queue.
|
||||
|
||||
One dispatch turn processes at most 64 events or 1 ms measured by injected Time before
|
||||
yielding; tests use event counts to avoid real-clock flakiness. Expired waiters are
|
||||
removed before state destruction. Low-level hooks remain optional so Fsm does not
|
||||
require an observability exporter or Runtime. Profile tick/transition/race/checkpoint
|
||||
p50/p95/p99, throughput, frame/event allocations, peak RSS/CPU and reflection compile
|
||||
cost under [PERFORMANCE](../PERFORMANCE.md); no results are asserted.
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
All rows are PLANNED.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-FSM-01 | P0 / current source | Characterize status, supervision ownership, event waits and race losers | Faulted discrepancy and indefinitely parked race fixture recorded; no claim of safe cancellation / sol_implementer |
|
||||
| M-FSM-02 | P1 / M-FSM-01; M-ASYNC-03 | Inject executor/clock, root/state scopes, waiter/timer ownership | Stop at each suspension frees only after join; borrowed execution outlives final cleanup / astra_implementer |
|
||||
| M-FSM-03 | P2 / M-FSM-02; M-SERVICE-02 | Structured parallel/race, terminal predicate, bounded mailbox/history and supervision | Losers stopped/joined; faults terminate all handle/wait APIs; old provider survives await / astra_implementer |
|
||||
| M-FSM-04 | P2 / M-FSM-03; Data schema gate | Boundary checkpoint, stable state IDs, validate-then-restore and schema migrations | Checkpoint during mutation waits for safe point; invalid restore leaves Idle candidate unchanged / astra_implementer |
|
||||
| M-FSM-05 | P3 / M-FSM-04; Plugin quiescence specification | Reloadable workflow adapter, restart policies, examples and profile harness | Reload migrates application state without frames; fault/restart cap and cleanup evidence visible / sol_implementer |
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT command:
|
||||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||||
not rerun for documentation. PROPOSED tests require NEW scope/checkpoint APIs: race
|
||||
winner with forever-waiting cooperative loser, fault during child exit, timeout versus
|
||||
event delivery, queued timer after state exit, nested cancellation, event saturation,
|
||||
observer reentrancy/throw, Faulted supervision, checkpoint/transition simultaneity,
|
||||
schema migration failure, and restart after effects with operation-ID deduplication.
|
||||
Use fake clocks and deterministic strand stepping before sanitizer stress runs.
|
||||
|
||||
Keep existing state declaration/reflection syntax where possible. EXISTING
|
||||
`MachineOptions{.own_worker=false}` maps to explicit injected execution; owning worker
|
||||
construction becomes an opt-in adapter. JSON `{state,data}` gets an explicit legacy
|
||||
checkpoint reader with declared machine/schema defaults; unknown compiler-derived
|
||||
state names require a migration map. Old race-any behavior is documented until the
|
||||
major-release switch to join-losers; no silent semantic change. Rollback preserves
|
||||
legacy readers and the original persisted checkpoint until the new version validates.
|
||||
See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), and [DELIVERY](../DELIVERY.md).
|
||||
@@ -0,0 +1,150 @@
|
||||
# Functional completion and error contracts
|
||||
|
||||
Status: planning only; feature tasks are **PLANNED**. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing surface
|
||||
|
||||
[Result.hpp](../../../include/Void/Functional/Result.hpp) defines
|
||||
`Void::Result::Result<T, E = Error>` as `std::expected<T,E>`, with `Failure`, `ok`,
|
||||
`fail` and `with_context`. [Error](../../../include/Void/Functional/Error.hpp) stores
|
||||
a message and shared immutable cause chain; it has no current machine-readable category.
|
||||
Keep the standard expected monadic operations rather than wrapping them in a new result
|
||||
class. Existing namespace facts also include `Void::Either` for
|
||||
[Either](../../../include/Void/Functional/Either.hpp) and
|
||||
[Opt](../../../include/Void/Functional/Opt.hpp), and `Void::Pipeline` for
|
||||
[Pipeline](../../../include/Void/Functional/Pipeline.hpp),
|
||||
[Curry](../../../include/Void/Functional/Curry.hpp) and
|
||||
[Memo](../../../include/Void/Functional/Memo.hpp).
|
||||
|
||||
[Retry](../../../include/Void/Functional/Retry.hpp) has delay policies, jitter and a
|
||||
steady elapsed budget, but sleeps synchronously and uses zero for unlimited elapsed
|
||||
time. Its zero-attempt path can return a default-constructed result without calling the
|
||||
operation. `Memoized::get_cache()` uses a function-local static map, so instance ownership
|
||||
and concurrency need deliberate migration. The reflection
|
||||
[diagnostic bridge](../../../include/Void/Functional/Detail/Repr.hpp) includes Core Meta,
|
||||
while [the module declaration](../../../src/Functional/module.cmake) lists no dependency.
|
||||
[Result tests](../../../tests/standalone/Functional/ResultContext.cpp),
|
||||
[memo tests](../../../tests/standalone/Functional/Memo.cpp),
|
||||
[retry tests](../../../tests/standalone/Functional/Retry.cpp), and
|
||||
[jitter tests](../../../tests/standalone/Functional/RetryJitter.cpp) establish useful
|
||||
fixtures. Scoped graph coverage reported no recorded parser gaps here; source was also
|
||||
read because graph cleanliness is not completeness evidence.
|
||||
|
||||
## Owner and dependency decisions
|
||||
|
||||
Functional owns error categories and exception/domain adapters under
|
||||
[C-02](../ARCHITECTURE.md). It imports no Async, Runtime, Log or Containers. Core stays
|
||||
below Functional; optional reflection formatting has the NEW interface target
|
||||
`Void::FunctionalCoreFormatting`, exporting Functional and Core dependencies. Its
|
||||
headers never create a reverse Core→Functional bridge; base `Void::Functional` retains
|
||||
no Core requirement. Time owns clocks; Functional's pure retry
|
||||
decision engine accepts times as values and never owns a timer. Async/Resilience own
|
||||
asynchronous waiting, task cancellation and policy composition above this layer.
|
||||
Native templates plus standard expected/optional/variant are the backend. No external
|
||||
functional framework or general policy runtime is justified.
|
||||
|
||||
## NEW error shape and adapters
|
||||
|
||||
These illustrative NEW additions extend `include/Void/Functional/Error.hpp` and add
|
||||
NEW `include/Void/Functional/Adapters.hpp`; existing `Result<T>` remains an alias.
|
||||
|
||||
```cpp
|
||||
namespace Void::Result {
|
||||
enum class ErrorKind {
|
||||
invalid_argument, not_found, conflict, cancelled, timeout, overloaded,
|
||||
unsupported, io, corrupt, exhausted, internal
|
||||
};
|
||||
struct ErrorCode { std::uint32_t domain; std::int32_t value; };
|
||||
// Compact failure descriptor; expected's value branch represents success.
|
||||
struct Status { ErrorKind kind; ErrorCode code; };
|
||||
// NEW members on Error:
|
||||
// explicit Error(Status) noexcept; // no diagnostic allocation
|
||||
// ErrorKind kind() const noexcept;
|
||||
// ErrorCode code() const noexcept;
|
||||
// std::error_code system_code() const noexcept;
|
||||
// Error with_context(std::string) const&;
|
||||
template<class T, class E, class Map>
|
||||
Result<T> adapt(std::expected<T,E>, Map&& map_error);
|
||||
template<class F, class Map>
|
||||
auto try_invoke(F&&, Map&& map_exception);
|
||||
}
|
||||
```
|
||||
|
||||
The library reserves domain 0 for generic classifications; domain numeric registration
|
||||
is documented by Functional, not generated by hashing type names. Preserve domain code,
|
||||
system code, root category and causes through context wrapping. Human strings are never
|
||||
parsed to decide retryability. Old `Error(string)` maps to `internal` with an unspecified
|
||||
domain code; callers should migrate to typed construction. Domain errors such as
|
||||
`Numeric::Error` may remain small enums and use explicit adapters at integration edges.
|
||||
`adapt` invokes its mapper only on failure and supports move-only values and `void`.
|
||||
|
||||
`try_invoke` catches only exceptions accepted by its caller-provided mapper; unrecognized
|
||||
exceptions rethrow. `std::bad_alloc` propagates by default. No automatic catch-all turns
|
||||
programmer errors into empty values. A C ABI adapter catches at its boundary and emits
|
||||
fixed status codes with explicitly owned diagnostic storage under C-09.
|
||||
|
||||
NEW error context limits default to 16 frames, 1 KiB per message and 16 KiB total rendered
|
||||
diagnostics. Truncation is visible and preserves the original classification. A compact
|
||||
`Status` carrying only kind/code provides an allocation-free boundary for Memory and
|
||||
low-memory paths; enriching it with strings is separate and fallible. Cause copying is
|
||||
immutable and bounded; destructor traversal must not recurse through unbounded chains.
|
||||
|
||||
## Pure retry and callable ownership
|
||||
|
||||
NEW `RetryState::next(now, last_error)` returns either `stop`, `attempt`, or an absolute
|
||||
next-attempt time. Defaults: three total attempts and a 30-second total budget; explicit
|
||||
`no_deadline` is required for unlimited time. Zero attempts is invalid. Backoff arithmetic
|
||||
saturates at a configured cap before overflow, rejects negative durations/nonfinite
|
||||
multipliers, and accepts an injected URBG for reproducible jitter. A stop request or
|
||||
expired admission deadline prevents the next attempt; the policy cannot interrupt an
|
||||
already-running callback or reverse its side effects. Retryability is a supplied
|
||||
predicate and retrying writes still requires the caller's idempotency contract.
|
||||
|
||||
Retain the synchronous `retry` adapter temporarily, explicitly named as blocking. A
|
||||
Time-clock/sleeper adapter belongs in a separate Time-dependent header; Async supplies
|
||||
its own awaiting adapter. This prevents foundational retry code from importing execution.
|
||||
|
||||
Memoization becomes per-instance with an explicit key/result signature, default 1,024
|
||||
entries and FIFO eviction. Recursive calls mark an entry as computing; a repeated key
|
||||
returns `conflict` rather than infinite recursion. Exceptions and failed expected results
|
||||
are not cached by default. Concurrent memoization is a separate externally synchronized
|
||||
adapter, not a hidden mutex in every callable. Pipeline/curry forwarding preserves
|
||||
move-only callables, return references only when the underlying callable does, and
|
||||
documents captured-reference lifetime. Standard ranges remain the default sequence API.
|
||||
|
||||
## Ordered backlog
|
||||
|
||||
| Task | Phase; dependencies | Implementation scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-FUNCTIONAL-01 | P0; current source | Lock existing expected alias, context rendering, namespace and exception behavior; compile minimal and reflection bridge consumers independently. | sol_implementer |
|
||||
| M-FUNCTIONAL-02 | P1; M-FUNCTIONAL-01 | Add compact Status, stable categories/domain codes, bounded context and explicit adapters; root classification survives 16 frames and allocation-free status paths allocate zero. | astra_implementer |
|
||||
| M-FUNCTIONAL-03 | P1; M-FUNCTIONAL-02; Time clock contract | Extract pure retry decisions and retain named blocking adapter; fake-time tests prove exact attempt counts, deadlines, jitter bounds and no zero-attempt success. | sol_implementer |
|
||||
| M-FUNCTIONAL-04 | P2; M-FUNCTIONAL-01–02 | Replace static memo caches with bounded instance caches and recursive-key detection; same callable type with different captures cannot share values. | sol_implementer |
|
||||
| M-FUNCTIONAL-05 | P2; M-FUNCTIONAL-01 | Complete Either/Opt/Pipeline/Curry move/ref-qualified behavior and declared Core bridge dependency; move-only, void and constexpr consumers compile. | sol_implementer |
|
||||
| M-FUNCTIONAL-06 | P2; M-FUNCTIONAL-02–05 | Publish migration adapters, error-domain registry and integration examples for Async/Data/Binary; no dependency cycle and installed minimal consumers pass. | sol_implementer |
|
||||
|
||||
## Evidence and migration gates
|
||||
|
||||
CURRENT verification is the inspected source/test inventory and parent-recorded baseline;
|
||||
no tests were rerun for these documents. PROPOSED tests add category-preserving adaptation,
|
||||
void/move-only expected, known/unknown exceptions, cause-limit truncation, allocator
|
||||
failure while enriching Status, two memo instances, recursive duplicate keys, failed
|
||||
compute cleanup, zero attempts, deadline-at-admission and saturated backoff. Async owns
|
||||
cancellation-race tests for its retry adapter; synchronous policy tests do not prove
|
||||
preemption or timely shutdown of arbitrary callbacks.
|
||||
|
||||
Measure successful expected chains separately from failures with context, memo hit/miss
|
||||
and eviction distributions, and callable compile cost. Follow
|
||||
[PERFORMANCE](../PERFORMANCE.md) for p50/p95/p99, allocations, throughput, RSS/CPU and
|
||||
build cost; do not compare a throwing diagnostic-heavy failure with an allocation-free
|
||||
status without reporting that work difference.
|
||||
|
||||
The [major migration](../MIGRATION.md) changes Error layout, memo ownership and retry
|
||||
defaults explicitly. Keep legacy blocking/zero-unlimited policy wrappers named and
|
||||
documented for one transition; never silently reuse old static caches. No serialized
|
||||
error object becomes a wire contract: RPC owns its versioned mapping. Rollback selects
|
||||
the old major with no persistent-data conversion, but mixed-major ABI objects cannot
|
||||
cross plugin boundaries. See [VALIDATION](../VALIDATION.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), [DELIVERY](../DELIVERY.md) and
|
||||
[requirements](../REQUIREMENTS.md) for integrated gates.
|
||||
@@ -0,0 +1,173 @@
|
||||
# Log — bounded delivery and process-wide facade
|
||||
|
||||
Status: plan; all feature tasks are PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
Implements R-005/R-009/R-012/R-014 under [C-03–C-05 and C-11](../ARCHITECTURE.md).
|
||||
|
||||
## Existing behavior and gaps
|
||||
|
||||
The names are deliberately distinct: `Void::Log` is the emission facade in
|
||||
[Log.hpp](../../../include/Void/Log/Log.hpp); `Void::Logging` owns `Logger`, `Entry`,
|
||||
formatters and sinks. [LogState/State.cpp](../../../src/LogState/State.cpp) defines the
|
||||
single facade state through a separate compiled target. Preserve this across host/plugin
|
||||
shared-library boundaries; replacing it with inline per-module statics changes behavior.
|
||||
Disabled facade calls gate formatting, and per-module levels override the global level.
|
||||
However, `Detail::emit` currently invokes the sink while holding `State::mutex` shared.
|
||||
Reentrant `set_sink` or level changes therefore need a defined safe design.
|
||||
|
||||
[Logger.cpp](../../../src/Log/Logger.cpp) supports Immediate, Buffered and Async modes.
|
||||
The async policies are Block, DropNewest and DropOldest. DropOldest currently enqueues
|
||||
without reserving capacity and trims later. The worker drains into an unconstrained batch
|
||||
and returns queue permits before delivery; queue capacity is not a bound on total retained
|
||||
entries. Existing derived sinks flush while still alive, whereas the base destructor
|
||||
stops/joins without invoking virtual delivery. Do not weaken that lifetime obligation.
|
||||
|
||||
[Sinks.hpp](../../../include/Void/Log/Sinks.hpp) has callback, null and fan-out sinks;
|
||||
fan-out configuration is assembled before concurrent use. File/rotation/history sinks and
|
||||
pattern/JSON-lines/logfmt formatters are existing capabilities. [FieldScope](../../../include/Void/Log/Field.hpp)
|
||||
and [Field.cpp](../../../src/Log/Field.cpp) maintain thread-local fields;
|
||||
[Entry](../../../include/Void/Log/Entry.hpp) owns snapshots for delivery.
|
||||
[module.cmake](../../../src/Log/module.cmake) currently declares Functional/Configuration
|
||||
and optional Stacktrace. LogState remains the lightweight compatibility bridge; foundation
|
||||
independence is governed by C-01, not by linking the full sink framework everywhere.
|
||||
|
||||
Evidence includes [facade tests](../../../tests/standalone/Log/Log.cpp),
|
||||
[async tests](../../../tests/standalone/Log/AsyncLogger.cpp), and
|
||||
[scope snapshots](../../../tests/standalone/Log/LogScopeSnapshot.cpp). Existing passing
|
||||
queue tests are not proof of a byte budget, reentrant callbacks or throwing-sink safety.
|
||||
|
||||
## Delivery architecture and NEW interfaces
|
||||
|
||||
Keep native delivery and formatting; external logging systems integrate via adapters,
|
||||
not a mandatory backend. Use a mutex-protected bounded ring initially: it makes eviction,
|
||||
permit accounting and flush boundaries auditable. A different concurrent queue is a later
|
||||
measured optimization with identical semantics. No dependency on Runtime or an exporter.
|
||||
|
||||
NEW illustrative additions in `Void::Logging`:
|
||||
|
||||
```cpp
|
||||
struct DeliveryLimits {
|
||||
std::size_t entries = 4096;
|
||||
std::size_t owned_bytes = 8 * 1024 * 1024;
|
||||
std::size_t max_entry_bytes = 64 * 1024;
|
||||
std::size_t batch_entries = 128;
|
||||
};
|
||||
enum class SubmitState { Accepted, Filtered, Dropped, Closed };
|
||||
using Ticket = std::uint64_t;
|
||||
struct SubmitReceipt { SubmitState state; std::optional<Ticket> ticket; };
|
||||
struct FlushReport { std::uint64_t delivered, dropped, failed; };
|
||||
Result<SubmitReceipt> try_submit(Entry); // NEW Logger method
|
||||
Result<FlushReport> flush_through(Ticket, FlushOptions);
|
||||
Result<FlushReport> close(CloseOptions);
|
||||
```
|
||||
|
||||
`Ticket`, `FlushOptions`, `CloseOptions` and admission receipts are NEW Log-owned types;
|
||||
they refer to Async's stop/deadline options rather than invent another cancellation type.
|
||||
Existing void-returning methods remain compatibility adapters until the major migration.
|
||||
NEW configurations default to DropNewest; existing constructors keep their documented
|
||||
Block default until explicitly migrated. Ticket assignment occurs only for admitted
|
||||
entries, under admission order, after fallible preparation succeeds.
|
||||
Non-admitted submissions have no ticket; sequence exhaustion closes admission rather than
|
||||
wrapping a watermark and reporting premature flush completion.
|
||||
|
||||
Reserve bytes and entries before making internal owned copies. Total accounting includes
|
||||
queued entries, producers preparing admitted entries, dequeued batches, sink formatting
|
||||
scratch and fan-out copies. A public caller's pre-existing Entry is outside the logger
|
||||
budget; any retained copy is inside. Format into capped storage; reject oversize by default
|
||||
instead of allocating an unlimited intermediate string. Truncation is an explicit policy
|
||||
and marks the record. Allocator overhead is charged conservatively, not just message size.
|
||||
Add defaults of 32 fields, 16 scope elements, 256-byte keys and 2 KiB field values.
|
||||
|
||||
The worker claims at most 128 entries/256 KiB per batch and retains their permits until
|
||||
delivery or terminal loss. DropNewest rejects immediately. DropOldest evicts only a queued,
|
||||
not-yet-dispatched entry under the admission lock; if all capacity is in flight, drop the
|
||||
new arrival. Block is opt-in, cancellable in the new API, and forbidden on the delivery
|
||||
worker or an executor needed to release capacity. Admission order defines per-logger
|
||||
ordering; no timestamp-based total order across independent loggers is promised.
|
||||
|
||||
Fan-out is bounded to eight children by default, checks cycles on configuration, and owns
|
||||
child handles. A child has a distinct budget; total memory is the sum of parent and child
|
||||
budgets, visible in configuration. Share immutable records where possible, charging the
|
||||
shared payload once to a retained owner and charging each envelope separately. A slow
|
||||
child must not create an unbounded staging queue in the parent.
|
||||
|
||||
## Reentrancy, flush and shutdown
|
||||
|
||||
Facade configuration becomes an immutable sink-registration object retained by emitters.
|
||||
Acquire/snapshot the registration under the configuration lock, then release that lock
|
||||
before formatting/callback invocation and before destroying the old callback. Replacement
|
||||
affects subsequent admissions; already-admitted calls may still use the old registration.
|
||||
NEW `detach_and_drain` waits for those calls to exit and is not callable synchronously
|
||||
from that registration's callback. `set_sink` alone is not an unsubscribe-and-join promise.
|
||||
Callbacks that capture plugin code retain its generation through the last callback.
|
||||
|
||||
A per-thread/per-logger dispatch guard suppresses recursive dispatch into the same sink,
|
||||
increments `reentrant_dropped`, and uses a bounded emergency diagnostic path only if
|
||||
explicitly installed. Logging to a different sink remains allowed within a maximum nesting
|
||||
depth of eight. No retry/error reporting calls back into a failing sink. User callbacks,
|
||||
formatter code and virtual sink methods run outside queue/configuration locks. A callback
|
||||
may request asynchronous close, but self-join or blocking flush returns WouldDeadlock.
|
||||
|
||||
Flush takes a ticket watermark, so later producers cannot extend it forever. Every admitted
|
||||
ticket becomes delivered, evicted or failed; the completion watermark advances only through
|
||||
a contiguous terminal prefix, even if immediate mode completes out of order. The report
|
||||
includes all losses through that watermark. A sink's buffer flush is distinct from durable
|
||||
file sync: a NEW `FlushDurability::SyncFiles` option syncs supported file sinks or returns
|
||||
UnsupportedCapability. Callback sinks cannot claim disk durability on the callback's behalf.
|
||||
|
||||
Catch sink exceptions at delivery boundaries, mark affected tickets failed, record a bounded
|
||||
error summary, and continue or quarantine that sink according to a selected configuration.
|
||||
Default is quarantine after the first delivery failure, with explicit operator reset;
|
||||
never silently retry a possibly written record. Mode/formatter changes use an admission
|
||||
barrier and drain the old generation before publishing the new one. Configuration validation
|
||||
cannot invoke arbitrary callbacks while locked.
|
||||
|
||||
`close` rejects new work, drains or explicitly drops queued work, then joins delivery and
|
||||
releases sink ownership. A deadline may stop waiting but cannot destroy a callback still
|
||||
executing; an owning close handle retains resources until completion (C-03). Legacy derived
|
||||
destructors still need their flush contract; NEW composition owns sink state independently
|
||||
of a partially destructed polymorphic logger. No forceful callback interruption is promised.
|
||||
|
||||
## Capability backlog and implementation order
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-LOG-01 | P0; current tests | Add regressions for callback reconfiguration, slow sink and total queued+in-flight accounting; preserve existing disabled/field/mode behavior. | astra_implementer |
|
||||
| M-LOG-02 | P1; M-LOG-01, C-11 | Snapshot facade registrations, drain handles, reentrancy guard and shared-library test; host sink receives plugin events and can replace itself without deadlock. | astra_implementer |
|
||||
| M-LOG-03 | P2; M-LOG-02, Memory budgeting | Bounded ring, byte admission, batch limits, all saturation policies and contiguous ticket completion; limits hold while sink stalls and producers race. | astra_implementer |
|
||||
| M-LOG-04 | P2; M-LOG-03, Async operation options | Result-based flush/close, failure quarantine, reconfiguration barriers; no self-join, stuck watermark or callback after owner release. | astra_implementer |
|
||||
| M-LOG-05 | P2; M-LOG-04 | Finish sink workflows: file failure reporting, retention quota, rotation/reopen, formatter escaping/redaction and configuration validation; disk-full preserves loss accounting. | sol_implementer |
|
||||
| M-LOG-06 | P3; M-LOG-04, Observability hook/context contract | Optional context bridge, metrics and managed shutdown adapter; no Log↔Observability or Async↔Log cycle. | sol_implementer |
|
||||
| M-LOG-07 | P3; M-LOG-05/06, shared performance harness | Profile disabled, immediate, async, structured and saturated paths; publish measured latency/memory/build costs and rejected counts. | sol_implementer |
|
||||
|
||||
P4 consumers reuse these contracts through [distributed platforms](../platforms/DistributedApplications.md);
|
||||
logging does not become a durable consensus log. For file rotation default NEW retention is
|
||||
five 16 MiB files per sink, with a 1 MiB capped formatting scratch budget. Opening/reopening
|
||||
files is fallible, directory creation is explicit, and partial writes are errors with
|
||||
possible partial external output. Audit records needing durable transactional semantics
|
||||
belong in Storage, not a loss-tolerant logger.
|
||||
|
||||
## Validation and compatibility
|
||||
|
||||
CURRENT interfaces: the existing `VoidTests` supports `--filter`; a TEMPLATE for the verified
|
||||
names is `<existing-build>/tests/VoidTests --filter '^(no_sink_is_silent|disabled_calls_do_not_format|async_.*)$'`.
|
||||
Use the configured build in [validation](../VALIDATION.md); this documentation task does not
|
||||
execute it. PROPOSED tests require M-LOG-01–06: deterministic blocked callbacks, callback
|
||||
replacement/destruction, thrown formatter/sink, concurrent flush, drop-oldest pressure,
|
||||
permit rollback on allocation failure, copied context after producer exit, and shutdown
|
||||
with an admitted callback. Stress and TSan supplement deterministic ownership checks.
|
||||
|
||||
Measure p50/p95/p99 admission and flush separately, throughput, allocations, RSS/CPU and
|
||||
build cost under [performance](../PERFORMANCE.md)'s warmup/repetition/confidence rules.
|
||||
Report drops and reentrant suppression alongside useful delivery; an apparent improvement
|
||||
caused by losing work is not an optimization result.
|
||||
|
||||
[Migration](../MIGRATION.md): preserve namespaces and LogState symbol linkage; add explicit
|
||||
registration and close handles before replacing legacy signatures. Example transition:
|
||||
`logger.info(text); logger.flush();` becomes checked admission plus `flush_through(ticket)`
|
||||
when delivery evidence matters. Frozen C/plugin contracts must use their own versioned
|
||||
bridges, not embed C++ Entry layout. Keep old sinks behind adapters during the major release;
|
||||
roll back a new queue/backend only if ordering, resource and flush tests remain satisfied.
|
||||
|
||||
Coverage: cited files were checked in the repository graph and read directly; partial parses
|
||||
in Logger/Sinks/Field were inspected, so graph absence is not used as evidence. New tests,
|
||||
resource guarantees and performance claims remain unverified planned work.
|
||||
@@ -0,0 +1,148 @@
|
||||
# Math and numeric utility completion
|
||||
|
||||
Status: planning only; all tasks are **PLANNED**. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Current capabilities
|
||||
|
||||
[Math](../../../src/Math/module.cmake) declares no dependencies.
|
||||
[Numeric](../../../include/Void/Math/Numeric.hpp) provides `Void::Numeric::Error`, checked,
|
||||
saturating and unsigned wrapping arithmetic, parsing, range and narrowing helpers.
|
||||
Checked arithmetic currently uses compiler overflow builtins. `parse_int`/`parse_double`
|
||||
pass `string_view::data()` to C conversion functions, so a bounded non-NUL-terminated
|
||||
substring requires correction. The `long long`-based narrowing interface is insufficient
|
||||
for every unsigned conversion. These are concrete foundations work, not scientific scope.
|
||||
|
||||
[Random](../../../include/Void/Math/Random.hpp) implements `Void::Random::Xoshiro256`, a
|
||||
thread-local generator, distributions, shuffle and sampling. Sampling materializes all
|
||||
`n` indices; `k > n` is not explicitly rejected. The generator is for simulations,
|
||||
sampling and jitter, not secrets. [Histogram](../../../include/Void/Math/Histogram.hpp)
|
||||
contains keyed frequency and fixed-bin structures. Fixed-size arithmetic exists in
|
||||
[Matrix](../../../include/Void/Math/Matrix.hpp) under `Void::Matrix` and
|
||||
[Vec](../../../include/Void/Math/Vec.hpp)/[Mat](../../../include/Void/Math/Mat.hpp) under
|
||||
`Void::Math`. Their distinct Mat4 names must not be silently treated as aliases.
|
||||
|
||||
[Numeric](../../../tests/standalone/Math/Numeric.cpp),
|
||||
[Random](../../../tests/standalone/Math/Random.cpp),
|
||||
[Histogram](../../../tests/standalone/Math/Histogram.cpp),
|
||||
[Matrix](../../../tests/standalone/Math/Matrix.cpp), and
|
||||
[VecMat](../../../tests/standalone/Math/VecMat.cpp) suites are current regression sources.
|
||||
Graph parsing is partial at Mat line 15 and Vec lines 13/50/91; these template declarations
|
||||
were read directly. No build or benchmark result is inferred from source inspection.
|
||||
|
||||
## Target and backend decisions
|
||||
|
||||
Keep standard-library-only, native numeric utilities below Data and application modules,
|
||||
per [C-01/C-02](../ARCHITECTURE.md). Core UUID removes its Math include; Math must not
|
||||
depend back on Data to supply numeric conversion. Functional provides optional enum-to-
|
||||
Error adapters, not a required string allocation in every arithmetic operation.
|
||||
Math imports neither Containers nor Algorithms; fixed arrays and standard-library scratch
|
||||
storage keep its scalar arithmetic below both. M-MATH-02 supplies the narrow checked-
|
||||
arithmetic prerequisite for Algorithms before Containers/Text adapters depend on it.
|
||||
Standard `from_chars`, distributions and ranges remain the default tools; overflow
|
||||
builtins are guarded optimizations over a constexpr portable reference path. No BLAS,
|
||||
Eigen, arbitrary precision or general scientific platform is introduced by this plan.
|
||||
|
||||
## NEW conversion and arithmetic APIs
|
||||
|
||||
Illustrative NEW additions in `include/Void/Math/Numeric.hpp`:
|
||||
|
||||
```cpp
|
||||
namespace Void::Numeric {
|
||||
enum class Rounding { exact, toward_zero, nearest_even };
|
||||
template<class To, class From>
|
||||
std::expected<To, Error> checked_cast(From value,
|
||||
Rounding mode = Rounding::exact) noexcept;
|
||||
template<std::integral T>
|
||||
std::expected<T, Error> parse_integer(std::string_view, int base = 10) noexcept;
|
||||
template<std::floating_point T>
|
||||
std::expected<T, Error> parse_real(std::string_view) noexcept;
|
||||
template<std::integral T>
|
||||
std::expected<T, Error> checked_mul_add(T a, T b, T c) noexcept;
|
||||
}
|
||||
```
|
||||
|
||||
Integer-to-integer conversion compares ranges by signedness without first narrowing.
|
||||
Float-to-integer first rejects NaN/infinity, then applies the named rounding policy,
|
||||
then tests against exactly representable exclusive/inclusive bounds before casting.
|
||||
Default exact rejects fractional values. Integer-to-float exact rejects a value if its
|
||||
significand cannot be represented; the implementation checks significant bits instead
|
||||
of performing an unsafe float-to-integer round trip. Float narrowing exact rejects loss
|
||||
of finite value; explicit nearest-even uses the documented floating environment policy.
|
||||
`Error` gains `Inexact` and `NonFinite` in the major release. Data converts these domain
|
||||
errors into path-aware diagnostics without changing Numeric's low-cost enum.
|
||||
|
||||
Parsing consumes precisely the supplied span and requires full token consumption.
|
||||
Integer bases are 2–36; base autodetection is a separate named policy, not default.
|
||||
No locale whitespace, leading plus, partial suffix, or nonfinite token is accepted by
|
||||
the default parser. Maximum numeric token is 256 bytes; an explicit larger bounded policy
|
||||
is separate. Grammar validation precedes conversion; there is no NUL scan beyond input.
|
||||
`checked_mul_add` is specified as sequential checked multiplication then addition, so
|
||||
an overflowing intermediate fails even if cancellation could produce a final in-range
|
||||
mathematical result. Saturating helpers use these classifications deliberately;
|
||||
wrapping arithmetic remains unsigned-only. Resource-size checked add/multiply stays
|
||||
available without a dependency on dynamic matrix or random headers.
|
||||
|
||||
## Other capability backlogs
|
||||
|
||||
Random adds injected-URBG overloads for distributions, shuffle and sampling, leaving
|
||||
thread-local convenience APIs as adapters. Seeded Xoshiro output has fixed golden vectors;
|
||||
standard-distribution output is not promised identical across standard-library vendors.
|
||||
Defaults cap sample output at 1,048,576 elements and scratch at 16 MiB. Reject `k > n`.
|
||||
Use Floyd sampling for sparse `k` (O(k) memory), and partial Fisher–Yates for dense samples
|
||||
only within the scratch cap; the selection threshold is `k <= n/8`, frozen with tests.
|
||||
No unrequested entropy acquisition occurs when a generator is supplied.
|
||||
|
||||
Histogram adds bounded merge, count-overflow errors and deterministic tie-breaking.
|
||||
Keyed defaults cap at 65,536 distinct keys; fixed bins default to 1,024 with maximum
|
||||
65,536, finite ordered endpoints and explicit underflow/overflow counters. NaN is
|
||||
rejected. Quantiles from fixed bins are approximate intervals, not invented exact
|
||||
percentiles; Time's exact benchmark samples do not reuse approximate results unnoticed.
|
||||
|
||||
Matrix work retains stack storage for fixed sizes, adds checked normalization/inversion
|
||||
with singular/nonfinite diagnostics, and documents row-major layout and transformation
|
||||
conventions. Select `Void::Matrix::Matrix<T,R,C>` as the shared arithmetic kernel while
|
||||
keeping Vec named-field value types and `Void::Math::Mat4` facades. Conversion is explicit
|
||||
until a major-version ABI change; no reinterpret-cast view assumes matching layouts.
|
||||
No heap-sized dynamic matrix is included. Generic integer matrix operations get checked
|
||||
variants rather than promising undefined signed overflow is acceptable.
|
||||
|
||||
## Task DAG
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-MATH-01 | P0; current source | Capture existing numeric, generator and matrix fixtures and namespace/layout contracts; identify builtins and unsupported conversion edges. | sol_implementer |
|
||||
| M-MATH-02 | P1; M-MATH-01 | Implement span-safe parsers, checked_cast and portable overflow fallback; signed/unsigned and float boundaries pass without undefined behavior. | astra_implementer |
|
||||
| M-MATH-03 | P2; M-MATH-02 | Add injected RNGs and bounded sampling; k=0/k=n/k>n, huge n with small k and seeded generator vectors pass within scratch limits. | sol_implementer |
|
||||
| M-MATH-04 | P2; M-MATH-02 | Complete bounded histograms and merge semantics; count overflow leaves prior histogram intact and approximate outputs carry bounds. | sol_implementer |
|
||||
| M-MATH-05 | P2; M-MATH-02 | Consolidate matrix arithmetic kernel with explicit facade conversion; singular/zero-vector, row-major and integer-overflow tests pass. | sol_implementer |
|
||||
| M-MATH-06 | P3; M-MATH-03–05 | Benchmark targeted kernels, publish compatibility adapters and isolated installed consumers; optional vectorization is admitted only after scalar differential tests. | sol_implementer |
|
||||
|
||||
## Limits, verification and migration
|
||||
|
||||
All operations are synchronous and caller-owned; no queue, cancellation thread or shutdown
|
||||
service exists. Batch sampling/merging receives a stop token only in explicit long-running
|
||||
overloads, checked at bounded chunks, returning no partially published output. Matrix
|
||||
template extents are compile-time; recommended instantiated extents are at most 16×16
|
||||
until compiler/build-cost evidence supports larger values. This is a supported profile,
|
||||
not a claim that all larger templates cannot compile.
|
||||
|
||||
CURRENT tests are the linked suites; no new execution was performed. PROPOSED validation
|
||||
uses property tests against wide/reference arithmetic, bounded substrings adjacent to
|
||||
guard pages, all small integer widths, INT64_MIN/UINT64_MAX, 2^53±1, fractional edges,
|
||||
NaN/infinities, subnormals and negative zero. Differential RNG tests check range and
|
||||
deterministic engine vectors; statistical smoke tests do not establish cryptographic
|
||||
quality. Matrix residual tests use stated tolerance and scale, not exact floating equality.
|
||||
|
||||
Follow [PERFORMANCE](../PERFORMANCE.md) for scalar/batch parse throughput, conversion
|
||||
p50/p95/p99, sample allocations/RSS/CPU and header/template build cost. Separate entropy,
|
||||
engine and distribution costs. [VALIDATION](../VALIDATION.md) and
|
||||
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md) own future commands/toolchains.
|
||||
|
||||
[Migration](../MIGRATION.md) deprecates unsafe `long long` narrowing wrappers and preserves
|
||||
legacy parsing only through named adapters. Exact Data integer conversion is gated on
|
||||
M-MATH-02 and does not change StrictJson. Old Mat4 storage/ABI remains until a major break;
|
||||
rollback selects the old package with no persisted numeric conversion. Consumers must
|
||||
not persist native object representations as wire formats; [Binary](Binary.md) owns those.
|
||||
See [requirements](../REQUIREMENTS.md), [dependencies](../DEPENDENCIES.md),
|
||||
[delivery](../DELIVERY.md) and [Data](Data.md).
|
||||
@@ -0,0 +1,179 @@
|
||||
# Net implementation plan
|
||||
|
||||
Status: planning only. All feature tasks below are PLANNED. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Authority: [requirements](../REQUIREMENTS.md) R-002–R-006, R-009–R-016;
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-06, C-11, C-13.
|
||||
|
||||
## Existing capability and evidence
|
||||
|
||||
The public namespace is `Void::Net`. [Http.hpp](../../../include/Void/Net/Http.hpp)
|
||||
exposes synchronous `HttpClient`, owning request/response strings, HTTP and SOCKS5 proxy
|
||||
configuration, a 30-second request timeout, opt-in redirects, and a 64 MiB body limit.
|
||||
Zero currently means unlimited. Non-2xx responses are successful transport results.
|
||||
[Http.cpp](../../../src/Net/Http.cpp) constructs an Asio context and socket per hop;
|
||||
there is no connection pool. Its watchdog starts after resolution/connect, and each
|
||||
redirect restarts the phase budget. Certificate checking defaults off; enabling it
|
||||
sets peer verification but the inspected handshake only sets SNI, not expected-host
|
||||
verification. Redirects retain the original method, body, and headers.
|
||||
|
||||
[Server.hpp](../../../include/Void/Net/Server.hpp) and
|
||||
[Server.cpp](../../../src/Net/Server.cpp) provide `Router`, `StaticFileResolver`, and
|
||||
`WebSocketSessions`. Routing snapshots a handler before invoking it outside the lock;
|
||||
the session registry also invokes callbacks/close outside its lock. These are useful
|
||||
transport-neutral components, not an HTTP listener or a WebSocket framing engine.
|
||||
Static resolution rejects traversal and canonical symlink escapes but returns a path;
|
||||
opening that path later needs protection against filesystem replacement races.
|
||||
[Socket.hpp](../../../include/Void/Net/Socket.hpp) and
|
||||
[Socket.cpp](../../../src/Net/Socket.cpp) implement connected blocking UDP on POSIX;
|
||||
Windows operations report unsupported. `wait_readable` uses poll.
|
||||
[Url.hpp](../../../include/Void/Net/Url.hpp) / [Url.cpp](../../../src/Net/Url.cpp)
|
||||
use Boost.URL and accept URI references as well as absolute URIs.
|
||||
|
||||
[module.cmake](../../../src/Net/module.cmake) declares Functional, Text, Boost
|
||||
headers/Beast/Asio/URL, OpenSSL, and Threads. Existing tests cover loopback GET/POST,
|
||||
invalid URL/refusal and a stalled response in
|
||||
[HttpClient.cpp](../../../tests/standalone/Net/HttpClient.cpp); router/static/session
|
||||
helpers in [Server.cpp](../../../tests/standalone/Net/Server.cpp); parsing in
|
||||
[Url.cpp](../../../tests/standalone/Net/Url.cpp); and closed/moved UDP state in
|
||||
[Socket.cpp](../../../tests/standalone/Net/Socket.cpp). They do not establish TLS,
|
||||
proxy, real server, WebSocket wire, or sustained reuse conformance.
|
||||
|
||||
Graph coverage was checked for all these files: Http.hpp lines 112/115 and Server.hpp
|
||||
207/211/214 have parse gaps and were read directly. Other paths reported matching
|
||||
metadata with no recorded issue; graph edges are advisory, source is authoritative.
|
||||
|
||||
## Target interfaces and backend ownership
|
||||
|
||||
NEW illustrative APIs below are not compiling examples. `OperationOptions` and `Task`
|
||||
refer to [Async](Async.md)'s C-03 types; byte streams and descriptor lifetime belong to
|
||||
[IO](../subsystems/IO.md). Net owns protocol state, endpoint resolution policy, TLS
|
||||
contexts, parsers, pools, and listener/session policy. No constructor starts workers.
|
||||
|
||||
```cpp
|
||||
// NEW shapes in Void::Net; Result is C-02 shorthand.
|
||||
struct ClientPolicy { TlsPolicy tls; RedirectPolicy redirects; PoolLimits pool; };
|
||||
class Client {
|
||||
Task<Result<StreamingResponse>> send(StreamingRequest, OperationOptions);
|
||||
Task<Result<void>> shutdown(OperationOptions);
|
||||
};
|
||||
class HttpServer {
|
||||
static Result<HttpServer> create(IOContext&, ServerPolicy, Handler);
|
||||
Task<Result<BoundEndpoint>> listen(Endpoint, OperationOptions);
|
||||
Task<Result<void>> shutdown(OperationOptions);
|
||||
};
|
||||
// StreamingResponse owns its connection lease until consumed or cancelled.
|
||||
// Handler receives headers plus a bounded body reader and returns a body producer.
|
||||
```
|
||||
|
||||
Choose native incremental HTTP/1.1 and WebSocket codecs over native IO; retain a
|
||||
separately selectable Boost migration adapter until wire conformance gates pass.
|
||||
Keep OpenSSL as the TLS backend; do not implement cryptographic primitives. Initial
|
||||
Linux IO is level-triggered epoll, owned by IO, with bounded work per readiness turn
|
||||
to avoid monopolizing the executor. Readiness is not a whole-message completion.
|
||||
See [epoll semantics](https://man7.org/linux/man-pages/man7/epoll.7.html).
|
||||
Native URL parsing must preserve encoded components and implement RFC reference
|
||||
resolution before replacing Boost.URL. HTTP/2, QUIC, compression, and proxy servers
|
||||
are later named capabilities, not claims of the first release.
|
||||
|
||||
## Protocol and operation rules
|
||||
|
||||
1. Admit against byte/operation budgets; validate absolute http/https destinations,
|
||||
authority, numeric ports, header syntax, and explicit proxy credential lengths.
|
||||
URI references remain a separate parsing API; they cannot silently become a host.
|
||||
2. Establish one absolute steady deadline at admission. DNS, capacity waiting,
|
||||
address attempts, connect, proxy negotiation, TLS, redirects and body transfer
|
||||
consume it. Resolver workers retain owned inputs after caller cancellation;
|
||||
late results are discarded and accounted until worker completion.
|
||||
3. Verify trusted chain and DNS/IP peer identity by default; SNI alone is inadequate.
|
||||
TLS minimum is 1.2, allow 1.3 through backend negotiation. Trust stores are explicit
|
||||
immutable configuration snapshots. Insecure test policy must be conspicuously
|
||||
named and opt-in. Follow the separate verification and identity setup in the
|
||||
[OpenSSL 3.5 client guide](https://docs.openssl.org/3.5/man7/ossl-guide-tls-client-block/).
|
||||
4. Parse HTTP framing incrementally: reject conflicting Content-Length values and
|
||||
Transfer-Encoding/Content-Length ambiguity, enforce CRLF and header limits, handle
|
||||
informational responses, HEAD/no-body statuses, chunk extensions/trailers and
|
||||
close-delimited bodies. Never reuse a connection with uncertain message boundaries.
|
||||
Protocol conformance fixtures must cover RFC 9110/9112 before native promotion.
|
||||
5. Default redirects remain disabled; enabling follows only 301/302/303/307/308, up to
|
||||
five hops. 303 changes non-HEAD to GET and drops body/body headers; 301/302 preserve
|
||||
method and require explicit replay permission for non-safe methods; 307/308 preserve
|
||||
method and require a replayable body. Reject HTTPS downgrade by default. Resolve
|
||||
relative references correctly; compare scheme/host/effective port. On origin change,
|
||||
strip Authorization, Cookie and caller-declared sensitive headers; always rebuild
|
||||
Host and keep Proxy-Authorization confined to its proxy hop. No implicit cookie jar.
|
||||
6. Pool by origin, proxy identity and TLS/trust-policy generation. HTTP/1.1 initially
|
||||
allows one exchange per connection, no pipelining. Return a lease only after body
|
||||
and trailers finish; abandon/cancel closes it. No automatic replay after bytes may
|
||||
have reached a peer. Upper layers supply idempotency policy.
|
||||
7. Server accept → TLS → bounded headers/body → dispatch → streamed response → reuse.
|
||||
Handler errors map through a configurable sanitized error mapper; no route is 404,
|
||||
known path with wrong method is 405 with Allow. Disable further admission on stop,
|
||||
drain admitted requests, then cancel/join connections. Static serving opens beneath
|
||||
a retained directory handle through IO/System capability checks, not a stale pathname.
|
||||
8. WebSocket upgrade validates version/key/Connection/Upgrade, origin policy and selected
|
||||
subprotocol. Enforce client masking, server non-masking, fragmentation/control-frame
|
||||
rules, UTF-8 text and close reasons, ping/pong and one close handshake. Disable
|
||||
extensions initially. Frame callbacks borrow payload only during invocation; retained
|
||||
payloads require owned copies. RFC 6455 fixtures and an independent peer are gates.
|
||||
|
||||
## Bounds and failure matrix
|
||||
|
||||
NEW defaults: 256 total client connections, 8/origin, 128 idle, 30-second idle eviction;
|
||||
1,024 admitted client operations; 4,096 server connections and 256 executing handlers.
|
||||
Headers: 32 KiB aggregate/100 fields/8 KiB start line. Buffered bodies: 8 MiB; streaming
|
||||
uses 64 KiB chunks, 256 KiB per-direction windows and a 256 MiB module buffer budget.
|
||||
WebSocket messages: 1 MiB, output: 64 messages or 4 MiB/session; either bound rejects
|
||||
admission. Limits include in-flight buffers. Body streaming has an explicit optional
|
||||
total-byte quota; there is no accidental zero-as-unlimited. Server headers expire at
|
||||
10 seconds, idle at 30 seconds, admitted request at 30 seconds by default; a public
|
||||
long-lived stream must opt into its own liveness policy. Shutdown grace: 10 seconds.
|
||||
|
||||
| Trigger | Terminal behavior and cleanup | Required evidence |
|
||||
| --- | --- | --- |
|
||||
| DNS/connect/proxy/TLS timeout | Timeout with phase; one completion; close/retire state | Stall every phase under one deadline |
|
||||
| Unknown CA / wrong hostname | Peer verification error before request bytes | Separate fixtures for trust and identity |
|
||||
| Body/header limit or malformed framing | Protocol/limit error; connection unusable | Split bytes at every boundary; smuggling corpus |
|
||||
| Capacity exhaustion | Overload before allocation; optional cancellable capacity wait | Queue plus in-flight accounting |
|
||||
| Cancellation mid-upload | Cancelled/unknown remote effect; close lease, retain buffers until IO ends | Stop/completion races, no replay |
|
||||
| Slow consumer / WebSocket output full | Await explicit capacity or return overload; bounded memory | Slow-reader soak with max RSS |
|
||||
| Handler throws or stream fails | Sanitized 500 before headers, otherwise terminate connection | Faulting handlers outside locks |
|
||||
| Shutdown with peer stalled | Stop admission, grace then cancel/join; no callbacks after join | Destruction and descriptor-reuse races |
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
Every row is PLANNED; dependencies refer to completed evidence gates, not file existence.
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-NET-01 | P0; baseline | Freeze current client/router/URL fixtures and secure-behavior gaps; installed Net-only consumer records actual dependencies | sol_implementer |
|
||||
| M-NET-02 | P1; M-NET-01, IO/Async/Time contracts | NEW context, resolver, socket/listener and deadline adapters; every phase cancellable without borrowed-state escape | astra_implementer |
|
||||
| M-NET-03 | P2; M-NET-02 | OpenSSL peer+identity defaults, proxy validation, redirect algorithm; trust/hostname/cross-origin matrix passes on Boost adapter first | astra_implementer |
|
||||
| M-NET-04 | P2; M-NET-03 | Native HTTP codec, real HTTP/HTTPS server, streaming, pool and safe static open; RFC corpus, fuzzing, independent peers pass | astra_implementer |
|
||||
| M-NET-05 | P2; M-NET-04 | Native WebSocket client/server and session lifecycle; fragmented/control/close/UTF-8 conformance and shutdown races pass | sol_implementer |
|
||||
| M-NET-06 | P3; M-NET-05 | Backend parity and performance gate; keep Boost selectable until migration consumer and workload evidence permit default switch | astra_implementer |
|
||||
| M-NET-07 | P4; M-NET-06, RPC/Messaging gates | Distributed transport stress, reconnect and bounded streaming workloads; no safety claims inferred from availability alone | sol_implementer |
|
||||
|
||||
## Validation, compatibility and rollback
|
||||
|
||||
CURRENT checks are existing `VoidTests` and `VoidInstalledComponentConsumers` registered
|
||||
in [tests/CMakeLists.txt](../../../tests/CMakeLists.txt). They were not rerun for this
|
||||
documentation task. Current source fixtures are evidence of coverage intent, not new
|
||||
passing results. PROPOSED checks add deterministic resolver/clock fault injection,
|
||||
TLS/proxy loopback peers, parser fuzz targets and independent HTTP/WebSocket clients;
|
||||
targets must be added before commands are advertised. Use [VALIDATION](../VALIDATION.md)
|
||||
and [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md) for the actual build gate.
|
||||
|
||||
Measure small reused requests, connection churn, large streaming downloads, many idle
|
||||
WebSockets and slow consumers: p50/p95/p99, throughput, allocations, peak RSS/CPU, file
|
||||
descriptors, handshake counts and build cost under [PERFORMANCE](../PERFORMANCE.md).
|
||||
Separate cold DNS/TLS from warm pool results and Boost from native.
|
||||
|
||||
Major-release migration replaces unsafe defaults and whole-body APIs with secure
|
||||
configuration and streaming, with an owning buffered convenience adapter. Existing
|
||||
`HttpClient` remains documented during transition; a synchronous wrapper cannot block
|
||||
the executor needed for its completion. Keep non-2xx transport-result semantics. Pools
|
||||
must be recreated when trust/proxy identity changes. Roll back backend selection only
|
||||
between operations; never replay an uncertain write on the old backend. See
|
||||
[MIGRATION](../MIGRATION.md), [RPC](../subsystems/RPC.md),
|
||||
[Security](Security.md), and [NetworkedApplications](../platforms/NetworkedApplications.md).
|
||||
@@ -0,0 +1,199 @@
|
||||
# Plugin generations, stable C ABI and reload protocol plan
|
||||
|
||||
Status: PLANNED feature work; no new ABI is delivered. Baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Requirements R-004, R-009, R-010 and R-013–R-016 apply. Preserve
|
||||
[architecture](../ARCHITECTURE.md) C-03–C-05, C-09, C-10 and C-13.
|
||||
|
||||
## Existing source baseline and compatibility classes
|
||||
|
||||
[Plugin.hpp](../../../include/Void/Plugin/Plugin.hpp) defines `Void::Plugin::IPlugin`,
|
||||
`PluginInfo`, `ABI_VERSION == 1`, C-linkage create/destroy/info symbols and optional
|
||||
configuration/readiness/state-transfer exports. The serialized-state protocol carries
|
||||
a state schema version and plugin-owned string release. Existing factory output is
|
||||
still an IPlugin C++ object; its vtable, RTTI and callbacks require compatible toolchains.
|
||||
The source's v2 state protocol is not a new general stable C ABI version.
|
||||
|
||||
[Loader.hpp](../../../include/Void/Plugin/Loader.hpp) owns one instance and is not
|
||||
thread-safe. [Manager.hpp](../../../include/Void/Plugin/Manager.hpp) exposes pinned
|
||||
`PluginHandle`, acquire/load/unload/reload/replace, validators, watching, observers and
|
||||
state snapshots. [Manager.cpp](../../../src/Plugin/Manager.cpp) stages a fresh inode,
|
||||
configures/restores/activates/checks readiness before atomic current-instance publication.
|
||||
Acquisition also takes the registry mutex; do not infer a completely lock-free path
|
||||
from the header's atomic-load description. Reload observers run after unlocking, but
|
||||
candidate validation and plugin activation currently occur inside reload's map lock.
|
||||
`dlclose_on_swap` defaults false to keep code mapped when arbitrary frames/callbacks
|
||||
may survive; a new protocol must prove async quiescence before changing that default.
|
||||
|
||||
[Module.hpp](../../../include/Void/Plugin/Module.hpp) already supplies C++
|
||||
`ModuleDescriptor`, `ModuleDependency`, `ActivationPolicy`, `ModuleHost`, `IModule`,
|
||||
`ModuleReadiness`, activate/quiesce/checkpoint/restore/readiness/deactivate. The descriptor
|
||||
contains STL, Json, Semver and unique_ptr factory types: it is explicitly a C++ descriptor.
|
||||
Its default methods are not proof that a coordinated reload host exists.
|
||||
[module.cmake](../../../src/Plugin/module.cmake) declares Functional/System/Data and
|
||||
Unix dl; target declaration versus public descriptor includes needs isolated-consumer
|
||||
validation under the shared dependency plan.
|
||||
|
||||
[Manager tests](../../../tests/standalone/Plugin/Manager.cpp),
|
||||
[load-under-reload test](../../../tests/standalone/Plugin/HotReloadUnderLoad.cpp),
|
||||
[configuration tests](../../../tests/standalone/Plugin/Configure.cpp), and
|
||||
[module descriptor test](../../../tests/standalone/Plugin/Module.cpp) are existing
|
||||
fixtures, not evidence of a stable C-only boundary or async pin protocol. Scoped graph
|
||||
coverage was checked; Manager declarations/test helper ranges were directly read.
|
||||
|
||||
The initial loader remains native platform dynamic loading (`dlopen` on Linux), with
|
||||
Void-owned descriptors and lifecycle; no external plugin framework is introduced.
|
||||
Portability adapters must satisfy the same pin/release conformance before enabling unload.
|
||||
|
||||
## NEW stable C boundary
|
||||
|
||||
NEW proposed path: `include/Void/Plugin/CAbi.h`; use a separately named export
|
||||
`void_module_query_v1`. Do not change the layout or reinterpret the meaning of
|
||||
`void_plugin_info`, existing ModuleDescriptor or the frozen [ShortUrl V1](../../short-url.md).
|
||||
The following is an illustrative C header shape, not an available ABI:
|
||||
|
||||
```c
|
||||
typedef struct void_module_handle void_module_handle;
|
||||
typedef struct void_operation_handle void_operation_handle;
|
||||
typedef struct { const uint8_t *data; uint64_t size; } void_bytes_v1;
|
||||
typedef struct {
|
||||
uint32_t struct_size;
|
||||
uint32_t abi_major;
|
||||
uint32_t abi_minor;
|
||||
uint32_t reserved;
|
||||
uint64_t capabilities;
|
||||
int32_t (*create)(const void *host_api, void_module_handle **out);
|
||||
int32_t (*activate)(void_module_handle *, void_bytes_v1 config);
|
||||
int32_t (*readiness)(void_module_handle *, uint32_t *out_ready);
|
||||
int32_t (*request_stop)(void_module_handle *);
|
||||
int32_t (*destroy)(void_module_handle *);
|
||||
} void_module_api_v1;
|
||||
/* int32_t void_module_query_v1(uint32_t host_size, void_module_api_v1 *out); */
|
||||
```
|
||||
|
||||
Complete this table with versioned quiesce/resume, checkpoint/restore, interface
|
||||
query/release and async-operation functions in M-PLUGIN-03 before freezing ABI V1.
|
||||
Tail capabilities use size-checked extension tables; reject unknown major, truncated
|
||||
required prefix and required capability mismatch. Copy descriptor metadata into host
|
||||
ownership while the generation is pinned. Reserved fields are zero; lengths are checked
|
||||
before conversion to size_t. Interface identifiers are fixed 128-bit byte values with
|
||||
independent interface major/minor and a function-table size; they are not typeid hashes.
|
||||
|
||||
All boundary functions use fixed-width status codes and explicit error detail access
|
||||
with owner-specific release. No exceptions, STL, reflection objects, standard-library
|
||||
stop tokens or C++ allocation cross the C boundary. C++ adapters catch exceptions and
|
||||
map operational failure; unknown exceptions become `internal_error` without unwinding
|
||||
through C. The host passes a versioned host function table instead of an untyped payload
|
||||
in the final header; the void pointer above stands for that separately sized table.
|
||||
|
||||
Input byte spans borrow only for the call. Checkpoint output is an opaque plugin-owned
|
||||
buffer with `data/size/release`; the host copies within its cap before releasing through
|
||||
the plugin. No allocator mismatch. Async submission copies required descriptors and
|
||||
returns an opaque operation handle plus exactly one terminal callback. Host cancellation
|
||||
maps its Async OperationOptions into explicit C request-stop/deadline fields relative
|
||||
to the negotiated host monotonic clock; it never copies std::stop_token into C memory.
|
||||
Release of an operation handle requires terminal acknowledgement and callback return.
|
||||
The final ABI conformance specification defines callback thread/reentrancy and null-output
|
||||
rules for every status; output handles are null on failed admission.
|
||||
|
||||
## Generation pins and unload invariants
|
||||
|
||||
Each loaded generation owns its mapping, instance, host registrations, service records,
|
||||
subscriptions and an Async scope. Two independent counts matter: external generation
|
||||
references (handles/function-table leases) and admitted async activities. Every callback,
|
||||
coroutine frame, deferred destructor and operation allocated by a plugin retains an
|
||||
activity pin until it and its terminal callback have returned. Capturing a raw plugin
|
||||
function pointer in a host queue without a pin is forbidden by the adapter contract.
|
||||
|
||||
Retirement stops new generation admission, asks its scope/subscriptions to stop, joins
|
||||
operations, releases provider references, calls deactivate/destroy once, then unmaps
|
||||
only after no code/data reference remains. Host-side reclamation executes after a
|
||||
plugin callback returns; never dlclose from the final callback's stack. Plugin-supplied
|
||||
threads must register activity pins and join during quiescence. Native code is trusted
|
||||
in-process code; it cannot be forcefully sandboxed by this ABI. Uncooperative code stays
|
||||
mapped and is reported as pinned; optional process isolation belongs to [IPC](../subsystems/IPC.md).
|
||||
|
||||
Default: 64 modules, 256 interfaces/module, four retained generations/module, 64 MiB
|
||||
retained mapped-image budget/module based on file accounting, 4 MiB checkpoint,
|
||||
1 MiB configuration, 1,024 async activities/generation and 256 pending callbacks.
|
||||
Mapped-image accounting is not an exact RSS measurement. Refuse further reload when
|
||||
retention budget cannot accommodate old + candidate; never unmap to recover the budget.
|
||||
Defaults for prepare/quiesce/readiness are 5/5/10 seconds within a 30-second total
|
||||
reload deadline. Every phase shares Async's absolute total deadline and injected Time
|
||||
clock; phase budgets can shorten it, never restart it.
|
||||
|
||||
## Reload state machine and rollback
|
||||
|
||||
Per-module transitions are serialized by a reload coordinator, outside the manager map
|
||||
lock. The short lock reserves a generation/expected epoch; expensive filesystem work,
|
||||
all validators, plugin code and release/destructor callbacks run after unlocking.
|
||||
Publication rechecks the epoch. Dependency reload batches topologically order modules;
|
||||
cycles or unsupported mixed activation policies fail before activating anything.
|
||||
|
||||
1. Verify immutable candidate identity/path, ABI and declared dependencies. Create and
|
||||
configure a private candidate using a scoped unpublished Service registry. Activation
|
||||
may prepare resources, but externally visible writes/registration are prohibited
|
||||
until publication. A module unable to stage safely is RestartRequired.
|
||||
2. For a stateless compatible replacement, candidate readiness can overlap old calls.
|
||||
For stateful writers, close old mutation admission and call quiesce: complete all
|
||||
admitted mutations and owned async writes, then checkpoint at Fsm/application state
|
||||
boundaries. Old acquired handles remain valid but new mutation attempts receive
|
||||
`quiescing`; they never run on freed objects. Reads can continue only if declared safe.
|
||||
3. Restore the bounded versioned checkpoint into the candidate, activate deferred parts,
|
||||
and await readiness without registry locks. The adapter requires an explicit resume
|
||||
operation for the old generation; existing IModule's no-op quiesce alone is insufficient.
|
||||
State migration is pure candidate construction; no destructive migration of the old
|
||||
persistent state is permitted during a reversible reload.
|
||||
4. Publish one Service-owned registry snapshot containing candidate interfaces and
|
||||
generation metadata. Host `acquire` and service lookup use that same publication epoch,
|
||||
avoiding inconsistent manager-current versus service-current swaps. Standalone legacy
|
||||
PluginManager keeps its existing local publication until explicitly adapted.
|
||||
5. Retire the old generation and drain pins. Before publication, any failure disposes
|
||||
candidate registrations/activities and resumes old mutation admission after validating
|
||||
its state. Resume failure yields degraded/not-ready status and requests a controlled
|
||||
restart; it never falsely reports the old service healthy. Failed-candidate cleanup
|
||||
errors retain its mapping and are reported separately from the original rejection.
|
||||
|
||||
Publication is a reversible in-memory switch only while old state remains a valid
|
||||
continuation. After new writes, reverting requires a compatible reverse migration or
|
||||
recovery from authoritative persistent state; do not silently discard them. Durable
|
||||
release activation follows Update's healthy marker, as detailed in
|
||||
[ReloadableApplications](../platforms/ReloadableApplications.md).
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
All feature rows are PLANNED.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-PLUGIN-01 | P0 / baseline | Inventory existing exports, descriptor includes, load/reload locks and compatibility fixtures | Existing C++ ABI/state protocol and frozen ShortUrl V1 documented independently / sol_implementer |
|
||||
| M-PLUGIN-02 | P1 / M-PLUGIN-01; M-ASYNC-03 | Explicit generation/activity leases and host-owned retirement queue | Callback/operation/frame held through replacement prevents unmap; late completion releases once / astra_implementer |
|
||||
| M-PLUGIN-03 | P2 / M-PLUGIN-02; Functional errors | Full CAbi.h specification, size/version negotiation, byte ownership, host clock/cancellation bridge and C++ adapter | C-only producer/consumer fixture, truncation/unknown-major rejection, throwing C++ shim contained / astra_implementer |
|
||||
| M-PLUGIN-04 | P2 / M-PLUGIN-03; M-SERVICE-03 | Unlocked staged validation, dependency activation and coherent registry publication | Reentrant validator does not deadlock; failed candidate changes no active lookup / astra_implementer |
|
||||
| M-PLUGIN-05 | P3 / M-PLUGIN-04; M-FSM-04 | Quiesce/checkpoint/restore/readiness/resume protocol with phase/total budgets | Outstanding writer drained; every prepublication phase failure resumes old state or reports degraded / astra_implementer |
|
||||
| M-PLUGIN-06 | P3 / M-PLUGIN-05; Update activation gate | Retention accounting, safe unload capability, reloadable-host integration and migration kit | Stuck pins refuse new reload; post-commit cleanup never triggers invalid rollback / astra_implementer |
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT aggregate command is
|
||||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||||
not rerun here. PROPOSED tests need the NEW ABI and host adapters: C compiler headers,
|
||||
different supported compiler producer/consumer matrix, layout/size checks, hostile length
|
||||
fields, missing release, cancelled async callback after generation retirement, queued
|
||||
std::function/frame pins, failed quiesce/restore/readiness/resume, reentrant observers,
|
||||
rapid replacement epoch conflict, and immutable-path replacement under sustained calls.
|
||||
Compile compatibility claims only for observed matrix entries. Native malicious code
|
||||
is outside the in-process fault model; do not fuzz arbitrary plugins in the host process.
|
||||
|
||||
Measure acquire/reload/quiescence p50/p95/p99, call throughput, allocations, retained
|
||||
generation count, image bytes, peak RSS/CPU and adapter build cost under
|
||||
[PERFORMANCE](../PERFORMANCE.md). No measured reload downtime is claimed.
|
||||
|
||||
Keep current IPlugin/ModuleDescriptor APIs as same-toolchain adapters. A stable C module
|
||||
opts into the new query symbol and tables; existing symbols do not silently change.
|
||||
Existing `PluginHandle::raw_symbol` remains valid only while its handle lives; replace
|
||||
manager-wide borrowed-symbol usage with a pinned lease. Default dlclose stays disabled
|
||||
until activity-pin conformance passes. Rollback can select the legacy manager for
|
||||
legacy plugins before loading; it cannot replay external effects or free stuck code.
|
||||
See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), and [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
|
||||
@@ -0,0 +1,129 @@
|
||||
# Resilience implementation plan
|
||||
|
||||
Status: planning only; all feature tasks PLANNED. Source baseline
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Applies [requirements](../REQUIREMENTS.md) R-005, R-009, R-012, R-014–R-016 and
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-05, C-11, C-13.
|
||||
|
||||
## Current primitives and gaps
|
||||
|
||||
`Void::Resilience` is a native header implementation with no declared module
|
||||
dependencies in [module.cmake](../../../src/Resilience/module.cmake).
|
||||
[Resilience.hpp](../../../include/Void/Resilience/Resilience.hpp) gathers
|
||||
[TokenBucket](../../../include/Void/Resilience/RateLimiter.hpp),
|
||||
[KeyedRateLimiter](../../../include/Void/Resilience/KeyedRateLimiter.hpp),
|
||||
[CircuitBreaker](../../../include/Void/Resilience/CircuitBreaker.hpp), and
|
||||
[ResourceMonitor](../../../include/Void/Resilience/ResourceMonitor.hpp).
|
||||
Injected steady-clock functions already support deterministic tests. Keyed buckets can
|
||||
be capped but default to historical unbounded `max_keys == 0`; cleanup scans the map.
|
||||
ResourceMonitor invokes threshold callbacks outside its mutex and clamps over-release.
|
||||
|
||||
Important implementation gaps: `CircuitBreaker::allow()` admits all callers after
|
||||
transitioning to HalfOpen; its comment about one probe is not enforced by a lease.
|
||||
Late outcomes are not associated with a breaker generation. Token costs/configuration
|
||||
are not validated for negatives/NaN. ResourceMonitor compares `usage_ + amount`, which
|
||||
needs overflow-safe subtraction, and callback setters need synchronized publication.
|
||||
These are proposed repairs, not claims that the current tests expose every issue.
|
||||
Existing [breaker tests](../../../tests/standalone/Resilience/CircuitBreaker.cpp),
|
||||
[bucket tests](../../../tests/standalone/Resilience/RateLimiter.cpp),
|
||||
[keyed tests](../../../tests/standalone/Resilience/KeyedRateLimiter.cpp), and
|
||||
[monitor tests](../../../tests/standalone/Resilience/ResourceMonitor.cpp) exercise
|
||||
transitions, refill, cap/cleanup and hysteresis. Scoped graph coverage reported matching
|
||||
metadata/no recorded gaps for these paths; implementation and test source were inspected.
|
||||
|
||||
## Native policy model and NEW APIs
|
||||
|
||||
Keep synchronous admission primitives standard-library-only, with no scheduler or logging
|
||||
dependency. Put cancellable waits/composition in an optional Async adapter; retries reuse
|
||||
Functional's policy owner rather than creating a second retry engine. Metrics flow through
|
||||
optional [Observability](../subsystems/Observability.md) hooks outside locks.
|
||||
|
||||
```cpp
|
||||
// NEW illustrative Void::Resilience shapes; Result follows C-02.
|
||||
struct BucketConfig { double capacity{100}; double refill_per_second{100}; };
|
||||
struct Admission { bool allowed; std::chrono::nanoseconds retry_after; };
|
||||
class Permit { // move-only; exactly one outcome; release on destruction
|
||||
void finish(Outcome); // success, dependency_failure, neutral
|
||||
};
|
||||
class Breaker {
|
||||
Result<Permit> acquire(); // refusal is CircuitOpen, never an empty success
|
||||
};
|
||||
class Bulkhead {
|
||||
Result<Permit> try_acquire(); // limits active plus admitted waiting work
|
||||
};
|
||||
// Async adapter uses Async-owned OperationOptions and Time-owned Clock.
|
||||
```
|
||||
|
||||
Select consecutive-failure breaker initially: five failures opens; 5-second cooldown;
|
||||
one simultaneous HalfOpen permit; two sequential successful probes close. A permit
|
||||
captures generation and probe identity. Old-generation completions release resources
|
||||
but cannot close a newer Open state. Abandoning a probe is neutral and releases its
|
||||
slot; it does not leave the breaker permanently HalfOpen. Timeout counts only when
|
||||
classified as dependency failure; local overload/caller stop/auth rejection are neutral.
|
||||
Callbacks run outside locks and do not change the recorded outcome on observer failure.
|
||||
|
||||
Token refill uses `max(last, now)` so a clock moving backwards cannot cause later double
|
||||
credit. Validate finite positive capacity/cost, finite nonnegative refill and cost ≤
|
||||
capacity. Zero refill is a finite non-refilling bucket, not an unlimited rate. Costs
|
||||
use checked arithmetic; a failed multi-limit admission rolls back every reservation.
|
||||
NEW keyed defaults: 10,000 keys, maximum encoded key 256 bytes, 5-minute idle retention;
|
||||
cleanup processes at most 256 entries/turn using a maintained cursor. At cap reject new
|
||||
keys; do not evict an active client's bucket and reset its quota. Keys must be normalized
|
||||
by the caller and must not become raw high-cardinality metrics labels.
|
||||
|
||||
Composition order: deadline/stop check → rate admission → bulkhead → breaker permit →
|
||||
one attempt → classify outcome → release permits → retry policy decides next attempt.
|
||||
A retry re-enters limits and shares the original total deadline. Default adapter: three
|
||||
attempts total, full jitter with 100 ms base and 2-second cap, only explicitly retryable
|
||||
and replay-safe work. No retry of an unknown write without identity/dedup support.
|
||||
No queue is created by `try_acquire`; asynchronous waiting is explicit FIFO admission.
|
||||
Default bulkhead is 64 active and 128 waiting; expired waiters are removed before admission.
|
||||
|
||||
## Ownership, limits and failures
|
||||
|
||||
Permits own their reservation until finish/destruction; the limiter state is retained
|
||||
until the last permit returns. Closing stops admission, cancels waiters, and joins owned
|
||||
adapter tasks without destroying in-use state. Observers cannot borrow a dead limiter.
|
||||
Resource budgets count queue, executing attempts and delayed retries separately; default
|
||||
aggregate adapter retention is 8 MiB. Monitoring uses `amount > limit - usage` after
|
||||
invariant checks. New strict permits reject over-release; legacy clamping remains an
|
||||
adapter behavior. Default hysteresis remains high 90%, low 70%, with validated ordering.
|
||||
|
||||
| Fault | Decision | Evidence gate |
|
||||
| --- | --- | --- |
|
||||
| Invalid/NaN config or negative cost | Configuration/input error; consume nothing | Boundary/property tests |
|
||||
| Key/queue cap full | Overload with retry hint when computable | Churn cannot reset live quotas |
|
||||
| Stop while waiting/retrying | Remove waiter/timer, one cancelled result | Stop vs grant/retry race |
|
||||
| Failure races with cooldown probe | Generation decides, one active probe | Hundreds of concurrent acquisitions |
|
||||
| Observer throws/reenters | Isolate observer error; reservation remains correct | Reentrant acquire/release tests |
|
||||
| Dependency outage | Open breaker, bounded retry traffic | Deterministic outage/recovery history |
|
||||
| Clock regresses / integer overflow | No refill gain / reject reservation | Min/max integer and reversed time |
|
||||
|
||||
## Task DAG
|
||||
|
||||
| ID | Phase / dependencies | Implementation and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-RESILIENCE-01 | P0; baseline | Record existing semantics and reproduce probe, invalid-cost and overflow gaps with meaningful regressions | sol_implementer |
|
||||
| M-RESILIENCE-02 | P1; M-RESILIENCE-01, Functional/Time contracts | Validated configurations and machine-readable admission errors; ordinary use needs no runtime | sol_implementer |
|
||||
| M-RESILIENCE-03 | P2; M-RESILIENCE-02 | Generation-bound RAII permits, bounded keyed cleanup, monitor synchronization; races and arithmetic tests pass | astra_implementer |
|
||||
| M-RESILIENCE-04 | P2; M-RESILIENCE-03, Async foundations | Optional bulkhead/wait/retry adapter; finite queues, total deadline, stop/join verified | sol_implementer |
|
||||
| M-RESILIENCE-05 | P3; M-RESILIENCE-04, Net/RPC foundations | Network policy recipes and observations; retries cannot amplify beyond configured attempt/admission budgets | sol_implementer |
|
||||
| M-RESILIENCE-06 | P4; M-RESILIENCE-05, Replication gate | Partition/recovery workloads separate local overload from peer failure; limits never substitute for quorum safety | astra_implementer |
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT tests are the four linked source suites in existing VoidTests; no execution is
|
||||
claimed here. PROPOSED verification adds deterministic model histories, concurrency and
|
||||
sanitizer tests, callback reentrancy, cancelled FIFO waiters and bounded cleanup work.
|
||||
Targets are added in implementation before advertising runner commands; use
|
||||
[VALIDATION](../VALIDATION.md). Benchmark hot-key contention, high key churn, empty/full
|
||||
admission, retry storms and observer overhead; capture p50/p95/p99, throughput, allocations,
|
||||
peak RSS/CPU and build cost per [PERFORMANCE](../PERFORMANCE.md).
|
||||
|
||||
Major-release migration changes zero/unbounded configuration to an explicit policy and
|
||||
replaces boolean breaker admission with a permit. Existing synchronous methods receive
|
||||
deprecated wrappers where semantics can be preserved; do not promise a one-probe guarantee
|
||||
through an API that cannot retain probe ownership. Ship comparison fixtures and a
|
||||
rollback switch for the optional composition layer; never discard active reservations
|
||||
on policy replacement. See [MIGRATION](../MIGRATION.md), [Net](Net.md) and
|
||||
[Messaging](../subsystems/Messaging.md).
|
||||
@@ -0,0 +1,133 @@
|
||||
# Security implementation plan
|
||||
|
||||
Status: planning only; all feature tasks PLANNED. Baseline
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Authority: [requirements](../REQUIREMENTS.md) R-004, R-006, R-009, R-012, R-014–R-016;
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-05, C-07, C-09, C-13.
|
||||
|
||||
## Existing capabilities and boundary
|
||||
|
||||
[Security.hpp](../../../include/Void/Security/Security.hpp) exposes `Void::Security`
|
||||
random URL-safe bearer tokens, BLAKE2b-256 token digests and verification, Argon2id password
|
||||
hashing/verification, random secret keys and authenticated local secret envelopes.
|
||||
[Security.cpp](../../../src/Security/Security.cpp) initializes libsodium once, uses
|
||||
`sodium_memcmp` for decoded token digests, sodium password presets and `crypto_secretbox_easy`.
|
||||
The actual secret format is a 24-byte nonce followed by secretbox's combined authenticated
|
||||
ciphertext, with 16 bytes authentication overhead; preserve these bytes rather than inferring
|
||||
layout from the header's informal description. Existing `SecretKey` is a copyable 32-byte
|
||||
array; existing plaintext/results are ordinary vectors/strings, not secure allocations.
|
||||
|
||||
[module.cmake](../../../src/Security/module.cmake) declares Functional and Sodium::Sodium.
|
||||
[Tests](../../../tests/standalone/Security/Security.cpp) cover token shape/digest, malformed
|
||||
digest rejection, salted Argon2id with Interactive tests, secret round-trip, tampering and
|
||||
wrong-key rejection. A test name mentioning constant time is not timing side-channel proof.
|
||||
No account store, login/session manager, policy engine, TLS identity service or revocation
|
||||
workflow ships here. Graph coverage for all four source files matched metadata with no
|
||||
recorded issue; source verification grounds these claims.
|
||||
|
||||
## Backend and workflow architecture
|
||||
|
||||
Retain libsodium for existing primitives; do not write replacement crypto. Keep low-level
|
||||
primitives usable without Storage, Net or Runtime. [Crypto](Crypto.md) owns interoperable
|
||||
hash/signature primitives; Net owns TLS peer checks. Security owns NEW authentication,
|
||||
principal/session and authorization workflows expressed through injected ports. Concrete
|
||||
Storage/Sqlite adapters are optional higher targets and cannot become primitive dependencies.
|
||||
External identity protocols such as OIDC are a later explicitly versioned adapter capability;
|
||||
initial completion is local accounts and opaque bearer sessions, not an implicit JWT system.
|
||||
|
||||
```cpp
|
||||
// NEW illustrative Void::Security shapes; not existing compilable APIs.
|
||||
class SecureBuffer; // move-only; explicit readable span, wiped on release
|
||||
struct Principal { SubjectId subject; std::vector<RoleId> roles; };
|
||||
struct SessionPolicy { std::chrono::seconds ttl{3600}; std::size_t max_per_subject{16}; };
|
||||
class AccountSessionPort { /* versioned compare/exchange, atomic session create/revoke */ };
|
||||
class Authenticator {
|
||||
Task<Result<SessionGrant>> login(LoginInput, OperationOptions);
|
||||
Task<Result<Principal>> authenticate(BearerToken, OperationOptions);
|
||||
Task<Result<void>> revoke(SessionId, OperationOptions);
|
||||
};
|
||||
Decision authorize(const Principal&, ActionId, const ResourceAttributes&);
|
||||
```
|
||||
|
||||
Result/operation/clock/executor shapes are owned by Functional/Async/Time. Identifiers
|
||||
above are NEW Security domain types; no bearer secret has implicit formatting/serialization.
|
||||
Authenticator holds port ownership through shutdown; a principal is an immutable value
|
||||
snapshot with an authorization-policy generation. Authentication validates identity;
|
||||
authorization evaluates explicit actions and resources, default deny, deny overrides allow.
|
||||
Limit roles to 64/principal, policy rules to 4,096 and expression depth to 16. First policy
|
||||
language is native typed predicates without arbitrary scripts or filesystem/network access.
|
||||
|
||||
Login dataflow: bounded parse → identity normalization → rate admission → account lookup →
|
||||
bounded password job → credential-version check → atomic session write → return raw token
|
||||
once. Unknown account and wrong password share public denial and comparable work using a
|
||||
precomputed dummy hash; internal audit reasons differ. Credential changes racing with login
|
||||
invalidate the write through the port's version precondition. Store only digest, subject,
|
||||
expiry, roles/policy version and revocation generation. Tokens contain 32 entropy bytes;
|
||||
logging, URLs and metrics never carry them. Rehash-on-success uses a version-checked update
|
||||
and must not accidentally resurrect disabled credentials.
|
||||
|
||||
Authenticate hashes the token and reads the authoritative session state on every call
|
||||
initially; positive caching is disabled so revocation has no hidden cache window. TTL uses
|
||||
civil time injected by Time with an explicit clock-health check; monotonic deadlines govern
|
||||
operations. Startup clock rollback beyond configured 60-second tolerance fails session
|
||||
admission until reconciled. This tolerance is not a distributed clock safety guarantee.
|
||||
Revocation succeeds only after durable port acknowledgement. Lost replies have unknown
|
||||
outcome; query/retry by session identity. Authorization has no network side effects.
|
||||
|
||||
## Resource and failure decisions
|
||||
|
||||
NEW defaults: password input ≤1 KiB, encoded hashes ≤1 KiB, tokens ≤512 bytes, local secret
|
||||
plaintext ≤16 MiB. Select Moderate for new stored passwords; accept supported existing
|
||||
encoded strengths only within an operator-approved verification budget. Do not reduce hash
|
||||
strength silently. Password jobs reserve their encoded memory cost before starting: default
|
||||
aggregate 512 MiB, at most two jobs and 32 waiters. If a preset exceeds the budget, report
|
||||
configuration/resource error. Password computation is not forcibly interruptible; cancelled
|
||||
jobs retain buffers/budget until completion, discard output and cannot create a session.
|
||||
Default sessions: 10,000 total, 16/subject, one-hour TTL; capacity includes unexpired entries.
|
||||
Explicit expiry cleanup is bounded at 256 records/turn. Shutdown closes admission and joins
|
||||
credential jobs before clearing secure buffers.
|
||||
|
||||
SecureBuffer uses sodium-assisted wiping and optional locked allocation; inability to meet
|
||||
a required locked-memory policy is an error, never an implicit downgrade. It does not claim
|
||||
to prevent every copy made by application code, swapping policy or core dumps. Add a NEW
|
||||
versioned secret envelope with magic/version/algorithm/key-id/length and authenticated metadata;
|
||||
legacy nonce+combined-ciphertext decoding stays a separate explicitly selected API. New writers
|
||||
never guess legacy format after authentication failure. Key rotation reads old key IDs, writes
|
||||
only the active ID, and retires a key only after an inventory proves no required ciphertext remains.
|
||||
|
||||
| Trigger | Outcome and ownership | Validation |
|
||||
| --- | --- | --- |
|
||||
| Sodium init / randomness failure | Backend error; publish no token/key | Backend fault seam |
|
||||
| Wrong/malformed credentials | Public denied; bounded work and internal audit reason | No user enumeration in response |
|
||||
| Encoded password requests excessive cost | Reject before costly allocation | Malicious encoded-hash corpus |
|
||||
| Store unavailable / policy load invalid | Fail closed; do not issue anonymous success | Port outage and version races |
|
||||
| Stop during hash | One cancelled result; running job drains, no session write | Cancellation vs completion |
|
||||
| Session expired/revoked | Denied; never recreate from token alone | Revoke/login/clock histories |
|
||||
| Secret authentication fails | Error with no plaintext publication | Every field and key mutation |
|
||||
| Observer/audit failure | Explicit audit policy; local login default fails if mandatory audit cannot admit | Full audit queue, no secrets retained |
|
||||
|
||||
## Task DAG and acceptance
|
||||
|
||||
| ID | Phase / dependencies | Scope and gate | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-SECURITY-01 | P0; baseline | Freeze token/password/secret fixtures including actual envelope bytes; distinguish test names from security proof | sol_implementer |
|
||||
| M-SECURITY-02 | P1; M-SECURITY-01, Memory/Functional contracts | SecureBuffer, input/cost validation, error separation; wipe and allocation-failure tests | astra_implementer |
|
||||
| M-SECURITY-03 | P2; M-SECURITY-02, Async/Time/Resilience gates | Account/session ports and local workflows; revocation, version races, capacity and hash-stop tests pass | astra_implementer |
|
||||
| M-SECURITY-04 | P2; M-SECURITY-03 | Typed default-deny authorization and versioned secret/key rotation; unknown policy/version fails closed | astra_implementer |
|
||||
| M-SECURITY-05 | P3; M-SECURITY-04, Storage or Sqlite adapter, Net | Durable auth adapter and network integration; no Security→Storage/Net cycle, restart/revocation acceptance | sol_implementer |
|
||||
| M-SECURITY-06 | P4; M-SECURITY-05, Replication | Optional replicated auth port; quorum revocation and partition denial tested; external identity remains a separate capability gate | astra_implementer |
|
||||
|
||||
CURRENT verification is existing VoidTests source coverage above; nothing rerun here.
|
||||
PROPOSED checks require deterministic port/clock fixtures, malformed hashes/envelopes,
|
||||
secret-lifetime instrumentation, concurrent revocation and backend error injection before
|
||||
new runner commands are documented. Measure password queue/work latency separately, token
|
||||
lookup p50/p95/p99, throughput, allocation/RSS/CPU and build cost; run under fixed memory
|
||||
budgets, not reduced password cost to improve a benchmark. See [PERFORMANCE](../PERFORMANCE.md),
|
||||
[VALIDATION](../VALIDATION.md), and [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
|
||||
|
||||
Migration preserves old verification and secret decoding, while new APIs adopt move-only
|
||||
secrets and explicit policy. Do not reinterpret old envelope bytes or silently turn existing
|
||||
digest storage into session authentication. Rollback keeps old keys/readers until all new
|
||||
records are supported; disable new writers before reverting. Invalid-policy rollback
|
||||
retains the last validated immutable policy only when the operator explicitly selects that
|
||||
policy; it cannot manufacture authorization. See [MIGRATION](../MIGRATION.md).
|
||||
@@ -0,0 +1,159 @@
|
||||
# Service ownership, lifecycle and replacement plan
|
||||
|
||||
Status: PLANNED feature work. Baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`,
|
||||
inspected 2026-11-24. Requirements R-004, R-009, R-010 and R-013–R-016 apply.
|
||||
[Architecture](../ARCHITECTURE.md) C-02–C-05 and C-09 owns shared semantics.
|
||||
|
||||
## Existing source baseline
|
||||
|
||||
[Service.hpp](../../../include/Void/Service/Service.hpp) defines
|
||||
`Void::Service::IService`, with `service_name`, `on_start`, and `on_stop`.
|
||||
[Registry.hpp](../../../include/Void/Service/Registry.hpp) defines
|
||||
`ServiceRegistry`: type-indexed shared_ptr providers, replacement/removal, local-first
|
||||
parent lookup, and registration/reverse-registration lifecycle order. `get<I>()`
|
||||
returns an owning shared_ptr, but `require<I>()` returns `I&` after a temporary owning
|
||||
lookup; concurrent replacement can invalidate that reference. `start_all`/`stop_all`
|
||||
invoke callbacks while holding a registry shared lock. Parent lifetime is borrowed.
|
||||
Lifecycle has no dependency DAG, readiness or failed-start rollback contract.
|
||||
|
||||
[PluginService.hpp](../../../include/Void/Service/PluginService.hpp) provides
|
||||
`PluginServiceBinding<I>` using `void_plugin_service`, RTTI cross-cast validation and
|
||||
an aliasing shared_ptr that retains a `PluginHandle`. Its existing generation pin is
|
||||
valuable; C linkage for the factory does not make the returned C++ IService stable
|
||||
across toolchains. [module.cmake](../../../src/Service/module.cmake) declares Functional
|
||||
and Log, while the optional plugin bridge's includes reach Plugin. Packaging that
|
||||
bridge separately is part of the target dependency cleanup, not a reason for Plugin
|
||||
and Service core to depend cyclically on one another.
|
||||
|
||||
Existing [registry tests](../../../tests/standalone/Service/Registry.cpp) cover provider
|
||||
lookup/replacement/removal and lifecycle order;
|
||||
[scoped tests](../../../tests/standalone/Service/ScopedRegistry.cpp) cover parent
|
||||
fallback/shadowing; [orchestrator tests](../../../tests/standalone/Service/Orchestrator.cpp)
|
||||
exercise consumers in Fsm. Graph paths were coverage-checked; PluginService line 52
|
||||
was directly read. Important callback and ownership conclusions were source-verified.
|
||||
|
||||
## NEW owning API and registry model
|
||||
|
||||
Design sketch; these additions are not existing declarations:
|
||||
|
||||
```cpp
|
||||
namespace Void::Service {
|
||||
template<class I> class ServiceHandle { // owns provider and code pin
|
||||
public:
|
||||
I* operator->() const noexcept;
|
||||
std::uint64_t generation() const noexcept;
|
||||
};
|
||||
// NEW registry methods:
|
||||
// acquire<I>() -> Result<ServiceHandle<I>>;
|
||||
// prepare_batch(ProviderSet, ExpectedEpoch) -> Result<PreparedPublication>;
|
||||
// publish(PreparedPublication&&) -> Result<PublicationEpoch>;
|
||||
// start(options) / close_and_join(options) use Async::OperationOptions.
|
||||
}
|
||||
```
|
||||
|
||||
ServiceHandle owns an immutable provider record: interface pointer, shared provider
|
||||
owner, generation pin and publication epoch. Copies extend lifetime. Acquisition of
|
||||
an absent provider returns `missing_service`; a stopped admission gate returns
|
||||
`service_stopping`. The handle is held across an entire call/await. Removing a registry
|
||||
entry prevents new lookup but never invalidates acquired handles or releases plugin
|
||||
code while a continuation is active. Provider retirement is distinct from destruction.
|
||||
|
||||
Use immutable registry snapshots and one atomic retained-snapshot pointer. A batch
|
||||
publication atomically replaces all interfaces belonging to a generation; a request
|
||||
needing a coherent group acquires one snapshot. Type-index keys remain same-toolchain
|
||||
only; stable C interface IDs and version negotiation belong to [Plugin](Plugin.md).
|
||||
ProviderSet rejects duplicate interface IDs, null providers, missing required
|
||||
dependencies and cycles. Aliases of one lifecycle object have a single lifecycle node.
|
||||
|
||||
The base registry is native standard containers/shared ownership, without Runtime,
|
||||
Plugin or a concrete telemetry dependency. Async lifecycle support and the plugin
|
||||
binding are higher adapters. A child snapshot retains its parent snapshot, so it can
|
||||
outlive the parent registry object; new parent publications are observed only through
|
||||
explicit child refresh/new acquisition policy. Choose snapshot parent semantics for
|
||||
NEW scoped handles and document the difference from today's live borrowed fallback.
|
||||
|
||||
## Startup, rollback and safe replacement
|
||||
|
||||
Provider descriptions declare stable local service IDs and required/optional edges.
|
||||
Topologically sort required edges with registration sequence as a deterministic tie
|
||||
break. Prepare a retained lifecycle snapshot under a short guard, then release the
|
||||
guard before invoking any application callback. Lifecycle operations are serialized
|
||||
by a coordinator state machine; ordinary lookups do not wait for callback execution.
|
||||
Reentrant lookup is supported. Reentrant lifecycle mutation queues a bounded request
|
||||
for the next epoch rather than recursively starting/stopping services.
|
||||
|
||||
Start transitions constructed → starting → ready. A provider's start/ready call may
|
||||
fail; then stop every provider whose start succeeded in reverse dependency order.
|
||||
Also call the failed provider's specified abort-start cleanup to release partial work.
|
||||
Aggregate cleanup errors while retaining the original startup error. Providers are
|
||||
unpublished until the required set is ready. Legacy void callbacks adapt by catching
|
||||
exceptions at the C++ boundary and mapping them into structured failures.
|
||||
|
||||
Replacement prepares candidate providers in a private snapshot and validates readiness
|
||||
before publication. ExpectedEpoch prevents stale concurrent replacements. The publish
|
||||
guard performs only a preallocated pointer swap; the old snapshot is retired outside
|
||||
the guard so final shared_ptr destruction cannot run user destructors under a lock.
|
||||
Notification callbacks run outside locks. A failed candidate keeps the old snapshot.
|
||||
Publication success is not a durable Update commit; that belongs to VersionStore.
|
||||
|
||||
Retired providers stop admitting new mutations when their owner requests quiescence,
|
||||
while existing handles remain valid for their documented operations. Their owned Async
|
||||
scope drains before `on_stop`/destruction. Do not call stop merely because a newer
|
||||
provider was published if that would invalidate an acquired handle. A retired-generation
|
||||
coordinator retains cleanup responsibility until all calls and async pins end. Stateless
|
||||
readers may overlap generations; stateful writers require Plugin's quiescence protocol.
|
||||
Shutdown stops publication and lookup admission, stops dependents before dependencies,
|
||||
joins their work, then releases owners. Noncooperative work yields a shutdown report
|
||||
and keeps owners retained; a deadline never licenses freeing live providers.
|
||||
|
||||
## Bounds, failures and observability
|
||||
|
||||
Default 256 providers/registry, 16 parent levels, 1,024 dependency edges, 64 staged
|
||||
changes, 128 lifecycle requests and four retained publication generations. Admission
|
||||
over these limits returns overload before invoking callbacks. At most one lifecycle
|
||||
transaction prepares per registry; concurrent requests have expected-epoch conflicts
|
||||
or bounded waiting using [Async](Async.md) options. Retention exhaustion refuses new
|
||||
replacement until pins drain. No forced eviction of old code or provider objects.
|
||||
|
||||
Errors distinguish missing, conflict, cycle, start failure, not-ready, stop failure,
|
||||
cancelled, timed-out and retained-generation limit. Emit optional bounded observations
|
||||
for epochs, retained handles, callback duration and rollback outcomes, with
|
||||
[Observability](../subsystems/Observability.md) adapters above the registry. Do not log
|
||||
configuration payloads or capture transient thread-local context. Stable interface IDs
|
||||
are not authorization; application policy controls which providers may be registered.
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
Every row is PLANNED.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-SERVICE-01 | P0 / baseline | Characterize borrowed require, lock-held callbacks, parent and alias lifetime; package bridge map | Regression cases distinguish owning get from borrowed require; declared dependencies recorded / sol_implementer |
|
||||
| M-SERVICE-02 | P1 / M-SERVICE-01; Functional error gate | Owning handles, immutable snapshots, retained parents, atomic provider batches | Old handles survive remove/replace/parent destruction; batch readers see one epoch / astra_implementer |
|
||||
| M-SERVICE-03 | P2 / M-SERVICE-02; Async scopes | Dependency lifecycle coordinator, readiness, failed-start cleanup and reverse rollback | Callback can acquire services without deadlock; middle-node failure leaves nothing newly published / astra_implementer |
|
||||
| M-SERVICE-04 | P2 / M-SERVICE-03; Plugin pin gate | Separate plugin bridge adapter, staged publication, retired-provider drain | In-flight async call pins exact generation through completion; no callback/destructor under registry guard / astra_implementer |
|
||||
| M-SERVICE-05 | P3 / M-SERVICE-04; Configuration snapshot gate | Bounded retention, Runtime/Fsm composition and migration | Retention saturation rejects reload; shutdown joins dependency graph and reports incomplete owners / sol_implementer |
|
||||
|
||||
## Validation, performance and migration
|
||||
|
||||
CURRENT aggregate command:
|
||||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||||
not rerun here. PROPOSED tests require NEW APIs: concurrent remove/acquire, provider
|
||||
destructor reentering registry, start callback registering another service, duplicate
|
||||
lifecycle aliases, parent destruction, dependency cycles, readiness timeout, second
|
||||
provider start failure, stop throws, reader held across four reloads, and async callback
|
||||
completion after publication. Lifetime/race sanitizers supplement deterministic barriers.
|
||||
|
||||
Measure acquisition and publication p50/p95/p99, lookup throughput under read/write
|
||||
contention, allocations, retained provider RSS/CPU, shutdown latency and template build
|
||||
cost per [PERFORMANCE](../PERFORMANCE.md). Compare immutable snapshots with the existing
|
||||
shared-mutex path using identical service sets; do not assert universal improvement.
|
||||
|
||||
EXISTING `auto& svc = registry.require<I>();` migrates to NEW
|
||||
`auto svc = registry.acquire<I>();` and retaining `*svc` through the call. Existing
|
||||
`get<I>()` remains a safe ownership bridge for simple same-toolchain providers.
|
||||
Deprecate borrowed require before removal at the major boundary. Legacy registration
|
||||
order is retained in the no-dependency adapter; dependency-aware startup is explicit.
|
||||
Never roll back a published generation by destroying live handles: publish another
|
||||
validated snapshot. See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||||
[Runtime](../subsystems/Runtime.md), [Fsm](Fsm.md), and [DELIVERY](../DELIVERY.md).
|
||||
@@ -0,0 +1,123 @@
|
||||
# ShortUrl implementation plan
|
||||
|
||||
Status: planning only; all feature tasks PLANNED. Baseline
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Authority: [requirements](../REQUIREMENTS.md) R-004, R-010, R-014–R-016;
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-05, C-09, C-13.
|
||||
|
||||
## Frozen source contract, not a shipped provider
|
||||
|
||||
[ShortUrl.hpp](../../../include/Void/ShortUrl/ShortUrl.hpp) declares the EXISTING
|
||||
`Void::ShortUrl::V1` service, current aliases in `Void::ShortUrl`, service ID
|
||||
`void.short-url`, version 1, request/result/error types, health and `IShortener`.
|
||||
`IShortener` derives from Service::IService; resolution defaults to `ErrorCode::unsupported`.
|
||||
There is no built-in storage or HTTP provider in this module's inventory.
|
||||
[module.cmake](../../../src/ShortUrl/module.cmake) declares only Service.
|
||||
[Tests](../../../tests/standalone/ShortUrl/ShortUrl.cpp) exercise a test subclass, identity,
|
||||
shorten result and optional resolution. This is not a production provider acceptance test.
|
||||
All three source paths reported matching graph metadata/no recorded issue and were read.
|
||||
|
||||
The existing [contract document](../../short-url.md) is preserved. V1 enum ordinals,
|
||||
member order and virtual order are frozen; same-toolchain C++ ABI restrictions remain.
|
||||
Nonempty custom keys and nonzero expiry must be honored or rejected as unsupported/conflict.
|
||||
Zero expiry means permanent; a returned owning provider handle must pin its implementation
|
||||
for the whole call. The existing header's `unsupported` is the exact error enumerator.
|
||||
|
||||
## Completion scope and NEW interfaces
|
||||
|
||||
Build native provider logic around injected repository/clock/randomness ports. Keep V1
|
||||
headers dependent only on Service; optional local and remote provider targets own Storage
|
||||
and Net dependencies respectively. No external short-link service/account is assumed.
|
||||
Select the original [Storage](../subsystems/Storage.md) as the first durable local adapter;
|
||||
an in-memory test adapter establishes semantics but is explicitly nondurable.
|
||||
|
||||
```cpp
|
||||
// NEW illustrative types, outside the frozen V1 interface.
|
||||
namespace Void::ShortUrl::V2 {
|
||||
struct ShortenOptions { OperationOptions operation; OperationId id; };
|
||||
struct Link { std::string key; std::string target_url; Expiry expiry; };
|
||||
class Provider {
|
||||
Task<Result<Link>> shorten(CreateLink, ShortenOptions);
|
||||
Task<Result<Link>> resolve(Key, OperationOptions);
|
||||
Task<Result<void>> revoke(Key, OperationOptions);
|
||||
};
|
||||
}
|
||||
// NEW LocalProvider composes LinkRepositoryPort, Time clock and Security randomness.
|
||||
// NEW V1Adapter implements V1::IShortener without adding virtuals or changing layout.
|
||||
```
|
||||
|
||||
Async owns operation options and task lifecycle; Functional owns Result. V2 uses a new
|
||||
service version/lookup entry, never replaces a V1 provider under an incompatible cast.
|
||||
The proposed Service C ABI is a separate adapter, not a reinterpretation of V1 objects.
|
||||
V1Adapter blocks only on an allowed calling thread and maps domain errors to existing
|
||||
ErrorCode values. It cannot pretend V1 has cooperative cancellation or request identity.
|
||||
|
||||
Local create dataflow: validate URL/key/expiry → authorization/rate admission at the host →
|
||||
generate or validate key → conditional insert plus operation-result record atomically →
|
||||
durable acknowledgement → construct short URL from configured canonical public base.
|
||||
Targets accept absolute http/https, no userinfo/control characters; no fetch/preview happens
|
||||
by default, so create does not contact the target. Host policy can forbid destinations;
|
||||
if previews are later added, SSRF controls are a separate mandatory capability gate.
|
||||
Default generated key is 16 base62 characters from rejection-sampled secure randomness;
|
||||
eight collision retries then conflict/resource error. A custom key is 1–64 ASCII
|
||||
alphanumerics, '-' or '_', case-sensitive, with reserved route names rejected. Target URL
|
||||
limit is 8 KiB. Key and target are owned immutable values after admission.
|
||||
|
||||
Records contain key, exact target, expiry, revocation flag, creation identity and schema
|
||||
version. Resolve reads one consistent record: absent → not_found, revoked → revoked,
|
||||
expired → expired, otherwise return exact stored URL. Expiry is an injected civil instant;
|
||||
clock-health failures do not extend a link silently. Cleanup is separate from logical expiry.
|
||||
Revoke creates a tombstone; key reuse is disabled initially so cached old links cannot point
|
||||
at a new target. V2 idempotency records make retries safe within a configured 24-hour
|
||||
retention window; expired identities return identity_expired, with no silent retry claim.
|
||||
|
||||
RemoteProvider is a NEW generic adapter SPI: explicit origin, secure Net policy, request/
|
||||
response schema and capability flags. Every provider supplies a conformance fixture;
|
||||
unsupported custom key/expiry/resolve is reported before network mutation where possible.
|
||||
Remote errors preserve retry-after and unknown-outcome classification internally; the V1
|
||||
mapping uses provider_error/unavailable/timeout without fabricating a local rollback.
|
||||
|
||||
## Limits and failure matrix
|
||||
|
||||
NEW defaults: 128 concurrent operations, 256 waiters, 16 MiB transient budget; remote
|
||||
responses ≤1 MiB and 10-second total deadline. Local live/tombstone entries have a configured
|
||||
disk quota, initially 1 GiB, and 10,000 retained V2 operation outcomes; full retention blocks
|
||||
new creates until cleanup, never drops active identities arbitrarily. Tombstones count toward
|
||||
quota; reclamation/key reuse requires a later explicit compatibility design. No module-global
|
||||
worker; managed hosts own cleanup scheduling. Shutdown stops admission and joins storage/network
|
||||
operations; V1 plugin pins remain held until synchronous calls finish.
|
||||
|
||||
| Fault | Required outcome | Gate |
|
||||
| --- | --- | --- |
|
||||
| Invalid URL/key/expiry | invalid_request/invalid_url; no mutation | Encoded/control/scheme boundary corpus |
|
||||
| Custom key collision | conflict, no overwrite | Concurrent conditional inserts |
|
||||
| Unsupported capability | unsupported, no ignored request fields | Provider conformance matrix |
|
||||
| Disk/sync failure | storage or unknown commit outcome; inspect/retry by V2 ID | Crash after commit before reply |
|
||||
| Remote timeout after send | timeout with unknown outcome internally; no blind create replay | Lost response test |
|
||||
| Expiry/revoke races | Resolve sees a consistent record; no target resurrection | Controlled clock and transaction histories |
|
||||
| Provider unload during call | Owning Service pin retains generation | Reload during blocked shorten |
|
||||
| Quota/queue exhausted | rate_limited or resource/unavailable mapping, bounded retention | Full quota plus churn |
|
||||
|
||||
## Task DAG
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-SHORTURL-01 | P0; baseline | Freeze V1 headers/ABI fixtures and exact semantics; test aliases and default unsupported | sol_implementer |
|
||||
| M-SHORTURL-02 | P1; M-SHORTURL-01, Service/Functional contracts | NEW V2/domain ports and V1 adapter specification; no V1 layout or method edits | astra_implementer |
|
||||
| M-SHORTURL-03 | P2; M-SHORTURL-02, Time/Security, Storage conditional batches | Native local provider with durable identity and quota; crash/conflict/expiry tests | sol_implementer |
|
||||
| M-SHORTURL-04 | P2; M-SHORTURL-02, Net secure/streaming gate | Remote provider SPI and fixture provider; capability and unknown-outcome tests, no shipped external account assumption | sol_implementer |
|
||||
| M-SHORTURL-05 | P3; M-SHORTURL-03, M-SHORTURL-04, Plugin/Service | Host wiring, metrics and reloadable pins; compatible V1 consumers pass | astra_implementer |
|
||||
| M-SHORTURL-06 | P4; M-SHORTURL-05, DistributedStorage single-group gate | Optional replicated repository adapter; minority create rejection, committed resolve/revoke history | astra_implementer |
|
||||
|
||||
CURRENT checks are linked source tests registered in VoidTests, not rerun here. PROPOSED
|
||||
provider contract fixtures, process crash points, schema/ABI consumers and reload races
|
||||
must be added before runner commands are documented. Measure create/resolve p50/p95/p99,
|
||||
throughput, allocations, RSS/CPU, collision retries, retained records and build cost under
|
||||
[PERFORMANCE](../PERFORMANCE.md); do not infer provider readiness from interface tests.
|
||||
|
||||
Migration leaves V1 and [docs/short-url.md](../../short-url.md) intact. Introduce V2 and
|
||||
versioned records additively, with V1 mapping tests and explicit data export. Rollback
|
||||
disables new writes, retains readable old records and provider generations, and never
|
||||
reuses revoked keys. See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||||
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md), and
|
||||
[NetworkedApplications](../platforms/NetworkedApplications.md).
|
||||
@@ -0,0 +1,165 @@
|
||||
# Sqlite — first-class SQLite C API integration
|
||||
|
||||
Status: plan; all implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
R-007 and [C-02–C-05/C-08](../ARCHITECTURE.md) require this module to remain distinct from
|
||||
the original [Storage](../subsystems/Storage.md) engine.
|
||||
|
||||
## Source-backed baseline
|
||||
|
||||
[Sqlite.hpp](../../../include/Void/Sqlite/Sqlite.hpp) exposes `Void::Sqlite::Database`,
|
||||
`Statement`, `Transaction`, `Migration`, `OpenMode` and a local Result alias. Database and
|
||||
Statement are move-only RAII wrappers. Bind indexes are one-based; column indexes are
|
||||
zero-based. `step()` returns Result<bool>, text reads copy, transactions roll back on
|
||||
destruction unless marked done, and migrations use `PRAGMA user_version`.
|
||||
[module.cmake](../../../src/Sqlite/module.cmake) links Functional and SQLite3::SQLite3.
|
||||
|
||||
[Sqlite.cpp](../../../src/Sqlite/Sqlite.cpp) opens writable databases with a 5,000 ms busy
|
||||
timeout and attempts WAL/foreign_keys pragmas without checking their results. Bind/reset
|
||||
and clear-bindings ignore SQLite return codes. Transaction stores a raw Database pointer,
|
||||
and `commit()` marks it done before calling SQLite. Database close ignores the close result.
|
||||
These are concrete lifecycle/error-completion targets, not evidence that all uses fail.
|
||||
[Tests](../../../tests/standalone/Sqlite/Sqlite.cpp) cover memory open, SQL execution,
|
||||
binding/nulls, successful commit, destructor rollback, migrations and bad SQL; they do
|
||||
not establish busy-commit recovery, database moves with live transactions or WAL durability.
|
||||
|
||||
## Backend decision and NEW API
|
||||
|
||||
Keep SQLite itself as the SQL engine, pager, locking and file-format owner. Void supplies
|
||||
checked RAII, lifetimes, configuration, async admission and migrations. Do not reimplement
|
||||
SQL, parse database pages, or translate Storage batches into a pretend identical SQL API.
|
||||
Pin/test supported SQLite versions through [build/distribution](../BUILD-AND-DISTRIBUTION.md);
|
||||
capture runtime version/compile options in diagnostics without claiming untested versions.
|
||||
|
||||
NEW illustrative additions in `Void::Sqlite`:
|
||||
|
||||
```cpp
|
||||
enum class JournalMode { Wal, Rollback };
|
||||
enum class SyncMode { Full, Normal };
|
||||
enum class BeginMode { Deferred, Immediate, Exclusive };
|
||||
struct OpenOptions; // mode, journal/sync, limits, busy budget, capabilities
|
||||
struct SqliteError; // primary and extended code, bounded message, operation
|
||||
Result<Database> open_database(path, OpenOptions);
|
||||
Result<void> Statement::bind_checked(int, ValueView);
|
||||
Result<void> Statement::reset_checked();
|
||||
Result<Transaction> Database::begin(BeginMode);
|
||||
Result<void> Database::close();
|
||||
Result<CheckpointReport> Database::checkpoint(CheckpointMode);
|
||||
```
|
||||
|
||||
These are proposals, not existing declarations. ValueView is a NEW typed view over null,
|
||||
int64, double, text and blob. Checked text/blob bindings copy by default; borrowed/static
|
||||
bindings require an explicit lifetime owner retained until reset/rebind/finalize. Row views
|
||||
expire at the next step/reset/finalize and cannot cross an await; owning row copies are
|
||||
available. Typed reads reject unexpected type/range instead of silently coercing a text
|
||||
column to zero. Named binds and blobs complete the basic API; parameter metadata validates
|
||||
indexes, and strict single-statement prepare rejects non-whitespace trailing SQL.
|
||||
|
||||
Use a shared ConnectionState independent of the Database object's address. Statements and
|
||||
transactions retain it, so moving/destroying a Database handle does not leave dangling
|
||||
transaction pointers. NEW `close()` stops admission and returns Busy while handles remain;
|
||||
destructor release defers final native close to the last owner and reports errors to an
|
||||
optional bounded diagnostic hook. Explicit finalization is available when error reporting
|
||||
matters. Native `handle()` access is an expert borrow under the connection's execution lease;
|
||||
it does not grant concurrent unsynchronized use or ownership transfer.
|
||||
|
||||
## Transactions, concurrency and operational behavior
|
||||
|
||||
A connection has one execution owner at a time. Embedded synchronous callers serialize
|
||||
operations explicitly. Managed async use moves work to a bounded blocking executor and
|
||||
leases one connection for the complete transaction; no await releases that lease midway
|
||||
through a transaction. SQLite's internal mutex modes do not replace wrapper object-lifetime
|
||||
rules. Read pools default to four connections, with one writer lane; users opt into other
|
||||
topologies knowingly. No global connection/thread pool is created by opening a Database.
|
||||
|
||||
Transaction state is Active, Committed, RolledBack or RecoveryRequired. Set Committed only
|
||||
after successful COMMIT. A busy COMMIT can leave the transaction active; retain rollback/
|
||||
retry capability and query SQLite's autocommit state after errors before deciding whether
|
||||
it was automatically rolled back. This follows SQLite's [transaction semantics](https://www.sqlite.org/lang_transaction.html)
|
||||
and [autocommit query](https://www.sqlite.org/c3ref/get_autocommit.html). Do not blindly replay
|
||||
statements or automatically rerun a whole transaction after an error: triggers and external
|
||||
callbacks may already have effects. Savepoints are NEW separately owned nested scopes;
|
||||
ordinary `begin` inside an active transaction fails rather than pretending to nest.
|
||||
|
||||
NEW defaults for file databases are checked WAL + synchronous FULL + foreign_keys ON.
|
||||
Query effective pragma results and fail configuration if a required mode is unavailable.
|
||||
In-memory/read-only databases have explicitly different effective capabilities. NORMAL is
|
||||
an explicit weaker durability choice. WAL permits readers alongside one writer, but long
|
||||
read transactions can hold back checkpoints; it also requires same-host shared-memory
|
||||
coordination and is not the selected network-filesystem deployment mode.
|
||||
[SQLite WAL documentation](https://sqlite.org/wal.html) defines these constraints; no claim
|
||||
is made that Void's native WAL shares SQLite's layout or exact durability modes.
|
||||
|
||||
Busy waiting uses a bounded configured budget (default five seconds), capped by the shared
|
||||
absolute operation deadline. Install cancellation/progress handling per leased operation,
|
||||
and clear it before connection reuse. A connection-wide interrupt must never accidentally
|
||||
cancel the next borrower's query; serialize lease handoff through completion and native
|
||||
interrupt cleanup. Stop can prevent execution or interrupt supported SQLite work, but a
|
||||
commit racing with stop may have taken effect. Return domain outcome evidence rather than
|
||||
claiming cancellation rolled it back. Avoid busy sleeps on an IO event-loop thread.
|
||||
|
||||
Checkpoint reports completed/remaining pages and Busy, with no automatic promise to shrink
|
||||
a WAL held by readers. Default managed policy requests passive checkpoints at 16 MiB WAL,
|
||||
warns at 64 MiB, and stops new write admission at a configured 256 MiB application threshold
|
||||
until reader/checkpoint progress permits it. This is a wrapper admission policy, not a hard
|
||||
SQLite file-size guarantee against other processes. Monitor external writers separately.
|
||||
Never delete a live `-wal`/`-shm` file to reclaim space.
|
||||
|
||||
## Completion capabilities and budgets
|
||||
|
||||
Defaults for NEW wrappers: 128 live statements/connection, 1 MiB SQL text, 16 MiB bound
|
||||
value/row-copy limit, 1,024 queued jobs and 64 MiB aggregate pending input, 64 cached
|
||||
statements with an 8 MiB wrapper-memory ceiling. Evict only idle cache entries; an active
|
||||
statement belongs to its borrower. Apply SQLite limit APIs where supported, and separately
|
||||
bound wrapper allocations. SQLite pager/cache memory is configured and measured, not
|
||||
assumed equal to wrapper memory. Bulk operations stream rows within one explicitly sized
|
||||
transaction; a `query_all` convenience has a row and byte cap.
|
||||
|
||||
Migration completion validates a strictly increasing unique version list before any SQL.
|
||||
The application supplies immutable migration identities/checksums; record them in an
|
||||
application migration table in the same transaction as schema changes and user_version.
|
||||
Reject unexpected newer schemas and checksum drift. A migration may be non-reversible;
|
||||
require a verified backup and explicit application rollback plan before applying it. Do
|
||||
not infer a down-migration from reversing SQL strings. Backup/restore use SQLite's supported
|
||||
backup interface with bounded steps and consistent source lifetime, not a raw copy of an
|
||||
open database file. Extension loading remains disabled by default; optional functions,
|
||||
collations and authorizers have explicit lifetime and no-exception-across-C-callback wrappers.
|
||||
|
||||
## Ordered tasks
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-SQLITE-01 | P0; existing tests, official SQLite contracts | Regress bind errors, busy/failed commit, outstanding statement close and move-with-live-transaction; record supported runtime/build options. | astra_implementer |
|
||||
| M-SQLITE-02 | P1; M-SQLITE-01, Functional typed errors | ConnectionState ownership, checked bind/reset/finalize/close and transaction states; failed COMMIT cannot disable necessary rollback. | astra_implementer |
|
||||
| M-SQLITE-03 | P2; M-SQLITE-02 | Checked options/pragmas, typed rows/blobs/named params, savepoints and migrations; malformed options/schema plans fail before mutation. | sol_implementer |
|
||||
| M-SQLITE-04 | P2; M-SQLITE-03, Async/Time ownership | Leased async connections, bounded jobs, cancellation/busy handling; no cross-query interrupt or transaction interleaving. | astra_implementer |
|
||||
| M-SQLITE-05 | P3; M-SQLITE-03/04, IO/Runtime operations | Checkpoint/backup/restore, health metrics and guarded callback adapters; active-reader pressure is visible and backup restores consistently. | astra_implementer |
|
||||
| M-SQLITE-06 | P3; M-SQLITE-05, shared performance/consumer harness | Supported-version/mode matrix and Storage comparison with matched guarantees; publish all latency/memory/build tradeoffs. | sol_implementer |
|
||||
|
||||
P4 platforms may use SQLite locally, but Sqlite does not become a consensus/replication
|
||||
engine by sharing a file across hosts. [NetworkedApplications](../platforms/NetworkedApplications.md)
|
||||
selects its SQLite profile explicitly.
|
||||
|
||||
## Verification and migration
|
||||
|
||||
CURRENT TEMPLATE for source-verified test names:
|
||||
`<existing-build>/tests/VoidTests --filter '^(open_in_memory|prepared_bind_and_read|transaction_.*|migrations_apply_in_order_and_are_idempotent|prepare_bad_sql_errors)$'`.
|
||||
See [validation](../VALIDATION.md) for actual baseline commands and failures. PROPOSED after
|
||||
M-SQLITE-01–05: two-connection busy fixtures, faulted COMMIT/destructor rollback, explicit
|
||||
null vs empty text/blob, embedded NUL, int64 bounds, wrong column/index, expired row views,
|
||||
long reader checkpoint pressure, cancellation at lease transfer, disk full and migration
|
||||
checksum drift. Use real supported SQLite libraries in addition to deterministic wrapper
|
||||
ports. Restart tests must use file databases; `:memory:` tests cannot prove durability.
|
||||
|
||||
[Performance](../PERFORMANCE.md) covers prepared/unprepared, batch/individual commits,
|
||||
WAL/rollback, FULL/NORMAL, read pool contention and database-larger-than-cache workloads.
|
||||
Report p50/p95/p99 including busy/admission, throughput, allocations, RSS/CPU and build cost,
|
||||
with common repetitions/confidence intervals and all failed/rejected jobs counted.
|
||||
|
||||
[Migration](../MIGRATION.md): add checked methods first; deprecate chainable unchecked binds
|
||||
and address-dependent transaction lifetimes only with a major-release adapter path. Example:
|
||||
`stmt.bind(1, value); stmt.step();` becomes checked bind followed by checked step. File formats
|
||||
remain SQLite's; wrapper upgrades do not convert them to Storage. Roll back code only when
|
||||
the schema remains backward compatible, otherwise restore a verified backup with explicit
|
||||
reconciliation of subsequent writes. Graph coverage reported no recorded gaps for cited
|
||||
Sqlite files, and source was read directly. No SQL tests or performance measurements ran
|
||||
for this documentation assignment.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Stacktrace — bounded diagnostics with explicit capabilities
|
||||
|
||||
Status: plan; feature tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
Supports R-003/R-006/R-012/R-014 under [C-01–C-05 and C-11](../ARCHITECTURE.md).
|
||||
|
||||
## Existing surface and limits
|
||||
|
||||
[Stacktrace.hpp](../../../include/Void/Stacktrace/Stacktrace.hpp) exposes
|
||||
`Void::Stacktrace::StackFrame`, `capture_stacktrace(skip_frames, max_frames)`,
|
||||
`read_source_snippet`, `format_stacktrace` and `print_stacktrace`. Capture defaults to
|
||||
32 frames; each frame owns function/source/snippet strings. Source reads return Result,
|
||||
whereas capture returns a vector and suppresses exceptions. [Stacktrace.cpp](../../../src/Stacktrace/Stacktrace.cpp)
|
||||
uses Boost.Stacktrace/demangle, resolves source locations and reads snippets during capture,
|
||||
then logs diagnostics. [module.cmake](../../../src/Stacktrace/module.cmake) selects
|
||||
Boost's addr2line backend on the Unix branch and windbg on Windows, depends on Functional
|
||||
and LogState, and applies Unix debug/frame-pointer flags.
|
||||
|
||||
There is no `tests/standalone/Stacktrace` directory in the inspected baseline. Integration
|
||||
through [Testing's signal handler](../../../src/Testing/SignalHandler.cpp) invokes capture
|
||||
and formatting on a fatal signal. Existing allocation, file IO, demangling and logging are
|
||||
not an async-signal-safe crash facility. The plan must not market that path as safe recovery
|
||||
of a corrupted C++ process. [Testing](Testing.md) owns the replacement crash-isolation policy.
|
||||
|
||||
## Selected backend and NEW API
|
||||
|
||||
Retain the existing Boost backend initially behind a Void-owned capability interface;
|
||||
do not add a new unwinding dependency or promise equivalent symbols on every build.
|
||||
Split raw address capture from optional symbol/source enrichment. A standard-library
|
||||
backend is a later M-STACKTRACE-05 gate after toolchain feature probes and conformance,
|
||||
not an assumed C++26 implementation capability. None of this becomes a foundation dependency.
|
||||
|
||||
NEW illustrative surface in the existing namespace:
|
||||
|
||||
```cpp
|
||||
struct CaptureOptions { unsigned skip = 0; unsigned max_frames = 32; };
|
||||
struct ResolveOptions { bool source_snippets = false; std::size_t max_bytes = 64 * 1024; };
|
||||
struct RawTrace; // owning addresses plus module identity snapshot
|
||||
struct ResolvedTrace; // bounded frames, incomplete flag, per-frame status
|
||||
struct Capabilities; // raw capture, symbols, line info; no signal-safety inference
|
||||
Result<RawTrace> capture(CaptureOptions);
|
||||
Result<ResolvedTrace> resolve(const RawTrace&, ResolveOptions);
|
||||
Capabilities capabilities() noexcept;
|
||||
```
|
||||
|
||||
The legacy capture adapter composes capture/resolve using its historical presentation
|
||||
until the major release. NEW capture does not read source or emit through Log; an optional
|
||||
diagnostic hook belongs above the low-level path to avoid recursive logging/stacktrace
|
||||
failures. Unsupported line information is an explicit per-frame result, distinct from
|
||||
an empty stack, permission-denied source read, or a failed unwinder.
|
||||
|
||||
Capture snapshots addresses and module identifiers before a plugin generation can unload.
|
||||
A trace needed for later resolution either retains that generation or owns sufficient
|
||||
module/build-id metadata for an explicitly configured offline symbol resolver. Raw addresses
|
||||
alone are not stable identities across unload, ASLR or process restart. Do not retain a
|
||||
pointer to a transient loader structure. A synchronous embedded resolver is the default;
|
||||
managed deferred symbolization uses caller-supplied execution and bounded admission, not a
|
||||
global worker implicitly started by `capture`.
|
||||
|
||||
## Dataflow, bounds and failures
|
||||
|
||||
1. Validate skip/count and capacity before unwinding; cap NEW calls at 256 frames and
|
||||
return InvalidArgument above that limit. Capture may return a valid truncated trace
|
||||
with an explicit flag when the stack is deeper.
|
||||
2. Copy module identity/address records to owned storage. Resolve symbols outside any
|
||||
application registry or logging lock. Resolve failures preserve raw frames for diagnosis.
|
||||
3. Source snippets are opt-in and constrained to caller-provided allowed roots. Defaults:
|
||||
three context lines, 4 KiB per snippet, 64 KiB total rendered output, 1 MiB source-file
|
||||
scan budget. Enforce overflow-safe line arithmetic, maximum line length and file-read
|
||||
limits; reject unsafe paths and symlink escapes through the configured file-access port.
|
||||
4. A NEW resolver cache holds at most 1,024 entries/4 MiB and keys by module identity and
|
||||
address offset. Invalidated module identities cannot reuse stale symbol entries. Default
|
||||
managed resolution admits 32 jobs/2 MiB total pending trace input with one worker.
|
||||
5. Cancellation/deadline is checked between frames/source reads. The terminal result owns
|
||||
completed frames and indicates Partial/Cancelled; it never frees buffers still used by
|
||||
a backend. Blocking symbol-tool calls require a bounded child-process boundary if that
|
||||
backend cannot otherwise be interrupted.
|
||||
|
||||
Source paths, snippets and module names may reveal private build information. Default
|
||||
rendering removes configured source-root prefixes and omits snippets. Explicit diagnostic
|
||||
configuration enables them; telemetry must not attach arbitrary source text automatically.
|
||||
No debug source file is opened merely because untrusted input names it.
|
||||
|
||||
The initial crash path is subprocess test isolation: the parent records exit/signal and
|
||||
optional externally captured diagnostics. A NEW minimal fatal-signal marker may write a
|
||||
fixed-size record to a preopened descriptor using a reviewed platform-safe implementation,
|
||||
but it does not call the rich Stacktrace API or resume the failed process. A fully signal-safe
|
||||
unwinder is outside this phase and requires a separate safety/capability gate.
|
||||
|
||||
## Ordered backlog
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-STACKTRACE-01 | P0; existing source and Testing contract | Add direct tests for empty formatting, source failures, frame caps and optional symbols; fixture assertions tolerate stripped builds without hiding failed capture. | sol_implementer |
|
||||
| M-STACKTRACE-02 | P1; M-STACKTRACE-01, Functional errors | Separate capture/resolve, capability report, remove logging recursion from NEW path; source access is absent by default. | astra_implementer |
|
||||
| M-STACKTRACE-03 | P2; M-STACKTRACE-02, IO safe file access | Bounded source resolver/cache, redaction, backend timeouts; hostile path/line/size inputs remain within limits. | sol_implementer |
|
||||
| M-STACKTRACE-04 | P2; M-STACKTRACE-02, Testing subprocess isolation, Plugin generation ownership | Crash integration and deferred lifetime tests; fatal child does not corrupt the test runner and resolution cannot use unloaded code. | astra_implementer |
|
||||
| M-STACKTRACE-05 | P3; M-STACKTRACE-03/04, supported-toolchain probes | Evaluate standard backend and platform parity using identical tests/profiles; retain Boost unless evidence supports replacement. | astra_implementer |
|
||||
|
||||
P4 users consume the same diagnostics through [Observability](../subsystems/Observability.md),
|
||||
without transmitting full stacks by default. No independent distributed stacktrace service
|
||||
is required.
|
||||
|
||||
## Verification and migration
|
||||
|
||||
CURRENT: baseline build and aggregate CTest commands are in [validation](../VALIDATION.md).
|
||||
There is no current Stacktrace-specific suite to invoke. PROPOSED after M-STACKTRACE-01:
|
||||
`<configured-build>/tests/VoidTests --filter '^stacktrace_'`; prerequisites include the
|
||||
new tests, selected Boost backend and a build with known debug information. Test both
|
||||
stripped and debug fixtures, shared-library unload, invalid UTF/path text, missing source,
|
||||
huge line number, cancellation and a nonresponsive symbol helper. Never use the current
|
||||
rich handler itself as proof of signal safety.
|
||||
|
||||
[Performance](../PERFORMANCE.md) separates raw capture, symbol resolution, cold/warm cache,
|
||||
source IO and formatting; report p50/p95/p99, allocations, RSS/CPU and build/debug-symbol
|
||||
size using the common repetition and regression rules. Measure disabled hooks separately.
|
||||
|
||||
[Migration](../MIGRATION.md) retains current names through adapters and documents the new
|
||||
default of no source reads. Consumer examples transition from `capture_stacktrace()` to
|
||||
checked `capture()` and optional `resolve()`. Rollback restores the legacy normal-context
|
||||
presentation adapter, never the unsafe promise of surviving fatal signals. Package tests
|
||||
in [build/distribution](../BUILD-AND-DISTRIBUTION.md) verify optional backend linkage and
|
||||
minimal consumers. Cited files have checked graph coverage and direct source verification;
|
||||
no Stacktrace test or performance result was executed for this plan.
|
||||
@@ -0,0 +1,168 @@
|
||||
# System facilities and process lifecycle plan
|
||||
|
||||
Status: PLANNED feature work; no system implementation changes. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
Requirements R-003, R-006, R-009 and R-014 apply. Follow
|
||||
[architecture](../ARCHITECTURE.md) C-02–C-06 and C-13.
|
||||
|
||||
## Existing source baseline
|
||||
|
||||
[Process.hpp](../../../include/Void/System/Process.hpp) exposes `Void::Process::run`,
|
||||
`run_streaming`, `shell`, `reexec`, `Output`, and line callbacks. Nonzero child exits
|
||||
are successful Results with an exit code. [Process.cpp](../../../src/System/Process.cpp)
|
||||
uses POSIX pipes/fork/execvp, writes stdin before draining outputs, polls stdout/stderr,
|
||||
sends SIGTERM on timeout, and then waits synchronously. The source derives a 30-second
|
||||
poll deadline when the supplied timeout is zero, despite the header's no-limit wording.
|
||||
It does not establish a bounded termination guarantee for a child ignoring SIGTERM.
|
||||
These are characterization and correction targets, not intentional NEW semantics.
|
||||
|
||||
[FileWatcher.hpp](../../../include/Void/System/FileWatcher.hpp) and
|
||||
[FileWatcher.cpp](../../../src/System/FileWatcher.cpp) provide
|
||||
`Void::FileSystem::FileWatcher`, a polling worker with default 500 ms polls and two
|
||||
stable polls before notification. It compares existence/mtime/size, and invokes copied
|
||||
callbacks outside the watch map lock. Stability of metadata is not proof of complete
|
||||
content or authenticity. Unwatch cannot revoke a copied callback already admitted.
|
||||
|
||||
[SignalWatcher.hpp](../../../include/Void/System/SignalWatcher.hpp) documents
|
||||
`Void::Process::SignalWatcher::create`, blocked signal-mask inheritance before worker
|
||||
startup, synchronous wait/poll, and destruction on its creating thread.
|
||||
[SignalWatcher.cpp](../../../src/System/SignalWatcher.cpp) is the platform implementation.
|
||||
[Path.hpp](../../../include/Void/System/Path.hpp),
|
||||
[Query.hpp](../../../include/Void/System/Query.hpp),
|
||||
[TempFile.hpp](../../../include/Void/System/TempFile.hpp), and
|
||||
[TempDir.hpp](../../../include/Void/System/TempDir.hpp) supply filesystem helpers and
|
||||
RAII temporary resources. `atomic_write` stages to a fixed sibling `.tmp` then renames;
|
||||
it does not fsync and must not be used as a durable-commit primitive based on its name.
|
||||
[Metrics.hpp](../../../include/Void/System/Metrics.hpp) supplies `Void::SystemInfo`
|
||||
Linux memory/process CPU samples, with unavailable/zero fallback on other platforms.
|
||||
[module.cmake](../../../src/System/module.cmake) declares Functional, LogState and Threads.
|
||||
|
||||
Existing fixtures cover [processes](../../../tests/standalone/System/Process.cpp),
|
||||
[streaming](../../../tests/standalone/System/ProcessStream.cpp),
|
||||
[watching](../../../tests/standalone/System/FileWatcher.cpp),
|
||||
[signals](../../../tests/standalone/System/SignalWatcher.cpp), and
|
||||
[paths](../../../tests/standalone/System/Path.cpp). Graph checks covered these source
|
||||
paths; partial Process/SignalWatcher/FileWatcher declarations were directly read.
|
||||
|
||||
## NEW process and filesystem contracts
|
||||
|
||||
Design sketch; Result follows Functional and OperationOptions belongs to Async:
|
||||
|
||||
```cpp
|
||||
namespace Void::Process { // NEW additions
|
||||
struct SpawnOptions {
|
||||
std::filesystem::path executable;
|
||||
std::vector<std::string> arguments;
|
||||
std::filesystem::path working_directory;
|
||||
EnvironmentPolicy environment; // explicit inherit or allowlist
|
||||
CaptureLimits capture; // bytes, line bytes, overflow policy
|
||||
};
|
||||
Result<Child> spawn(SpawnOptions);
|
||||
Coro::Task<Result<ExitStatus>> wait(Child&, Async::OperationOptions);
|
||||
Coro::Task<Result<Output>> communicate(Child&, InputSource&, Async::OperationOptions);
|
||||
}
|
||||
namespace Void::FileSystem { // NEW additions
|
||||
Result<void> replace_file(path, bytes, ReplaceOptions); // atomic visibility vs durable
|
||||
// watch registration -> owning WatchSubscription with close_and_join(options).
|
||||
}
|
||||
```
|
||||
|
||||
Child owns PID/process identity, descriptors and reaping responsibility. Move transfers
|
||||
all ownership. `communicate` concurrently writes stdin and reads both outputs through
|
||||
IO; EOF closes each direction independently, preventing pipe-buffer deadlock. Output
|
||||
retention and line streaming are separate policies: streaming need not retain all bytes.
|
||||
Default cap is 1 MiB each for stdout/stderr, 64 KiB per line, 4 MiB buffered input;
|
||||
overflow terminates the child and reports `output_limit` with truncated diagnostics.
|
||||
An explicit discard-after-limit mode continues draining and marks truncation.
|
||||
|
||||
Default active children per manager: 64; pending spawn requests: 128; admission rejects
|
||||
on overload. Argument/environment input totals are capped at 256 KiB and checked again
|
||||
against platform limits. Use argv execution by default. Shell interpretation is an
|
||||
explicit adapter; never concatenate untrusted arguments. Exec failures use an error
|
||||
pipe and retain errno, distinct from a program intentionally exiting 127. Environment
|
||||
snapshots are immutable per spawn and diagnostics redact marked secrets.
|
||||
|
||||
Timeout/stop first closes admission/input, requests SIGTERM for the owned process group,
|
||||
waits a configurable 2-second grace, then sends SIGKILL and reaps. Report cancelled or
|
||||
timed_out plus exit evidence; termination cannot undo external effects. Platform/kernel
|
||||
stalls can prevent prompt reaping, so a timeout does not release Child ownership. A
|
||||
manager retains outstanding reapers through shutdown. Descendants outside the process
|
||||
group are outside this guarantee; report that boundary. `reexec` remains an explicit
|
||||
application lifecycle action with open-descriptor policy and an error on exec failure.
|
||||
|
||||
System's synchronous primitives remain independently usable. NEW async process/watch
|
||||
adapters depend on [Async](Async.md) and [IO](../subsystems/IO.md) in an optional adapter
|
||||
target; the base System package does not depend on managed Runtime or force Async into
|
||||
small filesystem consumers. Final adapter target names are packaging work under
|
||||
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
|
||||
|
||||
## Watching, persistence and capability behavior
|
||||
|
||||
Retain polling as the portable initial backend. NEW injected scheduling uses Time's
|
||||
clock and one shared watcher service instead of a thread per file. Default 1,024 paths,
|
||||
256 queued notifications, one coalesced pending notification per path. Overflow emits a
|
||||
rescan-required marker; consumers reread/validate rather than infer a missing history.
|
||||
Path disappearance, atomic rename, symlink change and permission denial are distinct
|
||||
events. Default follows the configured path with no recursive traversal; symlink and
|
||||
directory-root restrictions are explicit options. Later Linux inotify is a capability
|
||||
adapter with the same rescan/overflow contract, gated after polling conformance.
|
||||
|
||||
Subscription state owns copied callback captures until close-and-join completes. User
|
||||
callbacks run outside locks and on the configured executor. Callback exceptions reach
|
||||
an error sink; they do not kill the watcher thread. Self-close requests stop but self-join
|
||||
is rejected. A callback never performs configuration publication itself; it submits a
|
||||
candidate to [Configuration](Configuration.md).
|
||||
|
||||
`replace_file` uses an exclusively created unpredictable sibling temporary file,
|
||||
bounded write loops, checked close/errors and rename on the same filesystem. Atomic
|
||||
visibility is distinct from durable replacement; durable mode syncs staged content,
|
||||
renames, then syncs the containing directory before acknowledgement. Failure after
|
||||
rename can mean visible-but-durability-unknown; return a phase-aware error and do not
|
||||
blindly overwrite on retry. Storage and Update retain their own commit protocols.
|
||||
Directory listing/read helpers gain explicit entry/byte limits and cancellation in
|
||||
the optional adapter. RAII temp factories enforce restrictive permissions and never
|
||||
recursively remove a directory they did not create and retain ownership of.
|
||||
|
||||
Capability queries return supported/unsupported/unavailable with diagnostic context.
|
||||
Metrics distinguish a real zero from unavailable sampling in NEW APIs. Native POSIX
|
||||
and standard filesystem facilities are initial choices; no external process or watcher
|
||||
library is required. Cross-platform backends are separate later conformance work.
|
||||
|
||||
## Ordered implementation backlog
|
||||
|
||||
All feature rows are PLANNED.
|
||||
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-SYSTEM-01 | P0 / current source | Characterize zero timeout, SIGTERM resistance, full-duplex pipe and rename/fsync behavior; portable child fixtures | Existing semantics recorded; tests use built fixture paths rather than `/bin` assumptions / sol_implementer |
|
||||
| M-SYSTEM-02 | P1 / M-SYSTEM-01; Functional errors | Owned descriptors/Child, explicit spawn options, error pipe, bounded capture | Exec failure distinct from exit 127; all early failures close/reap; caps enforced / astra_implementer |
|
||||
| M-SYSTEM-03 | P2 / M-SYSTEM-02; Async and IO foundation gates | Full-duplex async communicate, stop escalation, joined process manager | Multi-pipe pressure completes; timeout/child-exit race delivers once and reaps / astra_implementer |
|
||||
| M-SYSTEM-04 | P2 / M-SYSTEM-01; Async/Time injection gates | Shared polling watcher, owned subscriptions, coalescing/rescan and callback errors | Unwatch+join drains callbacks; replacement/deletion/overflow deterministic / sol_implementer |
|
||||
| M-SYSTEM-05 | P2 / M-SYSTEM-02 | Explicit atomic/durable file replacement, safe temp factories, query bounds | Fault-injected write/sync/rename errors report the actual phase and clean only owned temporaries / astra_implementer |
|
||||
| M-SYSTEM-06 | P3 / M-SYSTEM-03, M-SYSTEM-04, M-SYSTEM-05 | Capability matrix, optional inotify, metrics validity, installed adapter checks | Polling/backend conformance identical; unsupported platforms fail explicitly / sol_implementer |
|
||||
|
||||
## Validation, performance and migration
|
||||
|
||||
CURRENT aggregate command is
|
||||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||||
not rerun here. The inherited two failures depend on absent `/bin/echo` and `/bin/cat`,
|
||||
not evidence that the proposed process contract passes. PROPOSED fixture executables
|
||||
must exercise ignored SIGTERM, delayed stdin consumption, simultaneous stdout/stderr,
|
||||
huge unbroken lines, inherited descriptors, child exit during stop and callback throw.
|
||||
Signal tests run in isolated processes to protect the test runner's mask. File tests
|
||||
inject short writes, failed fsync, rename collision, symlink replacement and full queues.
|
||||
|
||||
Measure spawn/wait p50/p95/p99, watcher detection latency versus polling interval,
|
||||
throughput, allocations, descriptor/thread counts, peak RSS/CPU and build cost under
|
||||
[PERFORMANCE](../PERFORMANCE.md). A large output producer must keep retained bytes
|
||||
within its cap; an idle watcher must not busy-spin. No benchmarks ran for this plan.
|
||||
|
||||
Keep current namespaces (`Void::Process`, `Void::FileSystem`, `Void::SystemInfo`).
|
||||
Legacy `run`/`run_streaming` adapt into a managed Child only after their timeout/output
|
||||
changes are versioned; no silently reclassified child exits. Replace misleading durable
|
||||
claims on `atomic_write` through documentation/deprecation and a major-release policy,
|
||||
with new explicit visibility/durability choices. Preserve polling as a rollback backend
|
||||
selected before watching starts. Rollback of an effective file replacement requires
|
||||
application version recovery, not repeating a failed syscall. See
|
||||
[MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md) and [DELIVERY](../DELIVERY.md).
|
||||
@@ -0,0 +1,170 @@
|
||||
# Testing — trustworthy framework and deterministic verification
|
||||
|
||||
Status: plan; all feature tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
R-002/R-003/R-012/R-016 and [C-01–C-05](../ARCHITECTURE.md) apply. Testing owns reusable
|
||||
harness primitives; each feature owns its behavioral oracle and fixtures.
|
||||
|
||||
## Existing framework and evidence
|
||||
|
||||
The namespace is `Void::Testing`. [Config.hpp](../../../include/Void/Testing/Config.hpp)
|
||||
defines test/assertion results, skip/crash states, filters, reporters, shuffle/seed/repeat
|
||||
and parallel options. [Runner](../../../src/Testing/Runner.cpp) implements regex filters,
|
||||
exact suite/tag filters, sequential and optional Async-thread-pool execution, console/JUnit
|
||||
output and exit handling. [Suite.hpp](../../../include/Void/Testing/Suite.hpp) registers
|
||||
annotated methods using reflection where supported. [tests/CMakeLists.txt](../../../tests/CMakeLists.txt)
|
||||
collects generated standalone shims into `VoidTests`. [module.cmake](../../../src/Testing/module.cmake)
|
||||
declares LogState and optional diagnostics/execution/configuration/text integrations.
|
||||
|
||||
[Math.cpp](../../../tests/standalone/Testing/Math.cpp) intentionally includes DisabledTest
|
||||
examples named `broken_feature` and `unquoted_skip`; these exercise skip behavior and are
|
||||
not missing product implementations. [ContainerFixture](../../../tests/standalone/Testing/ContainerFixture.cpp)
|
||||
and [StructRepr](../../../tests/standalone/Testing/StructRepr.cpp) provide further framework
|
||||
examples. The baseline result is 1,245 passed, two environmental process-fixture failures
|
||||
and three skips out of 1,250; see [validation](../VALIDATION.md). This task ran no tests.
|
||||
|
||||
Source-backed improvement targets: malformed regex currently yields an empty selection;
|
||||
JUnit reporter creation holds a static output stream; sequential signal handling invokes
|
||||
rich diagnostics and jumps out of a signal handler; parallel execution omits that crash
|
||||
recovery. [SignalHandler.cpp](../../../src/Testing/SignalHandler.cpp) has process-global
|
||||
callback/jump state. These are reasons to specify framework regression tests and process
|
||||
isolation, not to infer reliable crash containment from ordinary unit-test passes.
|
||||
|
||||
## Native harness design and NEW API
|
||||
|
||||
Keep the existing native framework and C++26 reflection/scanner paths. No wholesale
|
||||
replacement by a third-party testing framework. Optional compiler fuzz/sanitizer adapters
|
||||
are development tooling, absent from consumer dependencies. Runtime is never required
|
||||
merely to register or execute a synchronous test. [Time](Time.md) owns fake-clock semantics
|
||||
and [Async](Async.md) owns executor semantics; Testing supplies controlled adapters and
|
||||
schedule exploration around those contracts, not competing production types.
|
||||
|
||||
NEW illustrative shapes in `Void::Testing`:
|
||||
|
||||
```cpp
|
||||
struct ReplayToken { std::uint64_t seed; std::uint32_t generator_version; };
|
||||
struct PropertyOptions {
|
||||
unsigned cases = 256;
|
||||
unsigned max_size = 64;
|
||||
unsigned max_shrinks = 1000;
|
||||
};
|
||||
template<class Generator, class Predicate>
|
||||
PropertyResult check_property(Generator, Predicate, PropertyOptions, ReplayToken);
|
||||
class DeterministicRun; // ready-queue control, injected clock, event trace
|
||||
class FailureCapture; // bounded child assertion sink, explicit result inspection
|
||||
struct ProcessTestOptions; // timeout/output/resource budget, expected exit policy
|
||||
```
|
||||
|
||||
These types and `PropertyResult` are NEW. Failures retain the original case, minimized
|
||||
case, seed, generator/codec version, shrink path and schedule decisions. Select
|
||||
`std::mt19937_64` with a recorded 64-bit seed and case ordinal. M-TESTING-03 freezes
|
||||
bounded-uniform rejection mapping over its integer outputs, with cross-toolchain golden
|
||||
sequences; standard distribution implementation details must not silently change replay.
|
||||
User-supplied generators own their values and deterministic
|
||||
shrinkers produce a strictly decreasing complexity measure or exhaust the shrink budget.
|
||||
Example workflow: generate a vector, apply a container operation, compare to a simple
|
||||
reference, then replay the stored minimal case in a normal regression test.
|
||||
|
||||
The deterministic executor runs one ready action at a time in recorded admission order,
|
||||
advances the injected clock only under test control, and records alternative runnable
|
||||
choices. A bounded exploration mode enumerates selected interleavings. It must not claim
|
||||
to simulate OS threads, cache coherence, or arbitrary data races. Dedicated stress/TSan
|
||||
work remains necessary. Stop/completion races are assertions on exactly one terminal
|
||||
result and released ownership, not on wall-clock sleep timing.
|
||||
|
||||
## Framework correctness and failure handling
|
||||
|
||||
Registration becomes a frozen catalog before running tests. Duplicate stable test IDs,
|
||||
invalid regex/options, missing requested suites and unreadable report paths are explicit
|
||||
configuration failures. A NEW default fails an explicitly requested empty selection;
|
||||
`--allow-empty` is an explicit override. Listing is side-effect-free with respect to test
|
||||
bodies. Shuffle/repeat reports seed and iteration; discovery order is stable by test ID.
|
||||
|
||||
Every run owns its reporter streams and context. An assertion emitted outside an active
|
||||
test is a framework error, not silently assigned to the next test. Async test adapters
|
||||
retain a context handle until their task scope joins; thread-local convenience access does
|
||||
not permit borrowed `TestResult*` pointers to escape. Freeze a result only after callbacks
|
||||
and mock verifiers finish. Reporter callbacks see immutable result snapshots outside registry
|
||||
locks; reporter failure makes the overall run fail and preserves an emergency summary.
|
||||
|
||||
One fixture lifecycle controller handles construction, setup, body, teardown and destruction.
|
||||
After setup is entered, teardown is attempted exactly once even if setup/body fails; destroy
|
||||
always runs for a constructed fixture. Report primary and cleanup errors separately. A
|
||||
require/fatal assertion aborts only that test's controlled scope, while ordinary expect
|
||||
records and continues. Intentional skip reasons survive console and JUnit output.
|
||||
|
||||
Crash/timeout tests run in fresh child processes through [System](System.md), with one
|
||||
selected test ID and a bounded result channel. Parent waits/reaps and distinguishes ordinary
|
||||
failure, signal, timeout, infrastructure failure and missing result. It can terminate the
|
||||
child after its deadline; it cannot safely kill an in-process C++ test thread and continue
|
||||
using its corrupted objects. Remove promises of rich signal-handler recovery in coordination
|
||||
with [Stacktrace](Stacktrace.md). Ordinary exception tests remain in-process.
|
||||
|
||||
## Resource policies and fuzz/property capabilities
|
||||
|
||||
NEW defaults: sequential execution; explicit parallel mode caps workers at four unless
|
||||
configured otherwise; 100,000 registered tests; 1,000 retained assertions/1 MiB diagnostics
|
||||
per test; 64 MiB aggregate report buffer. Above the assertion cap, retain first failures
|
||||
and counters, mark truncation, and continue or abort according to test policy without
|
||||
unbounded growth. Reporters stream results to avoid retaining all output text.
|
||||
|
||||
Property defaults above additionally cap generated input at 1 MiB, corpus at 64 MiB and
|
||||
one property at five seconds/10,000 scheduled steps. Time checks occur between generator,
|
||||
case and shrink calls; uncooperative custom callbacks require subprocess isolation for a
|
||||
hard timeout. A budget exhaustion is Inconclusive,
|
||||
not Pass. Rejection sampling is limited to ten times the requested successful case count;
|
||||
an impossible precondition is reported. Shrinking preserves the original failure category
|
||||
and never consumes production network/filesystem state. Use generated fixtures, not private data.
|
||||
|
||||
Process-test defaults: 60-second timeout, 1 MiB captured output per stream, four concurrent
|
||||
children, 256 pending jobs. Optional Linux resource limits are capability-reported rather
|
||||
than assumed portable. Output overage truncates with counts; it cannot deadlock a full pipe.
|
||||
Stop requests close admission, terminate opted-in child jobs, drain pipes, reap children
|
||||
and join owned harness work. Embedded in-process deadlines remain cooperative.
|
||||
|
||||
Fuzz entry points accept byte spans and use feature-owned parsers/models. NEW compiler
|
||||
adapters expose those same functions to supported fuzz engines; a deterministic corpus
|
||||
replay runner works without them. Corpus metadata records format, fixture license/source,
|
||||
seed and maximum memory/time. Minimized failures become normal regression fixtures.
|
||||
Mutation/crash-injection campaigns verify the oracle: intentionally broken length checks,
|
||||
lost writes or duplicate completions must be detected by the harness.
|
||||
|
||||
## Ordered tasks
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-TESTING-01 | P0; existing runner/registration | Framework self-tests for filter/seed/skip/fixture/reporter/exit behavior, with subprocess expected-failure fixtures; skip demonstrations remain intentional. | astra_implementer |
|
||||
| M-TESTING-02 | P1; M-TESTING-01, Async context ownership, System child process | Per-run contexts/reporters and crash isolation; cleanup runs once, child crash is contained, invalid selection cannot produce false success. | astra_implementer |
|
||||
| M-TESTING-03 | P1; M-TESTING-02, Time fake clock, Async test executor | Deterministic schedule driver, versioned generator/shrinker and replay token; cross-build seed replay and schedule minimization are reproducible. | astra_implementer |
|
||||
| M-TESTING-04 | P2; M-TESTING-03, Binary/Data bounded fixtures | Property combinators, model traces and failure capture; known faulty algorithms are caught and shrink to replayable cases. | sol_implementer |
|
||||
| M-TESTING-05 | P2; M-TESTING-02/04, supported compiler probes | Corpus runner, optional fuzz adapters, subprocess resource controls and sanitizer matrix; unsupported tooling is reported and corpus replay still works. | sol_implementer |
|
||||
| M-TESTING-06 | P3; M-TESTING-03/05, shared validation/performance schemas | Fault-file/transport ports and benchmark evidence adapters used by Storage/IO/Net; injected faults occur at named boundaries and totals reconcile. | astra_implementer |
|
||||
| M-TESTING-07 | P4; M-TESTING-06, Coordination/Replication models | Distributed schedule/history harness; partition/restart/duplicate scenarios reproduce and reject deliberately invalid histories. | astra_implementer |
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT test-runner syntax is source-verified. TEMPLATE:
|
||||
`<existing-build>/tests/VoidTests --filter '^(addition|db_query|broken_feature|unquoted_skip)$'`.
|
||||
`--filter` matches test names and suite-qualified names using regex search. No run is claimed
|
||||
here. PROPOSED after M-TESTING-01: a separate framework-verification child fixture set with
|
||||
known exit codes, exact counts and parsed JUnit output, driven by a parent checker independent
|
||||
of the framework assertions being checked. A green self-hosted suite alone is insufficient.
|
||||
|
||||
Required regressions include malformed regex, empty explicit selection, report-open failure,
|
||||
two runs to different output files, duplicate registration, require during setup/teardown,
|
||||
late async assertion, deterministic repeat/shuffle, intentional skips, signal/timeout,
|
||||
pipe saturation and a deliberately failing property. Verify expected failures without
|
||||
editing a live result to Passed. Run isolated module consumers and supported reflection
|
||||
configurations under [build/distribution](../BUILD-AND-DISTRIBUTION.md).
|
||||
|
||||
Apply [performance](../PERFORMANCE.md) to assertion overhead, reflection/registration build
|
||||
cost, worker scheduling and bounded report memory; preserve p50/p95/p99, throughput,
|
||||
allocations and RSS/CPU evidence without turning benchmark variance into test failure.
|
||||
[Validation](../VALIDATION.md) owns sanitizer/toolchain gates and baseline failure reporting.
|
||||
|
||||
[Migration](../MIGRATION.md) keeps Test/Suite/expect/require adapters while introducing
|
||||
explicit contexts, replay and isolation. NEW strict option validation is a documented
|
||||
major behavior change. Rollback may keep old output formats via adapters, but must not
|
||||
restore silent passing of invalid selections. [TestingMock](TestingMock.md) integrates
|
||||
through FailureCapture and joined contexts, with no reverse dependency from Testing to mocks.
|
||||
Graph coverage was checked for all cited source; partial Registrar syntax was read directly.
|
||||
No new framework, fuzz, crash or benchmark checks ran during documentation authoring.
|
||||
@@ -0,0 +1,149 @@
|
||||
# TestingMock — deterministic expectations and owned actions
|
||||
|
||||
Status: plan; implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
R-002/R-014/R-016 and [C-02–C-05](../ARCHITECTURE.md) govern future work.
|
||||
|
||||
## Existing capabilities and concrete gaps
|
||||
|
||||
`Void::TestingMock` provides [MockFunction](../../../include/Void/TestingMock/MockFunction.hpp),
|
||||
[Expectation](../../../include/Void/TestingMock/Expectation.hpp),
|
||||
[matchers](../../../include/Void/TestingMock/Matcher.hpp), and
|
||||
[Mock/MockBase](../../../include/Void/TestingMock/Mock.hpp). Expectations match arguments,
|
||||
record calls and run actions; `times`, `once`, `returns` and `invokes` are existing names.
|
||||
Actions use `std::move_only_function`; the [move-only action test](../../../tests/standalone/TestingMock/MoveOnlyAction.cpp)
|
||||
specifically demonstrates a unique_ptr-capturing lambda, not arbitrary move-only arguments
|
||||
or move-only returned values. Matching/execution currently passes arguments through several
|
||||
by-value layers, and `returns` returns its stored value as an lvalue.
|
||||
|
||||
`MockFunction::operator()` holds its mutex while matching and executing user actions.
|
||||
Expectation registration and verify/clear do not use that same synchronization. MockBase
|
||||
stores non-owning function pointers; registration has no lifetime token. `verify()` clears
|
||||
expectations, while destructors call it automatically. Preserve existing convenient usage
|
||||
but do not infer concurrent reconfiguration or reentrant action safety from the mutex.
|
||||
|
||||
[Reflect.hpp](../../../include/Void/TestingMock/Reflect.hpp) lists virtual methods and checks
|
||||
handwritten mocks; its source explicitly distinguishes introspection from unsupported
|
||||
override-code injection. Reflection availability is toolchain-probed, not a promise that
|
||||
complete automatic mock generation already exists. [module.cmake](../../../src/TestingMock/module.cmake)
|
||||
depends on Testing and Functional. Evidence includes
|
||||
[VerifyAll](../../../tests/standalone/TestingMock/VerifyAll.cpp),
|
||||
[FailureMessages](../../../tests/standalone/TestingMock/FailureMessages.cpp), and
|
||||
[Reflect tests](../../../tests/standalone/TestingMock/Reflect.cpp).
|
||||
|
||||
## Selected native design and NEW contract
|
||||
|
||||
Retain a native header-oriented mock library integrated with [Testing](Testing.md); no new
|
||||
external mocking engine. Separate configuration from invocation. A NEW session freezes
|
||||
expectations before concurrent calls, retains action/registration state, and closes after
|
||||
the test's task scope has joined. Existing `expect(...).invokes(...).times(...)` remains a
|
||||
builder adapter. Mutating a frozen session returns InvalidState rather than racing.
|
||||
|
||||
Illustrative NEW shapes in the existing namespace:
|
||||
|
||||
```cpp
|
||||
enum class Concurrency { SingleThread, ConcurrentActions };
|
||||
struct MockLimits { std::size_t expectations = 1024; std::size_t events = 4096; };
|
||||
class MockSession; // owns registrations, diagnostics and verification state
|
||||
class Sequence; // explicit order group, never global registration order
|
||||
struct Verification; // structured missing/excess/unmatched/action failures
|
||||
Result<void> freeze(MockSession&, Concurrency);
|
||||
Verification verify_and_close(MockSession&);
|
||||
// NEW builder operations: at_least(n), at_most(n), in_sequence(seq),
|
||||
// returns_once(move_only_value), invokes_once(move_only_action).
|
||||
```
|
||||
|
||||
`SingleThread` is the NEW default and permits same-thread reentrant calls after releasing
|
||||
internal locks; concurrent entry from another thread returns a deterministic framework
|
||||
failure. `ConcurrentActions` explicitly requires custom matchers/actions to support concurrent
|
||||
invocation. The library does not secretly serialize arbitrary user code under a mutex and
|
||||
cannot make a captured mutable object thread-safe by retaining it.
|
||||
|
||||
Invocation dataflow: snapshot immutable candidate matchers under a short session lock,
|
||||
evaluate pure matchers outside it, then reacquire to reserve a matching unsaturated
|
||||
expectation and sequence position. If another call consumed it, retry the remaining immutable
|
||||
candidates against the same borrowed arguments. Reservation is the call's linearization
|
||||
point. Release the lock, run the reserved action, then record terminal outcome. Keep the
|
||||
expectation/action storage alive through that outcome; verification waits for owned calls.
|
||||
Registration order breaks ties among otherwise eligible expectations. A custom matcher
|
||||
must be side-effect-free because it may be reevaluated; exceptions become MatcherFailure.
|
||||
|
||||
Once-actions transfer their move-only callable/value to the reserved invocation. Repeated
|
||||
actions stay in a retained immutable registration holder and use the explicitly selected
|
||||
concurrency policy; do not copy a move-only callable. Matchers inspect arguments through
|
||||
const references; forward each argument to the action exactly once after selection. Provide
|
||||
compile-time diagnostics for impossible reference lifetimes and missing return actions.
|
||||
For reference-return mocks the user must supply a lifetime-safe referent. A mismatched
|
||||
non-default-constructible return cannot fall back to `R{}`: record failure then throw a
|
||||
Testing-owned invocation-abort exception, caught at the test boundary. No exception crosses
|
||||
a plugin C boundary; C-facing mocks use status/result actions.
|
||||
|
||||
Explicit order groups model call dependencies. `never()` is an explicit prohibition checked
|
||||
before ordinary candidate selection; it is not a saturated zero-count expectation silently
|
||||
skipped by the matcher loop. Negative counts are invalid; min≤max is checked at freeze.
|
||||
Verification is idempotent and reports each unmet condition once, retaining a bounded
|
||||
summary for subsequent calls rather than destroying evidence prematurely.
|
||||
|
||||
## Ownership, diagnostics and resource limits
|
||||
|
||||
A registration token replaces MockBase's untracked raw-pointer lifetime for dynamic mocks.
|
||||
Removing a registration stops admission and joins its admitted calls before releasing action
|
||||
state. Destructors never throw; they perform best-effort verification through a retained
|
||||
Testing context. Explicit `verify_and_close` is preferred so failures cannot arrive after
|
||||
the result has frozen. Closing from inside an action returns WouldDeadlock or schedules
|
||||
deferred close; it cannot synchronously wait for itself.
|
||||
|
||||
NEW defaults: 1,024 expectations per session, 64 matchers per expectation, 4,096 retained
|
||||
invocation events, 4 MiB diagnostic memory and 4 KiB rendering per argument. Event overflow
|
||||
keeps total counters and first/last bounded samples, marks truncation, and does not drop
|
||||
the fact that an unexpected call happened. Bound matcher-description depth at 32. Test
|
||||
configuration may lower these; zero means zero capacity, never unlimited. User action
|
||||
allocations remain outside the framework's memory bound and are subject to process-test
|
||||
limits. Use Time's injected clock for timestamps and Testing's event sequence for ordering.
|
||||
|
||||
FailureCapture from Testing records expected mock failures in an isolated child assertion
|
||||
sink. Replace framework tests that temporarily alter the live test result with this API.
|
||||
Diagnostics report actual arguments, candidate matcher descriptions, declaration location,
|
||||
reserved call index and order-group position. Redaction is available for fixtures containing
|
||||
sensitive-looking fields; captured arbitrary object bytes are never a default diagnostic.
|
||||
|
||||
Async actions compose with Async tasks owned by the test scope. A NEW scripted action can
|
||||
yield a response, error, partial transfer, cancellation or delayed completion through the
|
||||
deterministic executor. It cannot retain borrowed arguments after return unless it copies
|
||||
them into an admitted owned buffer. The mock does not invent a second scheduler or wall-clock
|
||||
sleep mechanism. Scripted transport/file mocks are reusable test ports, not production APIs.
|
||||
|
||||
## Ordered backlog
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-TESTINGMOCK-01 | P0; current tests, Testing failure capture | Characterize once/count/unmatched/destructor semantics with isolated expected failures and compile fixtures; preserve current examples. | sol_implementer |
|
||||
| M-TESTINGMOCK-02 | P1; M-TESTINGMOCK-01, Testing context ownership | Session freeze/close, registration tokens and action-outside-lock reservation; reentrant actions complete, destroyed dynamic registrations cannot dangle. | astra_implementer |
|
||||
| M-TESTINGMOCK-03 | P2; M-TESTINGMOCK-02 | Perfect forwarding, once/repeated actions, explicit prohibition/ranges/sequence groups; move-only args/returns and count races have defined results. | astra_implementer |
|
||||
| M-TESTINGMOCK-04 | P2; M-TESTINGMOCK-03 | Bounded structured diagnostics, matcher combinators, property models and regression tests of the mock framework itself; injected wrong behavior is detected. | sol_implementer |
|
||||
| M-TESTINGMOCK-05 | P3; M-TESTINGMOCK-04, Testing deterministic run, Async/Time contracts | Scripted async/file/transport faults and cancellation; no post-close callback and every script is replayable by seed. | astra_implementer |
|
||||
| M-TESTINGMOCK-06 | P3; M-TESTINGMOCK-03, compiler probes | Reflection signature checks for overload/cv/ref/noexcept/inheritance cases; unsupported code generation remains explicitly unavailable. | sol_implementer |
|
||||
|
||||
P4 distributed tests reuse scripted ports; consensus assertions stay with Coordination and
|
||||
Replication. Cross-module ownership is tracked in [dependencies](../DEPENDENCIES.md).
|
||||
|
||||
## Acceptance and migration
|
||||
|
||||
CURRENT TEMPLATE for verified names:
|
||||
`<existing-build>/tests/VoidTests --filter '^(invokes_accepts_unique_ptr_capturing_lambda|verify_all_.*|failure_message_.*)$'`.
|
||||
See [validation](../VALIDATION.md) for build prerequisites and actual baseline outcomes.
|
||||
PROPOSED after M-TESTINGMOCK-02–05: deterministic two-call reservation races, action reentry,
|
||||
action throwing, verification while calls are admitted, unmatched move-only return,
|
||||
dynamic unregister, expired test context, never/range violations, scripted cancellation,
|
||||
seed replay and diagnostics saturation. Compile-negative fixtures verify lifetime/signature
|
||||
diagnostics separately from runtime tests. Use sanitizers where supported.
|
||||
|
||||
[Performance](../PERFORMANCE.md) measures matching cost versus expectation count, contention,
|
||||
diagnostic allocation and reflection build cost, with p50/p95/p99 and peak RSS/CPU. Avoid
|
||||
optimizations that skip mismatch evidence. [Migration](../MIGRATION.md) adds explicit sessions
|
||||
first; legacy destructor verification stays documented until the major transition. Repeated
|
||||
stateful actions must opt into concurrency; existing serial tests should need only optional
|
||||
explicit close. Keep handwritten mocks usable when reflection lacks a capability.
|
||||
|
||||
Coverage: graph checks and direct reads covered cited files, including MockFunction's flagged
|
||||
template parse range. New thread-safety, property/fuzz and async behavior is planned, not
|
||||
verified by the existing move-only action test or this documentation change.
|
||||
@@ -0,0 +1,141 @@
|
||||
# Text, byte encodings and parsing utilities
|
||||
|
||||
Status: planning only; tasks below are **PLANNED**. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Existing source and tests
|
||||
|
||||
[Text's declaration](../../../src/Text/module.cmake) has no dependencies.
|
||||
[Str](../../../include/Void/Text/Str.hpp) supplies trim, case conversion, split/join,
|
||||
replacement, padding and numeric conversion in `Void::Str`.
|
||||
[Format](../../../include/Void/Text/Format.hpp) adds placeholder rendering, wrapping and
|
||||
tables; [Tokenizer](../../../include/Void/Text/Tokenizer.hpp) owns ordered matching
|
||||
rules and allocating tokens; [Semver](../../../include/Void/Text/Semver.hpp) supplies
|
||||
versions and ranges. [Diff](../../../include/Void/Text/Diff.hpp) implements Myers-style
|
||||
edit reconstruction with stored trace vectors and line adapters. This exposes a meaningful
|
||||
memory/work bound to add, including checked conversion from size_t to internal indices.
|
||||
|
||||
Byte encoders live in `Void::Encoding::Base64`, `Hex` and `Url`:
|
||||
[Base64](../../../include/Void/Text/Base64.hpp),
|
||||
[Hex](../../../include/Void/Text/Hex.hpp), [Url](../../../include/Void/Text/Url.hpp).
|
||||
URL decoding explicitly distinguishes plus-as-space; URL-safe Base64 decoding rejects
|
||||
padding and invalid trailing bits. [Html](../../../include/Void/Text/Html.hpp) has
|
||||
entity unescaping, not a complete HTML parser or sanitizer. Neither existing case helpers
|
||||
nor byte length are a Unicode normalization or grapheme contract.
|
||||
|
||||
Current suites include [Str](../../../tests/standalone/Text/Str.cpp),
|
||||
[Encoding](../../../tests/standalone/Text/Encoding.cpp),
|
||||
[Tokenizer](../../../tests/standalone/Text/Tokenizer.cpp),
|
||||
[Format](../../../tests/standalone/Text/Format.cpp),
|
||||
[Semver](../../../tests/standalone/Text/Semver.cpp), and
|
||||
[Diff](../../../tests/standalone/Text/Diff.cpp). Graph parsing is partial at Diff lines
|
||||
30/96; both signatures and surrounding algorithm were read directly.
|
||||
|
||||
## Boundary and native implementation
|
||||
|
||||
Text remains byte/ASCII infrastructure under [C-01/C-05/C-13](../ARCHITECTURE.md).
|
||||
NEW Unicode owns UTF decoding, normalization, casing and segmentation. Select one-way
|
||||
dependency **Unicode→Text**: Text never imports Unicode. An opt-in NEW
|
||||
`include/Void/Unicode/TextAdapters.hpp` lives with Unicode. Existing Text byte operations
|
||||
remain useful without versioned Unicode tables. General numeric policy stays in Math;
|
||||
legacy Text numeric wrappers may use a small explicitly declared Math adapter header,
|
||||
not force Math on every Str include. Native byte scanners and standard string/span/
|
||||
from_chars are sufficient; no regex engine, ICU or formatting dependency is required.
|
||||
Generic diff mechanics move to Algorithms; Text keeps line/patch formatting above it.
|
||||
|
||||
## NEW bounded APIs and dataflow
|
||||
|
||||
Illustrative NEW additions in NEW `include/Void/Text/Bounded.hpp`:
|
||||
|
||||
```cpp
|
||||
namespace Void::Text {
|
||||
struct TextLimits {
|
||||
std::size_t max_input = 16 * 1024 * 1024;
|
||||
std::size_t max_output = 16 * 1024 * 1024;
|
||||
std::size_t max_parts = 65536;
|
||||
};
|
||||
struct TextError { enum Code { invalid_encoding, invalid_rule, limit } code;
|
||||
std::size_t offset; };
|
||||
std::expected<std::vector<std::string_view>, TextError>
|
||||
split_views(std::string_view input, std::string_view delimiter, TextLimits);
|
||||
std::expected<std::string, TextError>
|
||||
replace_bounded(std::string_view input, std::string_view needle,
|
||||
std::string_view replacement, TextLimits);
|
||||
}
|
||||
```
|
||||
|
||||
The code is a proposed shape, not an existing compiling example. `split_views` borrows
|
||||
input; delimiter is literal bytes; empty delimiter is invalid, empty fields are retained
|
||||
unless an explicit policy drops them. Returned views expire with input. `replace_bounded`
|
||||
counts matches then checks multiply/add before reserving; it never grows beyond the
|
||||
configured cap. Empty needle is invalid. Trim/case helpers gain explicit `_ascii` names
|
||||
and deterministic classification of bytes 0–127; bytes ≥128 are preserved, avoiding
|
||||
locale-dependent behavior. Unicode casing is requested from Unicode explicitly.
|
||||
|
||||
Encoders gain `encode_into(span<char>)`/`decode_into(span<byte>)`, reporting required
|
||||
capacity and error offset. Validate the whole token and required output size before
|
||||
publishing output for all-or-nothing overloads. Separate streaming codecs expose consumed/
|
||||
produced counts and partial-output semantics. Base64 defaults are strict alphabet,
|
||||
padding and unused-bit validation; URL-safe unpadded is a named profile. Permissive MIME
|
||||
whitespace decoding is explicit. Hex rejects odd length by default. URL percent decoding
|
||||
does not apply UTF normalization, path traversal resolution or repeated decoding.
|
||||
Protocol owners decide when decoding is permitted; Text does not reinterpret signed bytes.
|
||||
|
||||
Tokenizer's NEW view mode returns kind, byte range, line and byte-column offsets without
|
||||
copying lexemes. Defaults: 128 rules, 65,536 tokens, 1 MiB/token and the common 16 MiB input
|
||||
cap. First matching rule wins, preserving current ordered-rule intent. A callback result
|
||||
of zero means no match; a result beyond remaining bytes is `invalid_rule`. Every successful
|
||||
token advances, preventing non-progress loops. Rule callables may allocate or throw;
|
||||
exceptions propagate unless the caller selects an explicit Functional adapter. An
|
||||
incremental tokenizer owns its incomplete token buffer and limits it; views passed to
|
||||
callbacks are valid only for that callback. Long scans check optional stop tokens every
|
||||
4 KiB and return an explicit stopped result with consumed offset.
|
||||
|
||||
Format gains sink/output-span variants and bounded table cell/column counts (256 columns,
|
||||
65,536 rows, 16 MiB output). Missing placeholders remain literal by compatibility policy;
|
||||
strict rendering reports missing keys. Width is bytes in Text, never terminal display
|
||||
width. Semver separates strict SemVer parsing from the existing convenient `v` prefix
|
||||
profile, and caps versions at 4 KiB, identifiers at 256 and range clauses at 128. Range
|
||||
evaluation documents prerelease admission and build metadata comparison.
|
||||
|
||||
Diff defaults cap combined input at 65,536 elements, edit distance at 4,096 and scratch at
|
||||
16 MiB. Exceeding a work limit returns `limit`, not a silently approximate patch. Use
|
||||
Algorithms' checked Myers engine and leave later linear-space reconstruction behind the
|
||||
measured large-diff capability gate. A patch includes source identity/expected deletes;
|
||||
applying it validates input instead of merely emitting inserts/equalities as proof of a
|
||||
matching source. Human patch rendering escapes control bytes and caps output.
|
||||
|
||||
## Implementation tasks
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-TEXT-01 | P0; current source | Freeze legacy byte behavior, encoding profiles, Semver ordering and diff fixtures; document allocating/borrowed return lifetimes. | sol_implementer |
|
||||
| M-TEXT-02 | P1; M-TEXT-01 | Add ASCII-explicit helpers, view splitting and checked bounded growth; high bytes and overflow sizes are deterministic without Unicode linkage. | sol_implementer |
|
||||
| M-TEXT-03 | P2; M-TEXT-02 | Add strict into-span and streaming encoding APIs; every split boundary, malformed tail and insufficient-output case preserves its stated publication contract. | sol_implementer |
|
||||
| M-TEXT-04 | P2; M-TEXT-02 | Add tokenizer view/incremental modes and rule budgets; invalid rule lengths and chunk-split tokens cannot overread or loop forever. | sol_implementer |
|
||||
| M-TEXT-05 | P2; M-TEXT-02 | Complete bounded formatting and strict/compatibility Semver profiles; prerelease/range and output-limit tests pass. | sol_implementer |
|
||||
| M-TEXT-06 | P2; Algorithms bounded-diff gate; M-TEXT-01 | Delegate generic diff, add checked patch apply and rendering; replay reconstructs target and mismatched source is rejected. | sol_implementer |
|
||||
| M-TEXT-07 | P3; M-TEXT-03–06; Unicode conformance gate | Publish optional Unicode adapter examples and installed consumers; Text-only binary links without Unicode tables and legacy adapters retain fixtures. | sol_implementer |
|
||||
|
||||
## Validation, resources and migration
|
||||
|
||||
CURRENT checks are the linked suites and parent baseline, with no new test execution.
|
||||
PROPOSED tests include arbitrary byte fuzzing, every codec chunk split, invalid padding,
|
||||
overlong percent escape tails, embedded NUL, CRLF location tracking, adversarial tokenizer
|
||||
callbacks, integer length overflow, large repeated diff inputs and strict Semver vectors.
|
||||
Round-trip tests alone are insufficient: independently specified invalid inputs must fail.
|
||||
No security claim treats HTML unescaping as sanitization or URL decoding as authorization.
|
||||
|
||||
Measure ASCII and mixed UTF-8 byte workloads, allocations per split/token, streaming
|
||||
throughput, diff worst-case scratch and build cost under [PERFORMANCE](../PERFORMANCE.md).
|
||||
Report p50/p95/p99, peak RSS/CPU and limits hit; do not compare owning and borrowed output
|
||||
without labeling their lifetime/work difference. No module starts threads; streaming
|
||||
state is owned by its caller and finalization reports incomplete input.
|
||||
|
||||
[Migration](../MIGRATION.md) retains old namespaces and byte semantics through named
|
||||
compatibility functions. Unicode adapters never silently normalize keys or signed
|
||||
documents. Existing URL-safe Base64 strictness stays protected. Rollback selects the old
|
||||
package; applications that persisted normalized data need their own format/version
|
||||
transition, not a Text-wide rewrite. See [requirements](../REQUIREMENTS.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), [VALIDATION](../VALIDATION.md),
|
||||
[DELIVERY](../DELIVERY.md) and [Unicode](../subsystems/Unicode.md).
|
||||
@@ -0,0 +1,146 @@
|
||||
# Time, injected clocks and measurement
|
||||
|
||||
Status: planning only; all feature work is **PLANNED**. Source baseline:
|
||||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||||
|
||||
## Current source
|
||||
|
||||
[Time](../../../src/Time/module.cmake) has no declared dependencies.
|
||||
[Stopwatch](../../../include/Void/Time/Stopwatch.hpp) uses `steady_clock`, mutable
|
||||
single-writer state and an unbounded vector of laps. [Format](../../../include/Void/Time/Format.hpp)
|
||||
supplies duration formatting/parsing, UTC strings and an ISO-8601 duration subset;
|
||||
fractional interval seconds are truncated and calendar years/months are unsupported.
|
||||
Some allocating format functions are `noexcept`, which requires migration review.
|
||||
[Bench](../../../include/Void/Time/Bench.hpp) lives in `Void::Bench`, distinct from
|
||||
`Void::Time`, and calls a `std::function<void()>` between two clock reads per iteration.
|
||||
It records total/min/max/mean/operations-per-second and a vector-backed Suite. There
|
||||
are no existing per-sample percentile, injected-clock or managed-timer contracts here.
|
||||
`run_for` measures each body but checks the wall budget outside it; a body can exceed
|
||||
the budget and cannot be forcibly stopped. `run` with zero iterations leaves min/max
|
||||
sentinels, unlike `run_for`'s normalized empty result.
|
||||
|
||||
[Stopwatch](../../../tests/standalone/Time/Stopwatch.cpp),
|
||||
[Time](../../../tests/standalone/Time/Time.cpp) and
|
||||
[Bench](../../../tests/standalone/Time/Bench.cpp) tests cover existing behavior. Some
|
||||
tests sleep/use real time; future deterministic tests must supplement those, not claim
|
||||
that elapsed-time nonnegativity proves clock injection. Scoped graph coverage reported
|
||||
no recorded gaps; relevant implementation and tests were read directly.
|
||||
|
||||
## Clock ownership and NEW shape
|
||||
|
||||
Time owns clocks under [C-03/C-04](../ARCHITECTURE.md); Async owns waiting, operation
|
||||
options and completion. Scheduler owns calendar jobs. Runtime may retain clock objects
|
||||
but Time never imports these modules. Native `std::chrono` is the initial backend.
|
||||
No external timer thread or timezone service starts on inclusion or construction.
|
||||
|
||||
Illustrative NEW API, proposed NEW `include/Void/Time/Clock.hpp`:
|
||||
|
||||
```cpp
|
||||
namespace Void::Time {
|
||||
enum class ClockError { negative_step, overflow };
|
||||
class MonotonicClock {
|
||||
public:
|
||||
using time_point = std::chrono::steady_clock::time_point;
|
||||
virtual time_point now() const noexcept = 0;
|
||||
virtual ~MonotonicClock() = default;
|
||||
};
|
||||
class CivilClock {
|
||||
public:
|
||||
virtual std::chrono::system_clock::time_point now() const noexcept = 0;
|
||||
virtual ~CivilClock() = default;
|
||||
};
|
||||
class ManualClock final : public MonotonicClock {
|
||||
public:
|
||||
time_point now() const noexcept override;
|
||||
std::expected<void, ClockError> advance(std::chrono::nanoseconds);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Native adapters return standard steady/system clock points. ManualClock starts at the
|
||||
steady epoch, rejects backward steps and overflow, and publishes atomic ticks for tests.
|
||||
The injected clock must have a stable lifetime through final operation shutdown. It
|
||||
does not itself wake executors: a manual-time test advances the clock then explicitly
|
||||
drives Async's timer backend. Backends must not compare manual clock deadlines with
|
||||
the host's steady `now()`. Conversion to OS waits uses `deadline - injected.now()`;
|
||||
native absolute OS deadlines are used only for a verified matching clock domain.
|
||||
An expired deadline at admission fails without submitting work. This preserves Async's
|
||||
standard steady time-point operation options while making clock-domain ownership explicit.
|
||||
|
||||
Stopwatch gains a borrowed MonotonicClock constructor and a maximum 4,096 retained laps;
|
||||
`try_lap()` reports full without growing storage. Existing convenience stopwatch uses
|
||||
the native adapter. Stop/start/reset semantics are specified independently: start clears
|
||||
elapsed and laps, resume accumulates, and split restarts at the same sampled instant.
|
||||
No operation pretends a civil-clock adjustment changes monotonic elapsed time.
|
||||
|
||||
## Duration, civil time and calendar work
|
||||
|
||||
NEW parsing accepts bounded spans (256 bytes default), uses checked accumulation in
|
||||
integer nanoseconds, and returns precise error offset, invalid-unit, overflow and
|
||||
unsupported-calendar-unit classifications. Preserve the old truncating ISO interval
|
||||
parser as a compatibility profile; NEW exact parsing never silently truncates fractions.
|
||||
Separate elapsed durations from calendar periods. UTC timestamp parse/format has fixed
|
||||
precision policies (seconds/milliseconds/nanoseconds), explicit offset handling and
|
||||
overflow checks. Do not persist `steady_clock::time_point`; persist civil instants,
|
||||
durations or Scheduler occurrence identities with a versioned schema.
|
||||
|
||||
Calendar conversion uses the standard chrono timezone facility through an optional
|
||||
adapter, with explicit `unsupported` if the selected toolchain/environment has no
|
||||
usable database. No network download is performed. Record the timezone database version
|
||||
in reproducible scheduling fixtures. Ambiguous local times require earliest/latest/reject
|
||||
policy; nonexistent local times reject by default. Leap-second handling is explicit UTC
|
||||
conversion policy, not hidden normalization. Scheduler owns next-occurrence recurrence
|
||||
algorithms and durable admission; Time owns the conversions and their diagnostics.
|
||||
|
||||
## Measurement design
|
||||
|
||||
NEW benchmark options default to 10 warmup batches, 100 measured batches, 1,000 operations
|
||||
per batch and at most 65,536 retained raw samples. Templates accept the callable directly,
|
||||
avoiding mandatory `std::function` dispatch. Record both batch elapsed time and operation
|
||||
count. Two modes are separate: throughput batching reports amortized time/op; latency
|
||||
sampling clocks individual operations and reports p50/p95/p99 of those samples. Batch
|
||||
means are never labeled individual latency percentiles.
|
||||
|
||||
Measure the empty harness/clock-read pair and type-erased versus templated call overhead
|
||||
alongside raw results. Do not automatically subtract a noisy overhead estimate or publish
|
||||
negative corrected latencies. Retain the raw baseline and explain resolution limits.
|
||||
Warmup is excluded from measured samples but still charged to total wall/CPU resource
|
||||
use. Exceptions stop a run with a failure and partial-run metadata. Zero iterations and
|
||||
nonpositive budgets are invalid in the NEW API; the old API gets normalized zero results
|
||||
for compatibility. A maximum total admission budget defaults to 30 seconds per case,
|
||||
checked between batches; one arbitrary callback may overrun and this is reported.
|
||||
Allocation/RSS/CPU probes are optional injected observers outside timed regions, not
|
||||
global interception. Result sets cap at 1,024 cases and 16 MiB retained metadata.
|
||||
|
||||
## Ordered tasks
|
||||
|
||||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-TIME-01 | P0; current source | Record parser precision, exception and bench semantics; capture empty/zero and stopwatch transition fixtures. | sol_implementer |
|
||||
| M-TIME-02 | P1; M-TIME-01 | Add native/manual MonotonicClock and CivilClock adapters plus bounded stopwatch; deterministic start/resume/split and overflow tests pass. | sol_implementer |
|
||||
| M-TIME-03 | P1; M-TIME-02; Functional pure retry contract | Validate injected-deadline domains with Async and blocking retry adapters; advancing manual time plus explicit polling expires an operation once. | astra_implementer |
|
||||
| M-TIME-04 | P2; M-TIME-01 | Add exact duration/UTC parsing and optional timezone conversions; fractions, offsets, DST folds/gaps and unsupported database paths are explicit. | sol_implementer |
|
||||
| M-TIME-05 | P2; M-TIME-02 | Add templated bounded benchmark runs, separate latency/throughput results and overhead baselines; synthetic sample quantiles and empty runs have deterministic tests. | sol_implementer |
|
||||
| M-TIME-06 | P3; M-TIME-03–05 | Publish measurement methodology, compatibility adapters and isolated consumers; observed results include environment, harness cost and resource probes. | sol_implementer |
|
||||
|
||||
## Validation and compatibility
|
||||
|
||||
CURRENT verification is the linked source/tests and the parent baseline; no benchmark
|
||||
or C++ test was rerun. PROPOSED tests use manual clocks, fixed sample arrays for quantile
|
||||
rank definitions (nearest-rank, documented), clock-domain adapters, integer overflow,
|
||||
maximum lap/sample caps and throwing bodies. Keep a small real-clock smoke test with
|
||||
tolerances; do not use sleeps for logical deadline assertions. Timezone tests pin their
|
||||
database fixtures and skip only with an explicit capability reason.
|
||||
|
||||
[PERFORMANCE](../PERFORMANCE.md) requires p50/p95/p99, throughput, allocations, peak RSS/CPU
|
||||
and build cost. Benchmark infrastructure must report its own clock resolution and
|
||||
overhead before supporting other modules' performance claims. Instrumentation overhead
|
||||
is measured separately; passing a benchmark test establishes semantics, not speed.
|
||||
|
||||
[Migration](../MIGRATION.md) retains `Void::Bench` convenience names through adapters,
|
||||
documents changed empty-run and allocating-noexcept behavior, and versions benchmark
|
||||
output schemas. Rollback selects the prior package; persisted civil timestamps must keep
|
||||
their precision/schema marker and cannot be replaced by monotonic ticks. See
|
||||
[VALIDATION](../VALIDATION.md), [DELIVERY](../DELIVERY.md),
|
||||
[DEPENDENCIES](../DEPENDENCIES.md), [requirements](../REQUIREMENTS.md),
|
||||
[Async](Async.md) and [Scheduler](../subsystems/Scheduler.md).
|
||||
@@ -0,0 +1,192 @@
|
||||
# Update — verified releases and recoverable activation
|
||||
|
||||
Status: plan; all feature tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||||
R-010/R-015 and [C-02–C-07/C-09/C-10](../ARCHITECTURE.md) govern this module.
|
||||
|
||||
## Existing source and protected behavior
|
||||
|
||||
[Feed.hpp](../../../include/Void/Update/Feed.hpp) defines `Void::Update::Feed`, `Release`,
|
||||
`VerificationPolicy`, `VerifiedFeed`, `VerifiedEnvelope`, component catalog/release types,
|
||||
verification/parsing functions and selection. Defaults cap envelopes at 5 MiB, payloads at
|
||||
4 MiB and releases at 10,000; replay floor and injected current time are already policy
|
||||
inputs. [Feed.cpp](../../../src/Update/Feed.cpp) verifies Ed25519 signatures over decoded
|
||||
payload bytes and retains those bytes as `signedPayload`. Component-set validation and
|
||||
greatest-compatible-version selection are existing capabilities.
|
||||
|
||||
Important baseline distinction: Feed.cpp includes general `Void::Json` from
|
||||
[Json.hpp](../../../include/Void/Data/Json.hpp), not
|
||||
[StrictJson.hpp](../../../include/Void/Data/StrictJson.hpp). The latter has a separate
|
||||
restricted representation/profile. Schema-3 readable-document equality currently parses
|
||||
the signed payload before the signature call; `verifyFeedEnvelope` parses the feed schema
|
||||
after `verifyEnvelope`. The target verify-before-schema rule is therefore an explicit
|
||||
hardening task, not a claim that every current envelope path already follows that order.
|
||||
Do not broaden StrictJson or silently change legacy accepted documents when modernizing Data.
|
||||
|
||||
[VersionStore.hpp](../../../include/Void/Update/VersionStore.hpp) and
|
||||
[VersionStore.cpp](../../../src/Update/VersionStore.cpp) implement prepare/publish/activate,
|
||||
commit/rollback/reconcile, external lifecycle health recording and retention. Candidate
|
||||
activation is reversible until a durable healthy-history marker newer than the activation
|
||||
journal baseline commits it. `commit` rechecks marker evidence after an apparent write/sync
|
||||
failure. After that point journal cleanup is idempotent maintenance; `rollback` finalizes a
|
||||
committed candidate instead of undoing it. Preserve these exact semantics.
|
||||
|
||||
[Update tests](../../../tests/standalone/Update/Update.cpp) cover signatures/replay/selection,
|
||||
readable envelopes, component sets, idempotent commit, durable marker reconciliation,
|
||||
external lifecycle recording, health-order/prune behavior and unsafe filesystem layouts.
|
||||
[module.cmake](../../../src/Update/module.cmake) depends on Crypto, Data, Functional, System
|
||||
and Text. The module is not currently a complete transport/download/orchestrator service.
|
||||
|
||||
## Chosen composition and NEW interfaces
|
||||
|
||||
Keep native release-selection/workflow logic and existing cryptographic implementations
|
||||
from [Crypto](Crypto.md)/[Security](Security.md). OpenSSL/libsodium remain the initial
|
||||
primitives; Update does not write its own signature algorithm. Net handles transport,
|
||||
Archive handles bounded package extraction, Plugin/Service handle live candidate lifetimes,
|
||||
and VersionStore owns durable activation. Runtime/Fsm adapters are optional composition
|
||||
layers, so parsing and store operations remain usable in an embedded application.
|
||||
|
||||
NEW illustrative Update-owned orchestration API:
|
||||
|
||||
```cpp
|
||||
enum class InstallState {
|
||||
Verified, Downloading, Staged, Published, Activated, HealthyCommitted,
|
||||
CleanupPending, RolledBack, RecoveryRequired
|
||||
};
|
||||
struct InstallReceipt { InstallId id; InstallState state; ReleaseIdentity release; };
|
||||
struct InstallOptions; // admission limits plus Async operation options
|
||||
class InstallSession; // owns candidate, staging, callbacks and progress
|
||||
Result<InstallSession> plan_install(VerifiedSelection, InstallOptions);
|
||||
// async run/stop/status adapters use Async-owned task/operation contracts
|
||||
```
|
||||
|
||||
All names in this sketch beyond existing types are NEW, including VerifiedSelection and
|
||||
ReleaseIdentity. VerifiedSelection retains the original verified envelope bytes, signer
|
||||
identity, selected component dependency set, artifact digest/size and policy decision.
|
||||
It cannot be constructed from an arbitrary caller string pretending to be verified. The
|
||||
public unsigned parsers remain clearly named structural tools and never confer trust.
|
||||
|
||||
## Verification, selection and installation dataflow
|
||||
|
||||
1. Snapshot explicit trust keys, channel/platform/ABI constraints, clock and policy at
|
||||
admission. Fetch within Net's total deadline and bounded response size. Outer envelope
|
||||
parsing is bounded and only extracts schema/key/encoded payload/signature; decode exactly
|
||||
once, retain the decoded bytes, and verify their signature before payload schema parsing
|
||||
or readable-document comparison. No reserialization or whitespace normalization is
|
||||
substituted for those signed bytes.
|
||||
2. Select the Data-owned versioned parsing policy for that envelope schema. Pin the accepted
|
||||
legacy behavior with golden signed fixtures; general JSON improvements cannot silently
|
||||
enlarge it. StrictJson's numeric/duplicate/depth rules remain unchanged. New strict-profile
|
||||
schemas must explicitly declare their representation and compatibility in M-UPDATE-02;
|
||||
migration of legacy documents requires a separate schema version if the existing corpus
|
||||
cannot be preserved. This gate cannot be bypassed by switching parser aliases globally.
|
||||
3. Validate expiry, monotonic feed sequence, platform/toolchain/ABI and component dependency
|
||||
closure before downloading artifacts. Persist a high-water sequence per configured feed
|
||||
identity/channel using atomic file replacement and directory sync before accepting a
|
||||
lower sequence on any later restart. Key rotation does not reset that floor. Valid but
|
||||
unusable releases may advance the verified-feed floor; retain their signed metadata so
|
||||
the same verified selection can resume. Explicit rollback to an already known healthy
|
||||
local version is a separate operator action, not acceptance of a replayed feed.
|
||||
4. Stream artifacts to an exclusive staging area while checking actual size and incremental
|
||||
digest. Require exact final size/digest. A resumable download is accepted only after a
|
||||
server identity/validator match and final whole-artifact digest verification; default is
|
||||
restart into a new temporary file. Redirects follow Net's credential/origin policy.
|
||||
5. Extract using [Archive](Archive.md)'s safe staging workflow and validate the release
|
||||
manifest/ABI/component inventory. Publishing immutable version directories is distinct
|
||||
from activation. Do not substitute a tar filename for authenticated artifact identity.
|
||||
6. An explicit lifecycle owner activates the candidate, waits for bounded readiness/health,
|
||||
then calls the existing VersionStore commit path (internal activation) or `recordHealthy`
|
||||
(external activation). These modes remain separate; external health recording cannot
|
||||
implicitly commit an internal activation journal. [ReloadableApplications](../platforms/ReloadableApplications.md)
|
||||
owns generation publication and quiescence; acquired old handles keep their pins.
|
||||
7. Report HealthyCommitted only after the durable marker. Cleanup/prune failures become
|
||||
CleanupPending with diagnostics and retry state, never an invitation to rollback.
|
||||
|
||||
TLS trust-chain and peer-host checks remain enabled in transport. SNI alone does not verify
|
||||
the expected peer, as the [OpenSSL 3.5 client guide](https://docs.openssl.org/3.5/man7/ossl-guide-tls-client-block/)
|
||||
explains. Network trust does not replace signed release verification. Diagnostics/progress
|
||||
must omit keys, authorization headers and artifact contents.
|
||||
|
||||
## Failure, cancellation and recovery semantics
|
||||
|
||||
Before activation, failure leaves the active version unchanged and cleans only owned staging.
|
||||
During reversible activation, readiness failure requests stop, joins candidate work, then
|
||||
rolls back through VersionStore. Cancellation after the durable healthy marker reports the
|
||||
committed state and stops only optional cleanup. A lost acknowledgement or failed sync can
|
||||
be Unknown; run `reconcile` and inspect durable health/journal evidence before choosing the
|
||||
next action. A caller must not convert every error into a rollback command.
|
||||
|
||||
One coordinator per store serializes workflow transitions; filesystem mutation still uses
|
||||
VersionStore's locking. Network work and user health/lifecycle callbacks execute outside
|
||||
store/configuration locks. Progress subscriptions snapshot owning events; unsubscribe stops
|
||||
future admissions and has a separate drain boundary. Shutdown rejects new sessions, cancels
|
||||
downloads, joins extraction/candidate work and reconciles any transition already entered.
|
||||
No forced plugin unload or asynchronous use of destroyed staging paths is allowed.
|
||||
|
||||
Restart reads the operation journal, immutable publication identity, activation journal and
|
||||
healthy history. A journal is versioned/checksummed and written before its dependent side
|
||||
effect where compensation requires it; it references existing VersionStore evidence instead
|
||||
of declaring another activation commit point. Unknown or mismatched records stop automation
|
||||
with RecoveryRequired. Corrupt metadata is not discarded to make an update appear successful.
|
||||
Retain active, pending candidate, previous candidate and pinned plugin generations; retention
|
||||
must respect both durable store protection and external live-generation pins.
|
||||
|
||||
Trust changes are explicit configuration operations: bootstrap keys come from the application,
|
||||
rotation requires an authenticated old-trust transition or an operator-approved replacement,
|
||||
and removal/revocation invalidates future selections without rewriting historical signed bytes.
|
||||
Expiry is a civil-time policy with an injected clock; time rollback cannot lower the stored
|
||||
sequence floor. Update does not invent a network time authority.
|
||||
|
||||
## Defaults and operation budgets
|
||||
|
||||
Keep existing envelope/payload/release limits. NEW defaults: one active install per store,
|
||||
eight queued selections, two concurrent artifact downloads, 512 MiB per compressed artifact,
|
||||
2 GiB staging quota, 32 components and 256 dependency edges per transaction. Package
|
||||
extraction retains Archive's absolute limits and additionally obeys the session quota.
|
||||
Reserve disk headroom for candidate plus previous healthy content before admission; do not
|
||||
delete the rollback version to make an unverified candidate fit.
|
||||
|
||||
The default install deadline is ten minutes including admission, download and activation,
|
||||
with a 30-second readiness phase bounded by the remaining total time. Use a one-second
|
||||
health probe interval and require three consecutive ready responses in the reference
|
||||
workflow; applications can replace that health policy explicitly. Health callbacks are
|
||||
cooperative owned work, not forcefully killed code. Retain two previous healthy versions
|
||||
by default, subject to pins and space diagnostics; bounded cleanup batches process at most
|
||||
16 publications per pass. A pin preventing cleanup reports pressure rather than being broken.
|
||||
|
||||
## Ordered implementation tasks
|
||||
|
||||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| M-UPDATE-01 | P0; current signed/store tests | Freeze exact-byte and durable-marker fixtures, including schema-3 verification order and cleanup failure; record baseline general-vs-strict parser boundary. | astra_implementer |
|
||||
| M-UPDATE-02 | P1; M-UPDATE-01, Data profile owner, Crypto contract | Verify-before-payload-parse, pinned schema policy and durable replay floor; invalid signatures never trigger payload schema processing and legacy fixtures retain defined behavior. | astra_implementer |
|
||||
| M-UPDATE-03 | P2; M-UPDATE-02, Net streaming/deadlines, Archive staging | Bounded download/verify/extract/publication session and resumability; wrong size/digest/path never reaches activation. | astra_implementer |
|
||||
| M-UPDATE-04 | P2; M-UPDATE-03, Plugin/Service/Fsm lifecycle | Readiness, internal/external lifecycle adapters and operation journal; exactly one activation owner and no second commit marker. | astra_implementer |
|
||||
| M-UPDATE-05 | P3; M-UPDATE-04, Runtime/Observability | Managed shutdown, retained-generation-aware pruning, trust operations and recovery status; committed cleanup failure is visible but not rollback-safe. | sol_implementer |
|
||||
| M-UPDATE-06 | P3; M-UPDATE-05, Testing fault harness | Crash/race matrix and installed reference workflow; repeated reconcile is idempotent at every transition. | astra_implementer |
|
||||
|
||||
P4 rollout coordination uses [DistributedApplications](../platforms/DistributedApplications.md)
|
||||
policy above Update; a fleet controller cannot override a host's exact-byte verification,
|
||||
generation ownership or healthy commit semantics.
|
||||
|
||||
## Validation and migration
|
||||
|
||||
CURRENT TEMPLATE, with source-verified filters:
|
||||
`<existing-build>/tests/VoidTests --filter '^(update_feed_.*|component_feed_.*|readable_component_.*|version_store_.*)$'`.
|
||||
The actual baseline and unrun checks are in [validation](../VALIDATION.md). PROPOSED after
|
||||
M-UPDATE-02–06: mutate signed bytes while preserving equivalent JSON, invalid signature with
|
||||
malformed payload, duplicate/oversized/deep fields under each declared profile, schema-3
|
||||
mirror mismatch, replay after restart/key rotation, download redirect/partial/hash failure,
|
||||
disk full, callback reentry, activation-time cancellation and crash at every health/journal
|
||||
sync. Inject cleanup failure after commit and assert that rollback preserves the candidate.
|
||||
|
||||
Use [performance](../PERFORMANCE.md) for verify/select latency, streaming throughput, activation
|
||||
p50/p95/p99, peak RSS/CPU/staging space and build cost; use common sample/confidence rules.
|
||||
Report retained generations and failed installs, not only successful fast paths.
|
||||
|
||||
[Migration](../MIGRATION.md) preserves existing verification and VersionStore interfaces via
|
||||
adapters. Store-journal upgrades are versioned and recover old records before admitting new
|
||||
work; backup old metadata without erasing commit evidence. Unknown newer schemas are rejected.
|
||||
Roll back candidate code only before its healthy commit, or perform a new explicit activation
|
||||
of a known healthy version afterward. No automatic schema/data downgrade is implied.
|
||||
Graph coverage was checked; partial Feed declarations/definitions and adjacent Json ranges
|
||||
were read directly. These planned changes have not been built, fuzzed or crash-tested.
|
||||
Reference in new issue
Block a user