- Audit roadmap vs TASKS (D-033); scope Wave 11 to M-FUNCTIONAL-03, M-TIME-03,
M-ASYNC-04/05, S-IO-03/04, S-RUNTIME-02/03 (D-034..D-036)
- Schedule VoidForge upstream requests after Wave 11 (D-037)
- Persist planner output, PREFLIGHT findings and contract addendum (D-038)
- Add AsyncErrorCode::closed, IoErrorCode::sync_failed,
RuntimeErrorCode::{self_join, shutdown_incomplete}
- Update Functional/IO/Runtime area plans and MIGRATION per C-13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 KiB
Runtime explicit managed composition plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24.
Requirements R-005, R-009, R-010, R-012 and R-014 apply.
Architecture C-01–C-05, C-09 and C-11 controls layering.
NEW proposed roots are include/Void/Runtime, src/Runtime and
tests/standalone/Runtime; no host or runtime is implemented in this planning package.
Existing ingredients and boundary
There is no current managed Runtime module. Existing Async ThreadPool, EventBus, and System FileWatcher create their own workers in their respective owning forms. Fsm Engine can own a worker or be pumped. ServiceRegistry has lifecycle callbacks but no managed execution composition. These source paths were coverage-checked and key behavior read directly; FileWatcher's partial declaration was directly inspected. Existing executor, watcher, and orchestrator tests are integration anchors, not Runtime tests.
Runtime depends on Async, IO, Time and Memory facilities.
Async/IO/Time/Memory never depend on Runtime. Optional adapters compose Service,
Configuration, Plugin, Scheduler, Log and Observability without making them mandatory
runtime dependencies for small consumers. Foundation constructors do not acquire
threads, sockets or a process-wide runtime. No singleton Runtime::current() fallback
is part of this design.
NEW public shape and embedded composition
Illustrative, not available declarations:
namespace Void::Runtime {
struct Options {
std::uint32_t cpu_workers;
std::uint32_t file_workers;
RuntimeLimits limits;
ShutdownPolicy shutdown;
};
class Host { // owns managed resources
public:
static Result<Host> create(Options); // validates, starts no workers
Result<void> start(StartOptions); // explicit startup transaction
Async::Executor* executor();
IO::Driver* io();
Result<ShutdownReport> shutdown_blocking(Async::OperationOptions);
Result<ShutdownReport> poll_shutdown(); // non-blocking step
Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions);
// No awaited shutdown Task on the host's own executor: it would self-join (D-038).
};
// NEW EmbeddedResources borrows executor, IO driver, Time clock and Memory budget.
}
Runtime Options are resource policy, not a duplicate operation context. Every cancellable operation takes Async::OperationOptions. Time owns injected monotonic/civil clocks; Memory owns allocation/budget contracts; Observability supplies optional lightweight hooks. Runtime stores owners for managed resources and validated references for borrowed ones, with no implicit lifetime extension of arbitrary external objects.
An embedded application constructs Async scopes and an IO driver directly, then passes them to module factories. It may use NEW EmbeddedResources convenience views, but modules consume their own low-level ports, not a mandatory Runtime header. A managed Host exposes the same ports. A test host uses fake Time, ManualExecutor and a mock IO backend. Normal constructors remain inert; start is explicit and errors return before publication.
Startup algorithm
Use a lifecycle graph of explicit resources, with required/optional dependencies and
deterministic topological ordering. Default core order: validate limits/capabilities →
install the injected SignalGate on the designated owner thread (Runtime has no System
dependency; a System-backed adapter is optional) → allocate budgets and queues →
start CPU executor → start IO driver/file workers → start optional service/admission
adapters → report ready. SignalWatcher is created before worker threads as required by
its contract, and is destroyed on
the same creating thread after workers join; off-owner teardown calls uninstall(false),
which closes the gate's descriptor but cannot restore the owner's mask.
Each start step returns a retained cleanup action. A failed step aborts its partial resources and unwinds previously successful starts in reverse dependency order. Callbacks and service readiness checks execute outside lifecycle graph locks; a serialized lifecycle strand prevents concurrent start/shutdown transactions. Start is valid once per Host instance; retries after failure use a fresh Host after cleanup, avoiding partially restarted resources. Host ready means all required admissions can work, not merely that worker threads were created.
Configuration integration prepares a complete immutable resource/settings generation before Host publication. A failed reload keeps current resources. Increasing pool size can be prepared; shrinking retires workers after their admitted tasks drain. Changes that cannot be staged reversibly require a controlled restart. Runtime never applies half of a Configuration transaction.
Shutdown and failure ownership
States: constructed → starting → running → stopping_admission → draining → joining → stopped; failed_start and shutdown_incomplete retain cleanup ownership. Shutdown is idempotent; callers join one retained result rather than issue competing stop paths.
- Close external admissions/listeners/schedule admission and freeze new lifecycle publication. Existing accepted calls retain their resources and generation pins.
- Ask high-level applications/services to drain for a default 5-second grace within the caller's total steady deadline. Observe dependency order: stop dependents first.
- Request stop on remaining application/module work scopes and their timers, subscriptions and queued IO. Shutdown-owned cleanup/export scopes are separate and retain bounded internal admission. Continue driving IO/executor completions so cancellation can finish; do not stop workers needed to join their children.
- Join drained business scopes and their IO/plugin activities. Retain reactor, CPU/file workers, clock, callbacks and provider generations needed by final cleanup/export.
- Stop remaining telemetry producers, collect final metrics, then flush, close and join observation/logging adapters in dependency order. A flush deadline reports unsent/lost data and requests cooperative cancellation, but all admitted backend activity must still quiesce. Expiry of the total shutdown budget returns shutdown_incomplete with exporter owners and their execution resources retained; a later join continues them.
- After cleanup/export callbacks and backend references retire, drop component/exporter references, then stop owned IO, the reactor and CPU/file workers, and release budgets, descriptors and the signal gate in reverse creation order. Borrowed executor, driver, clock and memory are never shut down or joined by the Host. Observation failure cannot suppress cleanup or convert a failed operation into success. A timed-out flush is not evidence that its resources are releasable.
Default total shutdown observation budget is 30 seconds, shortened by caller options.
Each shutdown call observes min(caller deadline, now + total_timeout) for remaining work;
drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete
phase stops the sequence and the next call resumes there.
Expiry produces shutdown_incomplete containing pending owner IDs/counts and phase;
the Host remains in joining with resources retained. It can be waited again or the
application can choose explicit process termination. There is no forced thread kill,
buffer release or dlclose. Borrowed resources must outlive final cleanup, not merely
the first timed-out shutdown call. Destruction blocks to join only off Runtime threads;
destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error
that terminates after a diagnostic. Process-level
hard-stop policy belongs to the application, not a hidden destructor timeout.
Uncaught task exceptions reach explicit scope/error sinks. Default failure policy requests stop for the owning component and marks it not-ready; it does not terminate all unrelated components unless the host's declared critical-resource policy requires that. Core driver failure closes admission and starts supervised shutdown. Error sinks cannot recursively allocate unbounded work to report overload.
Default accounting and backend rationale
Use native standard threads plus the selected IO epoll/file-worker backend. Default one reactor, CPU workers = min(8, max(1, hardware_concurrency())), four file workers, 4,096 admitted CPU tasks, 8,192 IO operations, 256 queued file requests, 1,024 timers, 256 optional services and 256 MiB owned dynamic resource budget. Zero workers/limits are invalid unless a documented embedded mode supplies the corresponding resource.
Global budget permits are shared by submodules: adding their local caps never creates permission to exceed the host cap. Count running work, queued completions, prepared reload generations and retained buffers. Thread stacks, kernel buffers and borrowed memory are reported separately from allocator-controlled bytes; RSS is not falsely claimed to be capped by the 256 MiB allocator budget. Reserve terminal/control capacity when admitting work. Rejection is explicit; optional async waiting has bounded waiters and uses the same stop/deadline. Native affinity/priority tuning is P3 opt-in after measurements, not required for correctness.
Ordered implementation backlog
Every row is PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|---|---|---|---|
| S-RUNTIME-01 | P1 / Async ownership, IO driver, Time/Memory ports | Inert Host options, borrowed/owned resource graph, dependency validation | No constructor starts workers; invalid bounds/cycles fail before external admission / sol_implementer |
| S-RUNTIME-02 | P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port) | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
| S-RUNTIME-03 | P2 / S-RUNTIME-02, S-IO-04 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
| S-RUNTIME-04 | P3 / S-RUNTIME-03; Service/Configuration transaction gates | Optional managed adapters, transactional resize/reload and embedded examples | Same workload runs embedded/managed; failed resource prepare keeps active generation / sol_implementer |
| S-RUNTIME-05 | P3 / S-RUNTIME-04; profile harness | Latency/throughput/footprint presets, inspection and tuning gates | Limits remain invariant per preset; measured p99/RSS/build cost reported with environment / astra_implementer |
Validation and migration
CURRENT aggregate source-regression command:
ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60;
not rerun here; no Runtime executable/target is present. PROPOSED tests require NEW
Host: start failure at each node, stop during startup, concurrent repeated shutdown,
task creating a child while admission closes, file syscall held past deadline, full
completion queue, borrowed driver teardown ordering, observer throw, signal arrival
during start, and held plugin pin at shutdown. Hold a remote export in flight while
business admission closes, expire its flush and total shutdown deadlines, and assert
shutdown_incomplete retains IO/workers/buffers. Release the backend, join again and
assert exporter destruction precedes executor teardown, with no new business admission.
Run tests with isolated process signals
and deterministic clocks; avoid real sleeps for lifecycle ordering assertions.
Measure start/ready/shutdown p50/p95/p99, task and IO throughput, allocations, retained owners, peak RSS/CPU/thread count and build cost using PERFORMANCE. The managed preset is accepted only after embedded equivalence and no implicit-thread consumer checks pass under VALIDATION. No measurements ran here.
Migration is opt-in: existing thread-owning components keep versioned constructors; new factories accept explicit ports. A future reference host in NetworkedApplications or ReloadableApplications calls create/start, not a global bootstrap function. Rollback drains the managed host before restoring legacy ownership; two owners must never drive the same executor/descriptor. See MIGRATION, DEPENDENCIES, and DELIVERY.