Files
Library/docs/roadmap/subsystems/Runtime.md
T

192 lines
12 KiB
Markdown
Raw Blame History

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