docs: add expansion roadmap and workflow baseline

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

No files matched your search

@@ -0,0 +1,152 @@
# DistributedApplications platform plan — NEW reference compositions
Status: planning only; reference applications below are future artifacts, not runnable
applications in this checkout. All tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-009–R-016;
[architecture](../ARCHITECTURE.md) C-01–C-14, especially C-12/C-14.
## Baseline and product boundary
Current [Net](../../../include/Void/Net/Http.hpp),
[Security](../../../include/Void/Security/Security.hpp) and
[ShortUrl V1](../../../include/Void/ShortUrl/ShortUrl.hpp) are individual building blocks.
They do not constitute a distributed platform. Source/graph metadata was checked; Net
Http.hpp gaps 112/115 were read directly. There is no distributed launcher, membership
operator, broker, replicated database or acceptance suite claimed at this baseline.
Proposed reference source under `examples/distributed/` and tests under
`tests/integration/distributed/` are NEW; names/targets are assigned only during implementation.
This platform composes [NetworkedApplications](NetworkedApplications.md)'s managed service
and [ReloadableApplications](ReloadableApplications.md)'s optional upgrade discipline with
RPC, Messaging, Discovery, Coordination, Replication and DistributedStorage. It owns startup,
readiness, operator workflows, fault scenarios and reference applications. It does not own
alternative consensus, storage, TLS, task or observability implementations. Linux is the
initial validation host; process/container orchestration is a test/deployment adapter,
not a hidden dependency of embedded libraries.
## Future reference applications and NEW composition API
Choose two bounded first applications: a three-node fixed-membership replicated KV service,
and an at-least-once durable worker queue backed by one replicated group. The KV example
exercises conditional batches, read policies, session dedup, snapshot/restart and backup;
the queue example exercises durable publish/ack, duplicate delivery, poison messages/DLQ
and consumer recovery. A distributed ShortUrl repository is a later optional integration
recipe and must preserve its frozen V1 interface. No arbitrary external service/account or
paid infrastructure is required to run the future loopback tests.
```cpp
// NEW illustrative platform composition; component types remain owner-defined.
struct NodeConfig {
ClusterId cluster; NodeId self; FixedVoterSet voters; BootstrapEndpoints peers;
StorageConfig data; NetServerPolicy transport; ResourceBudget resources;
};
class DistributedHost {
static Result<DistributedHost> compose(NodeConfig, InjectedResources);
Task<Result<Readiness>> start(OperationOptions);
Task<Result<void>> stop(OperationOptions);
};
```
The host retains owned services and borrows injected executor/clock/allocator only through
final join. Async owns operation options and scopes, Runtime owns managed resources, Service
owns lifecycle handles. Embedded applications can construct the same graph with supplied
resources and explicit startup. Configuration is an immutable validated snapshot; changing
voter lists is not hot-reload configuration. Local node identity, data directory, peer trust
mapping and static bootstrap endpoints are explicit. No global singleton starts a cluster.
## Startup, readiness and shutdown algorithm
1. Validate config/schema, fixed group identity, peer identities, directory ownership,
quotas and available backend capabilities. Missing trust material is a startup failure;
credentials are runtime inputs and never checked into examples or printed in diagnostics.
2. Create owned resources, open native Storage and recover protocol/application/snapshot
state. Verify application+dedup+applied index consistency before listeners accept work.
Expose an isolated administrative health interface only under explicit bind/auth policy.
3. Start authenticated peer RPC listener and static Discovery provider. Connect fixed peers;
run the Replication adapter and election. Discovery availability is not a quorum vote.
User listener may bind but rejects calls until the selected service's readiness gate.
4. KV readiness requires an available leader path, current-term committed barrier and local
recoverable application state; leader-only write readiness is distinct from follower
process liveness. Queue readiness additionally requires storage quota and consumer/queue
admission health. A follower can report healthy-but-not-write-ready. Consistent reads
still perform per-operation quorum confirmation; readiness is not a lease.
5. Publish services/endpoint hints after readiness. Start periodic snapshot/observation tasks
through owned scopes; optional coordination-backed Discovery starts only after the
replicated directory is ready and never replaces static Raft membership.
6. Stop external admission and readiness publication, finish or cancel client scopes, drain
mandatory durable actions, stop consumers and peer admission as appropriate, join all
replication/transport/snapshot tasks, then close storage and finally execution resources.
Default grace is 30 seconds; expiry reports incomplete stop while preserving owned state
until join. Do not destroy resources merely to make shutdown appear bounded.
## Operational decisions and failure matrix
Initial profile: three voters, one group/service, one data directory/node, no shared database
file, no automatic member replacement. Use explicit static cluster identity and per-node
authenticated TLS identity. Security authorization separates peer, client and administration
actions; a client cannot issue peer consensus messages. Certificates/trust policy are rotated
with overlapping validated trust generations and connection draining, never disabling checks.
Default platform budgets are the minimum of component limits, plus a host aggregate: 256 MiB
queued/stream payloads, two simultaneous snapshots, 16 active groups and 1,024 external calls.
Account storage caches/indexes separately in RSS; this is not a 256 MiB total-process promise.
| Scenario | Expected service/operational result | Acceptance evidence |
| --- | --- | --- |
| One of three nodes stops | Majority continues after election; no acknowledged state lost | Client history plus durable recovered state |
| Two of three unavailable | No new committed writes or consistent reads; stale reads only by explicit policy | Minority old-leader test |
| Apply committed, response lost | Same identity returns original result | Kill leader at apply/reply boundary |
| Slow/full/failed disk | Admission pressure or group fault; no pre-sync success | Fault port plus real filesystem pressure |
| Corrupt log/snapshot | Quarantine node/group; restore or rebuild under explicit procedure | Mutation/restart test and diagnostics |
| Poison work / worker crash after effect | Retry/DLQ; duplicate side effect possible without application dedup | Worker inbox/outbox demonstration |
| Discovery or metrics unavailable | Static peer transport remains usable; observation failures bounded; no quorum weakening | Disable optional adapters |
| Snapshot load / slow follower | Rate-limited catch-up; bounded queues and readable leader | Long-lag soak and RSS/disk metrics |
| Rolling binary/schema mismatch | Refuse unsupported peer/command; operator halt before unsafe rollout | Mixed-version fixture matrix |
| Loss of quorum disks | Operator recovery into separately identified cluster; no automatic force-new-cluster | Recovery rehearsal and explicit data-loss report |
Metrics: term/role/quorum state, commit/applied lag, sync duration/errors, queue/DLQ depth,
admission rejection, cancellation, snapshot progress and disk headroom. Cap labels at
configured node/group/queue identities; no payloads, raw keys or bearer tokens. A diagnostic
bundle contains version/config fingerprints and sanitized histories, not credentials/data.
SLO profiles are chosen from measured workloads, with separate normal, failover and recovery
latency. Benchmark absence cannot be reported as a production reliability claim.
## Ordered platform backlog
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| P-DISTRIBUTED-01 | P0; baseline | Define future examples, deterministic failure histories and readiness states; no runnable artifact claim | astra_implementer |
| P-DISTRIBUTED-02 | P1; P-DISTRIBUTED-01, Runtime/Service/Async contracts | NEW host graph specification and fake component lifecycle tests; injected resources outlive join | astra_implementer |
| P-DISTRIBUTED-03 | P3; P-DISTRIBUTED-02, NetworkedApplications gate, RPC/Discovery | Single-node reference composition and authenticated peer fixture; bounded startup/rollback/shutdown | sol_implementer |
| P-DISTRIBUTED-04 | P4; P-DISTRIBUTED-03, Coordination/Replication/DistributedStorage single-group gates | Three-node KV reference and linearizability/crash histories; quorum reads and durable replies | astra_implementer |
| P-DISTRIBUTED-05 | P4; P-DISTRIBUTED-04, Messaging replicated queue gate | Worker queue reference, inbox/outbox and DLQ operations; at-least-once failure matrix passes | sol_implementer |
| P-DISTRIBUTED-06 | P4; P-DISTRIBUTED-04, snapshot/recovery gates | Backup/restore, trust rotation, mixed-version rollout and chaos tooling; restore rehearsals retain identities correctly | astra_implementer |
| P-DISTRIBUTED-07 | P4 later; P-DISTRIBUTED-06, DistributedStorage routing/movement gates | Range movement operations and optional replicated directory; ownership/freeze/crash evidence before scale claims | astra_implementer |
## Evidence, migration and release gate
CURRENT evidence is the root-recorded baseline build/tests in [VALIDATION](../VALIDATION.md),
not distributed feature evidence. No builds, benchmarks, fault tests or deployments ran
for this document. PROPOSED tests first run deterministic adapters, then three independent
processes with isolated ports/directories, controlled packet faults and kill/restart points.
Test harnesses collect complete operation histories including unknown outcomes, seeds and
fault timelines; acceptance checks linearizability, dedup, applied positions, durable replies,
resource bounds and shutdown. No future launcher command is advertised as presently usable.
Build/consumer gates follow [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Use [PERFORMANCE](../PERFORMANCE.md) to record p50/p95/p99, throughput, allocations, peak
RSS/CPU, disk amplification/recovery, network traffic and build cost. Compare one/three/five
node profiles only after corresponding membership configurations are supported and verified.
Durability tests follow [SQLite's crash fault methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior);
consensus safety follows the selected [Raft protocol](https://raft.github.io/raft.pdf), with
application-specific integration evidence still mandatory.
Rollout first verifies every node can read existing log/snapshot/application formats, then
deploys readers, then enables new commands only after all voters advertise support. Rollback
stops new command admission and requires old readers for everything already durable. Plugin
reload does not unload an in-use state-machine implementation: pin through active apply and
snapshot work, and migrate state only at a recoverable checkpoint. Majority-loss restoration,
voter changes and data-destructive repair are operator-authorized procedures, never automated
startup fallbacks. See [MIGRATION](../MIGRATION.md), [DELIVERY](../DELIVERY.md) and
[DEPENDENCIES](../DEPENDENCIES.md). A fresh independent integrated review and full affected
behavior checks precede any merge/release recommendation; documentation completion is not release.
@@ -0,0 +1,244 @@
# NetworkedApplications — bounded reference services and operations
Status: NEW platform composition plan; all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`. This document specifies future reference
applications only; it creates no server, deployment, open port or runnable command.
R-003/R-007/R-009/R-010/R-012 and [C-01–C-08/C-11/C-14](../ARCHITECTURE.md) apply.
## Existing pieces and composition boundary
The inspected repository already contains [Sqlite](../../../include/Void/Sqlite/Sqlite.hpp)
RAII operations, [Log](../../../include/Void/Log/Log.hpp) facade/sinks,
[Archive](../../../include/Void/Archive/Archive.hpp) extraction and
[Update VersionStore](../../../include/Void/Update/VersionStore.hpp) activation primitives.
They do not by themselves establish the startup, request ownership, durability or shutdown
contract of a complete service. Their existing tests remain module evidence, not an
end-to-end platform acceptance result. Native Storage and Observability are NEW designs.
The platform composes [Runtime](../subsystems/Runtime.md), [Async](../modules/Async.md),
[IO](../subsystems/IO.md), [Net](../modules/Net.md), [Configuration](../modules/Configuration.md),
[Service](../modules/Service.md), [Security](../modules/Security.md),
[Storage](../subsystems/Storage.md), [Sqlite](../modules/Sqlite.md),
[Log](../modules/Log.md) and [Observability](../subsystems/Observability.md).
It owns wiring, reference domain workflows, lifecycle policy and operational acceptance.
It does not own a second executor, HTTP parser, TLS engine, database, logger or error type.
Optional RPC/jobs use their existing plan owners, and no foundation imports this platform.
Choose Void-owned native protocol/IO paths when their conformance gates pass. Preserve
the existing Boost-based paths behind documented adapters during migration; do not replace
them merely to declare the platform native. IO owns level-triggered epoll/nonblocking sockets
and bounded file workers under C-06, Net owns protocol/session reuse, and OpenSSL supplies
TLS. Verify both trust and peer identity for outbound clients; SNI is a distinct setting.
[OpenSSL's client guide](https://docs.openssl.org/3.5/man7/ossl-guide-tls-client-block/)
is the primary TLS implementation reference.
## Reference applications and NEW composition surface
PROPOSED source locations are `examples/platforms/networked-kv/`,
`examples/platforms/networked-client/` and later `examples/platforms/networked-jobs/`.
These are NEW paths, not existing examples to run. Build them as installed-package consumers
so accidental whole-repository linkage cannot hide missing dependencies. The reference
service first uses a native Storage backend; a separate SQLite profile exercises first-class
SQL integration with its own schema/migrations. Both implement only the explicitly common
reference-domain contract; they are not interchangeable engine/file-format facades.
NEW illustrative platform-owned API, subject to module-owned type definitions:
```cpp
struct NetworkedConfig; // validated listener/domain/limit configuration
struct ApplicationResources; // owning/borrowed handles to module-owned resources
class NetworkedApplication {
public:
static Result<NetworkedApplication> create(ApplicationResources, NetworkedConfig);
Result<void> start();
Result<HealthSnapshot> health() const;
// stop/join use Async's operation options and completion contract
};
```
`Result` is C-02 shorthand; HealthSnapshot and the composition wrapper are NEW platform
types. Resources do not define competing executor/clock/memory/telemetry interfaces. Embedded
mode borrows application-supplied module resources through final join. Managed mode explicitly
starts Runtime, which owns them through shutdown. Construction alone opens no listeners or
workers. The reference client uses Net sessions, total deadlines and checked responses;
it never blindly retries a mutating request on a new connection.
## Initial HTTP key-value workflow
HTTP/1.1 is the first protocol profile. The service has the following NEW application
endpoints; Net remains responsible for parsing and framing.
| Endpoint | Contract and storage effect |
| --- | --- |
| `GET /v1/kv/{key}` | Canonical base64url key, bounded owning value response and opaque version ETag; 404 only for an absent key in the captured snapshot. |
| `PUT /v1/kv/{key}` | Raw value body, required idempotency ID and explicit absent/version precondition; atomically store value/new version and request outcome. |
| `DELETE /v1/kv/{key}` | Required version precondition/idempotency ID; atomically tombstone/remove plus record outcome. |
| `GET /v1/scan` | Bounded page within a retained snapshot; opaque expiring cursor, no leaking raw database sequence/file offsets. |
| `GET /v1/operations/{id}` | Auth-scoped known outcome or explicit Unknown; absence/expired retention is never proof that a write did not commit. |
| `/live`, `/ready`, `/metrics` | Separate administrative listener; lifecycle status and bounded telemetry, no data mutation or credential dump. |
Request flow is accept → protocol bounds → deadline/admission → authentication/authorization
→ decode/validate → domain operation → durable backend result → response encoding/write.
Each request owns a task scope, context snapshot, body buffers and storage handles until
exactly one completion and final backend access. Buffer ownership extends past socket close
if a write is still completing; disconnect does not roll back an already committed mutation.
Native Storage uses one conditional batch for the business key/version plus a reserved
application namespace containing idempotency record/result. SQLite uses one explicit
transaction and unique request-id constraint plus version-checked update; affected-row
count and stored outcome are checked before commit. No operation spans both backends in
one atomic promise. Domain adapters expose Conflict, NotFound, Overloaded, Unavailable and
UnknownCommit separately, preserving backend causes in bounded internal diagnostics.
Idempotency IDs are scoped to authenticated principal and operation type. Persist a digest
of canonical operation/key/precondition/body with the outcome; the same ID with different
inputs is Conflict. Retain records for at least 24 hours, with a default 100,000-record/
256 MiB budget; when full of unexpired records, reject new mutations instead of evicting
live deduplication promises. After the advertised retention window, clients must inspect
business state or obtain a new explicit decision, not retry an old ID as though dedup were
permanent. GC runs in bounded backend transactions/batches. Persist enough time/high-water
metadata that backward clock changes cannot shorten the advertised retention horizon.
Durable success is returned only after the chosen backend's durable commit succeeds. If
commit succeeded but the socket write fails, a retry with the same ID retrieves the stored
outcome. A backend Unknown makes readiness reflect recovery state and returns a structured
503 with operation ID/outcome=unknown when a reply is possible. A canceled pre-admission
request has no effect; cancellation after submission must retain outcome uncertainty.
Do not classify a transport timeout as a safe reason to create a new ID and replay the write.
## Startup, configuration and shutdown
Startup is a dependency-ordered transaction:
1. Validate configuration and capabilities, select embedded/managed resource ownership,
install bounded early diagnostics, load trust/auth policy and reserve budgets.
2. Open the selected database, recover/reconcile it, and validate schema/format compatibility.
Required migrations run only under their explicit migration gate; never expose readiness
while silently upgrading a store of unknown provenance.
3. Register service/domain handlers and telemetry, then start protocol listeners. Default
reference data listener is `127.0.0.1:8080`, admin is `127.0.0.1:9090`; tests use assigned
ephemeral loopback ports. Binding external interfaces requires explicit application
configuration with TLS and authentication policy.
4. Publish readiness only after storage, handler dependencies and mandatory resources are
healthy. On failure, close listeners/registrations and unwind started resources in reverse
dependency order, preserving the original failure and cleanup diagnostics.
Configuration reload parses a complete candidate, validates limits/paths/certificates,
then atomically publishes an immutable configuration generation. In-flight requests keep
their old generation. Level/telemetry policy and new-connection TLS material can change
live; backend selection, database path and persistent schema require a restart/migration
workflow. Do not partly install a configuration whose second listener fails to bind.
Hot code replacement follows [ReloadableApplications](ReloadableApplications.md), not an
uncoordinated callback swap in this platform.
Shutdown first marks unready and closes new admission/keepalive reuse, then drains requests
for 20 seconds, requests cooperative stop, and joins them within a default 30-second total
shutdown budget where supported. Storage operations that already crossed a commit boundary
finish/report their outcome. If arbitrary application code does not cooperate, an external
process supervisor may terminate the service; the library does not forcibly destroy its
objects and claim clean shutdown. After tasks join: flush/checkpoint as configured, close
database handles, flush telemetry/logging, stop IO/executors and release resources. Never
destroy the logger/exporter first while tasks still hold callbacks into it.
A timed-out telemetry flush retains its backend ownership and execution dependencies;
Runtime reports shutdown_incomplete until those calls quiesce and can be joined. The
platform must not treat the flush timeout as permission to stop their IO/workers.
## Admission, security and operation budgets
These are NEW reference-profile defaults, not universal module defaults. Apply the smaller
of platform and module limits; reject contradictory configurations at startup.
| Resource | Default |
| --- | --- |
| Connections | 1,024 total; 128 per authenticated principal/source admission bucket, with bounded bucket registry. |
| Requests | 256 active, 512 waiting; four pipelined requests/connection; overload returns 503 or closes before body admission. |
| Input/output | 16 KiB headers, 64 header fields, 64 KiB mutation body, 1 MiB output page; 64 MiB total admitted request/response buffers including sends in flight. |
| Time | Five-second total request deadline, two-second header deadline, 30-second keepalive idle timeout; retries consume the original total budget. |
| Scans | 64 retained cursor snapshots, 30-second idle lease, 1,024 rows/page; expiry explicitly ends the cursor instead of switching snapshots silently. |
| Control plane | Four admin requests concurrently, 64 KiB admin response, separate admission reserve so data overload cannot starve health. |
Rate-limit registry cardinality is bounded at 4,096 buckets with conservative shared overflow
limits, preventing attacker-created IP/identity labels from exhausting memory. Use a caller-
approved authentication adapter; the reference profile uses explicit static test identities
on loopback and a configured verified credential mechanism for external deployment. Production
secrets stay in runtime secret/config facilities and never appear in examples, metrics or logs.
Map authorization to key namespaces before storage access, including scans and operation-status
lookups. Admin endpoints expose aggregate health only and bind separately by default.
Malformed framing, conflicting lengths, oversized bodies, slow readers and connection churn
are Net conformance cases plus platform resource tests. Optional compression cannot expand
past the same body cap. TLS configuration is replaced only for new handshakes; active sessions
retain their state through completion. Outbound redirects cannot forward origin-sensitive
credentials cross-origin. Untrusted trace headers supply context, never user identity.
## Operational workflows and later capabilities
Health reports separate process liveness, readiness and degraded optional exporters. Database
RecoveryRequired, mandatory auth failure or exhausted durable-write capacity makes the service
unready for mutations; a telemetry outage alone does not. Metrics use bounded route/status/
backend labels and include admission rejection, active requests, total owned bytes, commit
latency, Unknown outcomes, oldest snapshot and exporter loss. Request IDs belong in bounded
logs/traces, not metric labels.
Backup is an authenticated operator workflow using the selected backend's consistent backup
API. Verify a restore into a separate directory and run read-only domain checks before any
traffic switch. Do not copy an open SQLite main file alone or a moving native table set.
Upgrades validate module/package versions and persistence compatibility; [Update](../modules/Update.md)
can stage signed application artifacts, while application schema changes remain separately
gated. A committed data migration is not undone by choosing the previous executable.
The later job reference composes [Scheduler](../subsystems/Scheduler.md) and
[Messaging](../subsystems/Messaging.md) for durable admission, retries and acknowledgements.
It demonstrates an outbox/deduplication workflow with at-least-once external delivery, not
exactly-once effects. The RPC profile reuses [RPC](../subsystems/RPC.md) serialization and
transport contracts. P4 service discovery/replication integrate through
[DistributedApplications](DistributedApplications.md); this initial single-node platform
makes no minority-write, leader-election or cross-shard consistency promise.
## Ordered platform tasks
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| P-NETWORKED-01 | P0; shared contracts and module plans | Freeze reference-domain operations, limits, error mapping and startup/shutdown DAG; backend-specific guarantees are explicit. | astra_implementer |
| P-NETWORKED-02 | P2; P-NETWORKED-01, Runtime/Async/IO/Net lifecycle gates | Embedded/managed composition skeleton and installed-package consumer; no hidden workers before start, failed startup unwinds ownership. | astra_implementer |
| P-NETWORKED-03 | P3; P-NETWORKED-02, Storage durable batches/snapshots, Security, Configuration | Native durable KV service and client, idempotency/version/scan workflows; lost replies never cause partial or duplicate mutations inside retention. | astra_implementer |
| P-NETWORKED-04 | P3; P-NETWORKED-02, Sqlite checked transaction/migration gates | Independent SQLite service profile with schema/backup workflow; shared domain tests pass without claiming identical engine semantics. | sol_implementer |
| P-NETWORKED-05 | P3; P-NETWORKED-03/04, Log/Observability, Update recovery | Operational health, graceful shutdown, config generations, backup/restore and signed-code-upgrade scenario; cleanup failure and schema rollback limits stay visible. | astra_implementer |
| P-NETWORKED-06 | P3; P-NETWORKED-05, Testing fault/performance harness | Protocol interoperability, overload/crash matrix and workload baselines; bounded memory and durable-ack invariants hold with slow clients/storage/exporters. | astra_implementer |
| P-NETWORKED-07 | P3; P-NETWORKED-05, Scheduler/Messaging/RPC capability gates | Job and RPC reference compositions; retries, cancellation and duplicate delivery match their module contracts. | sol_implementer |
| P-NETWORKED-08 | P4; P-NETWORKED-06/07, distributed platform gates | Add discovery/replicated domain adapters through owners; partition behavior is tested before an availability/consistency claim. | astra_implementer |
## Acceptance scenarios, commands and migration
CURRENT: aggregate module build/tests exist, as recorded in [validation](../VALIDATION.md).
No reference-server executable or platform-specific CTest entry is claimed. PROPOSED command
templates after P-NETWORKED-02 registers the consumers and P-NETWORKED-06 adds the test label:
`cmake --build <configured-build> --target <registered-reference-target>` and
`ctest --test-dir <configured-build> -L networked-platform --output-on-failure`.
Target/label registration is implementation work; these commands were not run.
Acceptance exercises both embedded and managed modes: start/fail-start/restart, parallel
conditional writes, duplicate ID with same/different body, disk full and failed sync,
response loss after commit, cursor expiry under compaction, slow header/body/response,
wrong-host/untrusted TLS, authenticated namespace isolation, config reload races, telemetry
failure, signal-triggered shutdown and restore of a consistent backup. Use private local
fixtures, assigned ports and disposable directories; no public endpoint or production data
is required. Check durable receipts against recovered backend contents after forced process
termination. SQLite and native Storage get separate evidence records.
[Performance](../PERFORMANCE.md) governs warmup, repetitions, confidence intervals and
regression thresholds. Measure cold/warm TLS, keepalive, tiny/large values, mixed reads/writes,
scans and overload, retaining per-request p50/p95/p99 plus throughput, rejection/timeouts,
allocations, total peak RSS/CPU (all workers), storage amplification and installed build cost.
Drive independent client arrival schedules so queueing latency is not hidden. Hard budgets
are correctness gates; only measured workload baselines can set later numerical latency SLOs.
[Migration](../MIGRATION.md) versions HTTP/domain schemas separately from package/storage
formats. Additive response fields remain ignorable; required semantic changes use a new
endpoint version. Backend migration exports a consistent logical snapshot into a new store,
checks key/value/version/dedup invariants, then changes routing under a controlled write pause.
Rollback to an old store after new writes requires reconciliation; switching a config string
is not sufficient. [Documentation](../DOCUMENTATION.md) owns operator/client walkthroughs and
[delivery](../DELIVERY.md) owns evidence gates. Cited existing component headers have graph
coverage checks and source verification; all platform APIs, applications and end-to-end
validation here are future work.
@@ -0,0 +1,257 @@
# Reloadable applications reference-platform specification
Status: PLANNED platform and future runnable-host specification. No host, executable,
deployment configuration or feature code is implemented by this document. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Requirements R-004, R-009, R-010 and R-013–R-016 apply.
[Architecture](../ARCHITECTURE.md) C-03–C-05, C-07, C-09, C-10, C-11 and C-14
defines the platform contract.
## Source baseline and composition boundary
Existing [PluginManager](../../../include/Void/Plugin/Manager.hpp) supports pinned
generations, transactional candidate validation and immutable-path replacement.
[Module.hpp](../../../include/Void/Plugin/Module.hpp) supplies C++ module descriptors
and lifecycle hooks; it is not a stable C-only interface.
[PluginServiceBinding](../../../include/Void/Service/PluginService.hpp) pins providers;
[ServiceRegistry](../../../include/Void/Service/Registry.hpp) still has borrowed require
and lock-held lifecycle gaps. [Fsm Machine](../../../include/Void/Fsm/Machine.hpp)
already serializes named application state but needs boundary/quiescence guarantees.
[Configuration Watch](../../../include/Void/Configuration/Watch.hpp) preserves parse
failures but publishes before its observer callback, so it is not a platform transaction.
[VersionStore.hpp](../../../include/Void/Update/VersionStore.hpp) explicitly separates
reversible activate/rollback from durable commit: the durable healthy-history event is
the commit marker, and later journal cleanup can fail after commitment. This boundary
must remain authoritative. Source paths were coverage-checked, with partial Plugin,
Service and Configuration declarations directly read. Existing
[reload-under-load](../../../tests/standalone/Plugin/HotReloadUnderLoad.cpp),
[replacement](../../../tests/standalone/Plugin/Manager.cpp),
[Fsm serialization](../../../tests/standalone/Fsm/Serialize.cpp), and
[configuration watch](../../../tests/standalone/Configuration/Watch.cpp) fixtures cover
ingredients; they do not prove a runnable reload platform exists.
The platform composes [Runtime](../subsystems/Runtime.md),
[Async](../modules/Async.md), [IO](../subsystems/IO.md),
[Service](../modules/Service.md), [Plugin](../modules/Plugin.md),
[Fsm](../modules/Fsm.md), [Configuration](../modules/Configuration.md),
[Update](../modules/Update.md), [Security](../modules/Security.md),
[Log](../modules/Log.md) and [Observability](../subsystems/Observability.md).
It owns ordering, host policy and operator experience, not alternate implementations
of their shared primitives. Optional process workers use [IPC](../subsystems/IPC.md).
Distributed membership/consensus is not a prerequisite for local reload.
## Future reference host and user journeys
NEW proposed application root: `examples/reloadable-host/`; NEW proposed target and
installed executable: `void-reloadable-host`. These are specification names only.
The host starts from an explicit trusted release directory/config path, validates a
release, creates Runtime resources, starts required services, restores boundary state,
then admits application calls. It never watches arbitrary directories or loads an
unverified library solely because its mtime changed.
The reference workload is a counter/workflow provider. Version A serves acquire/read/
increment and a cancellable delayed operation; version B changes internal layout and
migrates a versioned checkpoint while preserving durable counter operations. It exposes
both a same-toolchain C++ fixture and a separate stable C-table fixture. A client holds
an old read handle across replacement, while a delayed callback proves activity pinning.
Stateful increments use operation IDs and one authoritative state owner; the example
does not promise duplicate-free external effects from checkpointing alone.
Future local operator commands are inspect, validate-candidate, reload, health, drain,
shutdown and recover. They run through an authenticated local IPC control endpoint;
network exposure is disabled by default. Inspect reports active release/publication
epoch, readiness, retained generations, async pins, quiescence phase and last error
category without secrets. Reload returns a transaction ID and a phase-aware outcome.
Remote request cancellation can stop preparation but cannot undo publication or a
durable healthy commit. A lost reply is inspected by transaction ID before retry.
Future CLI examples below are PROPOSED syntax, not available commands:
```text
void-reloadable-host --release-root <owned-directory> --config <validated-file>
void-reloadable-host ctl inspect --endpoint <local-socket>
void-reloadable-host ctl reload --candidate <immutable-release-id> --deadline 30s
void-reloadable-host ctl recover --release-root <owned-directory>
```
Angle-bracket arguments denote application inputs in proposed documentation, not
unresolved implementation choices. Build/install/run prerequisites and target selection
will be added only when the reference target exists, following
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
## NEW host generation and interfaces
Illustrative composition types, not library declarations:
```cpp
struct HostGeneration { // NEW platform-owned aggregate
ReleaseId release;
PublicationEpoch epoch;
ValidatedConfigurationView configuration;
ServiceRegistrySnapshot providers;
WorkflowCheckpointMetadata workflow;
std::vector<PluginGenerationLease> plugins;
};
// prepare_reload(candidate, Async::OperationOptions) -> Task<Result<PreparedReload>>;
// publish(PreparedReload&&, ExpectedEpoch) -> Result<PublicationEpoch>;
// inspect(transaction_id) -> ReloadOutcome; // includes durable commit state
```
Shared types belong to their module plans. HostGeneration is retained behind a single
publication pointer; its providers/configuration/plugin identities describe one epoch.
The Service-owned publication primitive is the publication authority for the host:
store HostGeneration/config views as part of that immutable registry generation and
derive manager/host acquisition from it. Do not separately swap PluginManager current,
Configuration current and the service table and call that atomic. Configuration exports
a prepared immutable view to this coordinator; its standalone controller is not another
publisher for the same host generation. A request captures one generation at admission.
Initial host supports one reload transaction at a time and one application process.
Required dependencies form a DAG; optional dependencies have explicit absence behavior.
ActivationPolicy Reloadable uses the protocol below; RestartRequired performs a supervised
stop/start with persisted application checkpoint; InstallerRequired returns an operator
action without executing a privileged installer. No mode silently escalates permissions.
## Candidate-to-commit dataflow
1. **Discover/verify.** Resolve an immutable release ID under the owned release root.
Update/Security verify the signed manifest and exact signed payload bytes before
parsing its schema. Validate path containment, hashes, ABI/application contracts,
dependency versions and retained-resource budgets. Existing StrictJson and frozen
ShortUrl V1 fixtures remain unchanged. A file watch only suggests a validation job.
2. **Prepare privately.** Create candidate module instances and configuration/resource
views in a private Service snapshot. No candidate accepts user requests or publishes
external writes. Validate startup/readiness prerequisites before interrupting the old
application. A module that cannot stage reversibly requires restart policy.
3. **Quiesce stateful owners.** Stop old-generation mutation admission, await admitted
writes and child scopes, and ask Fsm to checkpoint at a declared state boundary.
Existing read handles can remain valid if the provider declares snapshot-safe reads;
other old-handle calls return quiescing rather than entering a second writer. Stop
and join race losers, subscriptions and generation-owned activities as specified by
Async/Fsm/Plugin. A deadline retains ownership and fails the candidate safely.
4. **Restore/readiness.** Candidate validates checkpoint schema into private state,
prepares compatible persistent views, activates staged resources and reports readiness.
Readiness includes dependency health and a bounded synthetic operation; it is not
merely a successful factory call. Do not perform an irreversible persistent format
migration inside a reversible reload. Such a release requires an explicit migration
gate with separate backup/rollback policy.
5. **Activate reversibly and publish.** Persist the bounded versioned application
checkpoint to an immutable file using System's NEW durable replacement protocol,
with release/schema identity and checksum; sync its recovery dependencies before
recording its reference. Today's non-fsync `atomic_write` is insufficient. Call
VersionStore activation for the verified candidate to record the durable reversible
activation journal. Then publish one
preallocated host/Service generation after rechecking expected epoch. No fallible
plugin code or user callback runs under the publication guard. A failure before
publication rolls back VersionStore activation, disposes/joins the candidate and
resumes the old owner. Failed rollback/resume is degraded recovery, not success.
6. **Health window.** Observe required services and bounded synthetic checks for a default
10-second window. During this reversible window, admit snapshot-safe reads only;
queue no unbounded writes. Mutation requests receive retryable not-ready/quiescing.
This preserves the old checkpoint as a valid rollback continuation. A release that
requires writable probation needs a separately proven compatible shared-state protocol
before enabling it. On failure, republish the retained old generation, roll back the
reversible activation and resume old mutation admission after validation.
7. **Commit and reopen writes.** Commit through VersionStore's durable healthy event.
Once commitment is known durable, enable candidate mutations and retire old owners.
Failure/lost acknowledgement is resolved by VersionStore reconciliation/inspection
before choosing rollback. Cleanup failure after the healthy marker reports
committed-with-cleanup-error; never roll back as though the commit had not occurred.
8. **Reclaim.** Drain old external generation references and async activity pins. Run
deactivate/destruction/release outside locks and after plugin stacks return, then
unmap only if unload conformance is enabled. Retain stuck generations and refuse
further reload when budgets saturate. Process shutdown is a separate explicit choice.
This selected initial health policy trades brief write unavailability for deterministic
rollback. The platform does not claim zero write downtime. Read continuity and delayed
old-handle completion are measured independently.
## Failure matrix and recovery
| Failure point | Active ownership / required outcome |
| --- | --- |
| Manifest/ABI/dependency/config rejection | Old generation unchanged; candidate never activated publicly |
| Quiescence timeout | Old/candidate owners retained; resume old admission only after confirming safe ownership; report phase |
| Restore/readiness failure | Dispose and join candidate; restore old mutation gate; no new publication |
| Activation journal written, crash before registry swap | On startup VersionStore reconcile chooses prior healthy release; no in-memory generation survives crash |
| Published during reversible read-only health window, crash | Reconcile uncommitted activation to prior healthy release/checkpoint |
| Health failure before healthy marker | Publish retained old state and roll back activation; no new writes admitted |
| Commit acknowledgement lost | Inspect/reconcile durable healthy event; classify unknown until resolved |
| Healthy marker durable, cleanup fails | Candidate remains committed; retry cleanup; preserve marker and report cleanup error |
| Old plugin activity never ends | Keep mapping/owner; report retained pins; reject reload beyond retention cap |
On first bootstrap with no prior healthy release, failed candidate health leaves
admission closed, joins the candidate and enters diagnostic/not-ready mode. Recovery
never invents a previous release or labels an unvalidated candidate healthy.
Host transaction metadata persists release/transaction identity, activation phase and
checkpoint reference through Update-owned durable facilities. It never introduces a
second independent commit marker that can disagree with VersionStore. Crash recovery
validates checkpoint/release compatibility before opening listeners. Candidate checkpoints
are versioned and bounded; credentials/configuration secrets are not dumped into them by
default. Recovery failure starts diagnostic/not-ready mode without user mutation admission.
## Limits, security and performance
Platform defaults: 64 modules, 256 services, four retained generations/module, one reload
transaction, 4 MiB checkpoint/module, 32 MiB aggregate checkpoint bytes, 64 MiB total
candidate images and 256 MiB owned runtime dynamic budget. All candidate/retired resources
share global permits as well as local module caps. Image bytes, stacks/kernel buffers,
external application state and RSS are reported separately. Control endpoint defaults
to 16 sessions, 64 KiB requests and 32 in-flight operations; reload admission rejects a
second transaction with busy. Phase limits fit a default 30-second total Async deadline;
cleanup retains resources beyond expiry when safety requires it.
Native module compositions are selected; preserve current OpenSSL/libsodium primitives
through Security/Update and existing same-toolchain plugin support. Stable C ABI is an
opt-in separate path. A native plugin is trusted code; signatures establish authorized
origin, not memory isolation. Optional isolated workers use IPC/System with explicit
restart/effect semantics and narrower exposed capabilities. Diagnostics use bounded,
redacted logs/metrics with transaction correlation, not unbounded plugin names as labels.
Measure reload/ready/quiescence/commit p50/p95/p99, read throughput during replacement,
write-unavailable duration, allocations, retained pins, peak RSS/CPU and complete host
build cost under [PERFORMANCE](../PERFORMANCE.md). Test slow callbacks and memory pressure;
do not infer platform latency from an uncontended PluginManager test. No host benchmarks
or deployment checks ran for this plan.
## Ordered implementation backlog
All rows are PLANNED; none authorizes building the host in this documentation task.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| P-RELOADABLE-01 | P0 / current Plugin/Service/Fsm/Update source | Freeze source-based fixture matrix, release/health/rollback state diagram and isolated-consumer baseline | Existing C++ versus NEW C ABI and Update commit boundary are independently testable / astra_planner |
| P-RELOADABLE-02 | P2 / P-RELOADABLE-01; Async/IO/Runtime, Service owning snapshots and Configuration prepare gates | Host-generation composition and lifecycle coordinator with fake modules | Failed prepare publishes nothing; readers acquire one coherent epoch; no user callback under locks / astra_implementer |
| P-RELOADABLE-03 | P3 / P-RELOADABLE-02; Plugin C ABI/activity pins and Fsm checkpoint gates | Future reference host, counter/workflow A/B fixtures and local IPC controls | C++/C fixture migration, old read handle and delayed operation survive replacement without unmap / sol_implementer |
| P-RELOADABLE-04 | P3 / P-RELOADABLE-03; Update durable activation/reconciliation gate | Signed candidate lifecycle, reversible read-only health window, healthy commit and crash recovery | Crash matrix obeys one durable commit marker; precommit health failure loses no admitted writes / astra_implementer |
| P-RELOADABLE-05 | P3 / P-RELOADABLE-04; validation/profile harness | Failure injection, sustained reload/load, retained-resource limits, runbook and package examples | Uncooperative plugin remains pinned; budget saturation rejects reload; measured downtime/RSS reported / astra_implementer |
| P-RELOADABLE-06 | P4 / P-RELOADABLE-05; IPC worker-isolation gate | Optional supervised out-of-process provider composition | Worker crash yields explicit unknown effects and restart policy; no claim of distributed/exactly-once reload / astra_implementer |
## Validation and migration evidence gates
CURRENT ingredient tests can be invoked with
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here. The inherited build/test observations in [VALIDATION](../VALIDATION.md)
are not host acceptance evidence. PROPOSED checks require the future application and
fixtures: continuous readers and operations during A→B, cancelled delayed callbacks,
writer quiescence, failed schema/ABI/readiness, lost commit acknowledgement, killed host
at each matrix boundary, failed journal cleanup after commit, invalid config during
reload, stuck generation pins, endpoint authorization and repeated shutdown under load.
Persist expected counter operation IDs and compare recovery state after every crash.
Proposed build template, only after the NEW target is implemented and configured with
its dependencies: `cmake --build <configured-build-dir> --target void-reloadable-host`.
This is not a current command result. Add isolated package/ABI consumers and documented
manual recovery drills under [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Migration initially wraps existing PluginManager and IModule without changing their
symbols; explicit host staging is opt-in. Legacy plugins lacking async pin/quiescence
evidence remain restart-required with dlclose disabled. Persistent state upgrades keep
old readers/checkpoints until verified; incompatible destructive migrations require a
separate release plan. Preserve [ShortUrl V1](../../short-url.md), exact signed payload
bytes and Update healthy markers throughout. Rollback after committed new writes is
another compatible release/recovery action, never an automatic pointer reversal.
See [MIGRATION](../MIGRATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[DELIVERY](../DELIVERY.md), and [DOCUMENTATION](../DOCUMENTATION.md).