225 lines
19 KiB
Markdown
225 lines
19 KiB
Markdown
# S-RUNTIME-02/03 — Host start, readiness, failed-start cleanup, structured shutdown, joined teardown
|
||
|
||
Task ID: S-RUNTIME-02-03
|
||
Role: opus-implementer
|
||
Status: READY
|
||
|
||
## 1. Context and baseline
|
||
- Wave 11 package steps B3+B4 combined (same files, shared teardown core). Dispatched after M-ASYNC-04
|
||
(ThreadExecutor), S-IO-03 and S-IO-04 (`pump_until`) are committed (gates G3, G5). Repo VoidLibrary,
|
||
branch `feat/roadmap-p2-wave11`. Isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘).
|
||
- Observed source:
|
||
- `include/Void/Runtime/Host.hpp`: inert `Host` (movable, `~Host() = default`, header-only; `HostState`
|
||
has no moved-from value; `started_worker_count()` always 0; `memory_budget()` dereferences
|
||
`owned_budget_` which is null after a move — pre-existing hazard), `EmbeddedResources` (borrowed
|
||
executor/io/clock), `ShutdownReport`, `HostBuilder`. `include/Void/Runtime/Options.hpp`:
|
||
`RuntimeLimits`, `Options` (`file_workers`, `cpu_workers`, `total_timeout`, `drain_grace`,
|
||
`export_flush_timeout`, …), `validate_options` (rejects `total_timeout <= 0`), `RuntimeErrorCode` incl.
|
||
root-added `self_join = 8`, `shutdown_incomplete = 9` (both → `ErrorKind::conflict`).
|
||
`include/Void/Runtime/ResourceGraph.hpp`: `ResourceKind` incl. `service`, `exporter`; `LifecyclePlan`
|
||
with `startup_order`. Existing tests `tests/standalone/Runtime/RuntimeHost.cpp` pin `started_worker_count()
|
||
== 0` after create and inert `add_resource` nodes.
|
||
- Available after upstream steps: `Async::ThreadExecutor` (`create/start/close/join/idle/admitted/stats`,
|
||
`before_worker_start` hook, `is_executor_thread`), `Async::TaskScope` (`stop_on_first_error` option),
|
||
`Async::TimerQueue`; `IO::Driver` (`start_file_workers`, `run_file_work`, `poll_once` → `busy` rules,
|
||
`shutdown(options)` → `DriverShutdownReport`, `shutdown_complete`, `quiescent`, `is_io_worker_thread()`,
|
||
`BackendOptions::before_file_worker_start`, mock `poll_once` ignores `max_wait`), `IO::pump_until`.
|
||
- System signal gate: `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp`; create before
|
||
worker threads, destroy on the creating thread; off-thread destruction closes the fd but skips the mask
|
||
restore, `src/System/SignalWatcher.cpp:27-37`). Runtime has NO System dependency (D-W11-04).
|
||
- Requirements: roadmap rows S-RUNTIME-02 ("Explicit start, readiness and reverse failed-start cleanup |
|
||
Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained") and
|
||
S-RUNTIME-03 ("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"); `docs/roadmap/subsystems/Runtime.md` (updated in W11);
|
||
C-03..C-06, C-09; decisions D-038, D-040, D-042.
|
||
- MANDATORY design sources (precedence R2 > REV1 > PLAN): `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`
|
||
§S-RUNTIME-02 and §S-RUNTIME-03; `W11-PLAN-REV1-OUTPUT.md` F3, F4, F5, F6, F11 and P3 (business scope,
|
||
mock reactor spin, budget accounting test); `W11-CONTRACT-R2.md` N1, N2, N3, P3-1, P3-2, P3-3, P3-7, P3-8.
|
||
|
||
## 2. Objective and deliverables
|
||
1. NEW `include/Void/Runtime/Lifecycle.hpp`: `StartStep`, `SignalGate`, `HostContext`, `Component`,
|
||
`StartOptions`, `ShutdownPhase`.
|
||
2. NEW `include/Void/Runtime/Detail/HostCore.hpp`: all lifecycle state and teardown (Runtime stays header-only).
|
||
3. EDIT `include/Void/Runtime/Host.hpp`: start/readiness/shutdown API, appended `ShutdownReport` fields,
|
||
`HostBuilder::add_component`, moved-from rules.
|
||
4. NEW tests `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals,RuntimeShutdown}.cpp`.
|
||
|
||
## 3. Scope and non-goals
|
||
Out: Runtime→System edge or production signal bridge (S-RUNTIME-04), managed resize/reload, host-managed
|
||
TimerQueue polling (D-W11-14), any IO/Async/System source change, build files.
|
||
|
||
## 4. Files to inspect
|
||
`include/Void/Runtime/*.hpp`, `src/Runtime/module.cmake`, `tests/standalone/Runtime/RuntimeHost.cpp`,
|
||
`tests/package/RuntimeOnly/*`, `tests/package/InstalledComponents.cmake` (RuntimeOnly runs with
|
||
`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`), `include/Void/Async/{ThreadExecutor,TaskScope,Executor,Timer}.hpp`,
|
||
`include/Void/IO/{Driver,Pump,Types}.hpp`, `include/Void/Memory/BudgetResource.hpp`,
|
||
`include/Void/System/SignalWatcher.hpp`, and the design sources in §1.
|
||
|
||
## 5. Write ownership and coordination
|
||
Write scope: `include/Void/Runtime/Host.hpp`, `include/Void/Runtime/Lifecycle.hpp` (NEW),
|
||
`include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/RuntimeStart.cpp` (NEW),
|
||
`tests/standalone/Runtime/RuntimeSignals.cpp` (NEW), `tests/standalone/Runtime/RuntimeShutdown.cpp` (NEW),
|
||
`tests/package/RuntimeOnly/main.cpp` (optional smoke only).
|
||
Forbidden: every other path, including `Options.hpp`, `ResourceGraph.hpp`, IO/Async/System files and
|
||
`RuntimeHost.cpp` (stop and report if a change there is needed, P3-8). No git operations except the
|
||
authorized fast-forward.
|
||
|
||
## 6. Implementation or investigation approach
|
||
MANDATORY start (S-RUNTIME-02):
|
||
- `start(StartOptions)` once: `constructed → starting → running | failed_start`; records the owner thread.
|
||
Steps in order, each pushing a cleanup action: (1) `signal_gate->install()` (track `gate_installed_`;
|
||
borrowed gate must outlive the Host); (2) memory budget; (3) owned `ThreadExecutor{workers = cpu_workers,
|
||
max_admitted = limits.max_cpu_tasks}` create + `start()` (forward `before_thread_start(cpu_executor, i)`
|
||
into `before_worker_start`); (4) `IO::Driver::create` with `io.limits.file_workers = Options::file_workers`
|
||
(Runtime is authoritative) and the memory budget as its pmr resource; (5) `start_file_workers()` (forward
|
||
hook into `BackendOptions::before_file_worker_start`); (6) Runtime-owned reactor `std::thread` (catch
|
||
`std::system_error`; `before_thread_start(reactor, 0)` hook; thread-local `tl_reactor` marker) looping
|
||
`poll_once(5ms)`; on `busy`, or on a mock backend / a turn that did no work, wait up to 5 ms stop-aware
|
||
(never spin); exits on reactor stop or `shutdown_complete()`; (7) components in `plan_.startup_order`, `start`
|
||
called outside Host locks; (8) readiness: executor `try_post` probe plus one reactor turn within
|
||
`readiness_timeout` → `running`, `is_ready() == true`. `before_step(step)` hook errors inject failure
|
||
between steps; thread hooks inject failure within threaded steps.
|
||
- Failure at any point: pop cleanups in reverse on the starting thread, bounded by `cleanup_timeout`
|
||
(injected clock); state `failed_start`; return the error wrapped with context preserving the root
|
||
`Status`. If cleanup does not finish in budget, resources are retained and the next `shutdown_blocking`
|
||
or `~HostCore` continues. No thread or descriptor may remain after a completed cleanup.
|
||
- Embedded mode (`create_embedded`): steps 3–6 are skipped (borrowed executor/driver/clock); no threads.
|
||
- `started_worker_count()` reports real CPU + reactor + file threads.
|
||
- Business work: `spawn(Task, OperationOptions)` into a business `TaskScope` with
|
||
`TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`.
|
||
MANDATORY shutdown (S-RUNTIME-03; REV1 F3/F4 phase list, R2 N1–N3):
|
||
- Phases: 1 closing_admission, 2 draining (drain deadline fixed at first entry = min(total, start +
|
||
drain_grace)), 3 cancelling, 4 joining_business, 5 stopping_components (non-exporters, dependents first),
|
||
6 flushing_exporters (flush deadline fixed at first entry; expiry requests stop on exporter operations,
|
||
sets `export_flush_expired`, keeps waiting), 7 releasing_components (drop every component `shared_ptr`, so
|
||
exporters are destroyed here), 8 stopping_io (request reactor stop and JOIN the reactor, then
|
||
`driver->shutdown(remaining)` from the shutdown thread; retain if incomplete), 9 stopping_workers (wait for
|
||
`ThreadExecutor::idle()` within budget, then `join()`), 10 releasing (budgets, descriptors; signal gate
|
||
`uninstall(on_owner_thread)` at most once), 11 stopped. Assert ordering
|
||
`exporter_stopped < exporter_destroyed < executor_joined`.
|
||
- Every entry point (`shutdown_blocking`, `poll_shutdown`, `shutdown_pumping`) computes its own budget
|
||
`min(options.deadline, deadline_after(clock, total_timeout))`. In waiting phases 2, 4, 5, 6, 8, 9 a
|
||
call-deadline expiry stops the sequence and returns `complete=false`, state `shutdown_incomplete`, phase
|
||
recorded, all resources retained; the next call resumes at that phase. Drain expiry moves on to phase 3 and
|
||
sets `drain_grace_expired`.
|
||
- Component `stop()` tasks are launched through `post_completion` (never normal-lane admission), so a full
|
||
queue cannot block them. Concurrent callers get the same final report; exactly one teardown.
|
||
- `shutdown_blocking` on a Runtime worker/reactor/IO worker → `RuntimeErrorCode::self_join`;
|
||
`shutdown_blocking` when the executor has no background workers (embedded) → `invalid_argument`;
|
||
`shutdown_pumping` in managed mode → `invalid_argument`. Off-owner shutdown completes every phase except
|
||
the gate release (`owner_release_pending = true`); a later owner-thread call or `~HostCore` calls
|
||
`uninstall(this_thread == owner)`.
|
||
- Embedded `shutdown_pumping(manual, options, timers)` drains business scope and components using
|
||
`IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`; borrowed
|
||
executor, driver, clock and memory are NEVER shut down, closed or joined.
|
||
- `~HostCore` (teardown lives here so default move-assign is safe): managed — loop shutdown with no
|
||
deadline cap until `complete` ("destruction blocks until complete"); embedded with a borrowed
|
||
`ManualExecutor` (dynamic_cast) — loop `shutdown_pumping(manual)` until complete; embedded otherwise and
|
||
incomplete — stderr diagnostic + `std::terminate`. On an OWNED Runtime worker/reactor/IO worker thread —
|
||
stderr diagnostic + `std::terminate` (detection via owned executor `is_executor_thread()`, `tl_reactor`,
|
||
`IO::is_io_worker_thread()`; never for a borrowed executor).
|
||
- Moved-from Host: `valid() == false`; `state()` returns `stopped`; `is_running/is_ready` false;
|
||
`started_worker_count()` 0; `executor()/io()` nullptr; `owner_thread()/last_shutdown_report()` nullopt;
|
||
`start/shutdown_*/poll_shutdown` → `invalid_state`; `spawn` → `AdmissionError::stopped`; reference accessors
|
||
(`options`, `lifecycle_plan`, `embedded_resources`, `memory_budget`) have precondition `valid()` (document,
|
||
assert in debug). `HostCore` holds no pointers into `Host` members. Owned BudgetResource/executor/driver live
|
||
until `~HostCore`.
|
||
|
||
## 7. Interfaces and data contracts
|
||
```cpp
|
||
namespace Void::Runtime {
|
||
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
|
||
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
|
||
stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped };
|
||
class SignalGate { public: virtual ~SignalGate() = default;
|
||
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
|
||
virtual void uninstall(bool on_owner_thread) noexcept = 0; };
|
||
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
|
||
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
|
||
class Component { public: virtual ~Component() = default;
|
||
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0;
|
||
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
|
||
struct StartOptions { SignalGate* signal_gate{nullptr};
|
||
std::function<Void::Result::Result<void>(StartStep)> before_step{};
|
||
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)> before_thread_start{};
|
||
std::function<void(ShutdownPhase)> on_phase{};
|
||
std::chrono::milliseconds readiness_timeout{5000}; std::chrono::milliseconds cleanup_timeout{5000}; };
|
||
}
|
||
// Host (EDIT): [[nodiscard]] Result<void> start(StartOptions = {}); bool is_ready() const noexcept; bool valid() const noexcept;
|
||
// Async::Executor* executor() noexcept; IO::Driver* io() noexcept; std::optional<std::thread::id> owner_thread() const noexcept;
|
||
// std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
|
||
// void begin_shutdown() noexcept; Result<ShutdownReport> poll_shutdown(Async::OperationOptions = {});
|
||
// Result<ShutdownReport> shutdown_blocking(Async::OperationOptions = {});
|
||
// Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr);
|
||
// std::optional<ShutdownReport> last_shutdown_report() const; std::size_t cpu_admitted() const noexcept;
|
||
// lifecycle state in std::unique_ptr<detail::HostCore>.
|
||
// ShutdownReport (EXISTING fields kept) + appended: ShutdownPhase phase; std::size_t pending_business_tasks,
|
||
// pending_cpu_admitted, pending_io_operations, retained_buffer_bytes; bool drain_grace_expired,
|
||
// export_flush_expired, owner_release_pending; bool complete (if not already present).
|
||
// HostBuilder (EDIT): [[nodiscard]] Result<void> add_component(std::string id, ResourceKind,
|
||
// std::shared_ptr<Component>, std::vector<std::string> deps = {}, bool critical = true);
|
||
```
|
||
Use existing `Result`/`make_runtime_error` spellings. Existing 1.x Host/HostBuilder API and `RuntimeHost` tests unchanged.
|
||
|
||
## 8. Dependencies and integration
|
||
Upstream: M-ASYNC-04, S-IO-03, S-IO-04, M-TIME-03 (all in your base). Downstream: P-NETWORKED-02 /
|
||
P-RELOADABLE-02 (later waves). Root integrates and commits.
|
||
|
||
## 9. Edge cases security and performance
|
||
Failure at every step and inside threaded steps (index 0 and last); thread-creation exceptions; pending
|
||
SIGUSR2 must be drained before uninstall (otherwise default action kills VoidTests); `/proc/self/task` and
|
||
`/proc/self/fd` deltas measured within a single test, Host telemetry primary; ManualClock + blocking waits
|
||
re-read the injected clock in short slices; deterministic tests use `poll_shutdown` or expired deadlines
|
||
rather than sleeps; full normal queue during shutdown; exporter waiting on a held mock read; RuntimeOnly
|
||
consumer has Threads lookup disabled (libc with integrated pthreads assumed, as IO already does).
|
||
|
||
## 10. Acceptance criteria
|
||
- `RuntimeStart.cpp`: `runtime_start_spawns_workers_only_on_start_ready`, `runtime_start_twice_invalid_state`,
|
||
`runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds`, `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup`,
|
||
`runtime_failed_start_component_cleanup_timeout_retains_then_completes`, `runtime_component_start_failure_unwinds_reverse`,
|
||
`runtime_signal_gate_before_threads_uninstall_on_owner`, `runtime_signal_gate_uninstalled_at_most_once`,
|
||
`runtime_embedded_start_no_threads`, `runtime_move_after_start_keeps_resources_valid`, `runtime_moved_from_host_safe_defaults`.
|
||
- `RuntimeSignals.cpp` (includes `Void/System/SignalWatcher.hpp`; silently skipped without System; test-local
|
||
SignalGate adapter over `Process::SignalWatcher`, SIGUSR2): `runtime_system_gate_mask_inherited_by_workers`,
|
||
`runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`,
|
||
`runtime_signal_during_start_stays_pending_and_is_drained`, `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`
|
||
(restores the owner mask and drains SIGUSR2 before finishing).
|
||
- `RuntimeShutdown.cpp`: `runtime_shutdown_concurrent_callers_single_teardown_tsan`,
|
||
`runtime_shutdown_full_normal_queue_still_delivers_completion`,
|
||
`runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (ordering log),
|
||
`runtime_shutdown_stalled_business_task_incomplete_retains`, `runtime_shutdown_child_spawn_during_close_rejected`,
|
||
`runtime_shutdown_budget_expired_caller_deadline_incomplete_then_resumes`,
|
||
`runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`,
|
||
`runtime_shutdown_on_worker_self_join`, `runtime_shutdown_non_owner_defers_gate_release`,
|
||
`runtime_shutdown_embedded_pumping`, `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`,
|
||
`runtime_embedded_shutdown_blocking_invalid_argument`, `runtime_managed_shutdown_pumping_invalid_argument`,
|
||
`runtime_destructor_joins_after_start`, `runtime_destructor_blocks_until_complete_after_incomplete_shutdown`.
|
||
- Existing `RuntimeHost` tests pass; `RuntimeOnly` consumer passes (ctest); TSan 0 races; ASan+UBSan 0 errors;
|
||
`-Werror` syntax checks clean. Keep each test well under 1,000 assertions (X-QA-02) and each test declaration
|
||
on ONE line (X-QA-03).
|
||
|
||
## 11. Verification commands and evidence
|
||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in the output.
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt --parallel 8 && /tmp/void-w11-rt/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt --output-on-failure --timeout 180'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt-nosys --parallel 8 && /tmp/void-w11-rt-nosys/tests/VoidTests --filter "^(RuntimeStart|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt-nosys --output-on-failure --timeout 180'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-rt-tsan --parallel 8 && /tmp/void-w11-rt-tsan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown)\."'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-rt-asan --parallel 8 && /tmp/void-w11-rt-asan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\."'
|
||
dev cpp-gcc -c bash -lc 'for f in RuntimeStart RuntimeSignals RuntimeShutdown; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Runtime/$f.cpp || exit 1; done'
|
||
```
|
||
|
||
## 12. Constraints and stop conditions
|
||
No edits outside write scope; no weakened assertions; no Runtime→System edge; no Threads link. Stop and report
|
||
BLOCKED if an IO/Async primitive misbehaves (give a reproducer), a forbidden file must change, RuntimeHost tests
|
||
must change, or two repair attempts at one check fail.
|
||
|
||
## 13. Authorization and decisions
|
||
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only; no
|
||
commits, pushes or other side effects.
|
||
|
||
## 14. Return format
|
||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion;
|
||
commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.
|