Files
Library/docs/roadmap/modules/System.md

11 KiB
Raw Permalink Blame History

System facilities and process lifecycle plan

Status: PLANNED feature work; no system implementation changes. Source baseline: f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24. Requirements R-003, R-006, R-009 and R-014 apply. Follow architecture C-02–C-06 and C-13.

Existing source baseline

Process.hpp exposes Void::Process::run, run_streaming, shell, reexec, Output, and line callbacks. Nonzero child exits are successful Results with an exit code. Process.cpp uses POSIX pipes/fork/execvp, writes stdin before draining outputs, polls stdout/stderr, sends SIGTERM on timeout, and then waits synchronously. The source derives a 30-second poll deadline when the supplied timeout is zero, despite the header's no-limit wording. It does not establish a bounded termination guarantee for a child ignoring SIGTERM. These are characterization and correction targets, not intentional NEW semantics.

FileWatcher.hpp and FileWatcher.cpp provide Void::FileSystem::FileWatcher, a polling worker with default 500 ms polls and two stable polls before notification. It compares existence/mtime/size, and invokes copied callbacks outside the watch map lock. Stability of metadata is not proof of complete content or authenticity. Unwatch cannot revoke a copied callback already admitted.

SignalWatcher.hpp documents Void::Process::SignalWatcher::create, blocked signal-mask inheritance before worker startup, synchronous wait/poll, and destruction on its creating thread. SignalWatcher.cpp is the platform implementation. Path.hpp, Query.hpp, TempFile.hpp, and TempDir.hpp supply filesystem helpers and RAII temporary resources. atomic_write stages to a fixed sibling .tmp then renames; it does not fsync and must not be used as a durable-commit primitive based on its name. Metrics.hpp supplies Void::SystemInfo Linux memory/process CPU samples, with unavailable/zero fallback on other platforms. module.cmake declares Functional, LogState and Threads.

Existing fixtures cover processes, streaming, watching, signals, and paths. Graph checks covered these source paths; partial Process/SignalWatcher/FileWatcher declarations were directly read.

NEW process and filesystem contracts

Design sketch; Result follows Functional and OperationOptions belongs to Async:

namespace Void::Process {                       // NEW additions
struct SpawnOptions {
    std::filesystem::path executable;
    std::vector<std::string> arguments;
    std::filesystem::path working_directory;
    EnvironmentPolicy environment;             // explicit inherit or allowlist
    CaptureLimits capture;                      // bytes, line bytes, overflow policy
};
Result<Child> spawn(SpawnOptions);
Coro::Task<Result<ExitStatus>> wait(Child&, Async::OperationOptions);
Coro::Task<Result<Output>> communicate(Child&, InputSource&, Async::OperationOptions);
}
namespace Void::FileSystem {                    // NEW additions
Result<void> replace_file(path, bytes, ReplaceOptions); // atomic visibility vs durable
// watch registration -> owning WatchSubscription with close_and_join(options).
}

Child owns PID/process identity, descriptors and reaping responsibility. Move transfers all ownership. communicate concurrently writes stdin and reads both outputs through IO; EOF closes each direction independently, preventing pipe-buffer deadlock. Output retention and line streaming are separate policies: streaming need not retain all bytes. Default cap is 1 MiB each for stdout/stderr, 64 KiB per line, 4 MiB buffered input; overflow terminates the child and reports output_limit with truncated diagnostics. An explicit discard-after-limit mode continues draining and marks truncation.

Default active children per manager: 64; pending spawn requests: 128; admission rejects on overload. Argument/environment input totals are capped at 256 KiB and checked again against platform limits. Use argv execution by default. Shell interpretation is an explicit adapter; never concatenate untrusted arguments. Exec failures use an error pipe and retain errno, distinct from a program intentionally exiting 127. Environment snapshots are immutable per spawn and diagnostics redact marked secrets.

Timeout/stop first closes admission/input, requests SIGTERM for the owned process group, waits a configurable 2-second grace, then sends SIGKILL and reaps. Report cancelled or timed_out plus exit evidence; termination cannot undo external effects. Platform/kernel stalls can prevent prompt reaping, so a timeout does not release Child ownership. A manager retains outstanding reapers through shutdown. Descendants outside the process group are outside this guarantee; report that boundary. reexec remains an explicit application lifecycle action with open-descriptor policy and an error on exec failure.

System's synchronous primitives remain independently usable. NEW async process/watch adapters depend on Async and IO in an optional adapter target; the base System package does not depend on managed Runtime or force Async into small filesystem consumers. Final adapter target names are packaging work under BUILD-AND-DISTRIBUTION.

Watching, persistence and capability behavior

Retain polling as the portable initial backend. NEW injected scheduling uses Time's clock and one shared watcher service instead of a thread per file. Default 1,024 paths, 256 queued notifications, one coalesced pending notification per path. Overflow emits a rescan-required marker; consumers reread/validate rather than infer a missing history. Path disappearance, atomic rename, symlink change and permission denial are distinct events. Default follows the configured path with no recursive traversal; symlink and directory-root restrictions are explicit options. Later Linux inotify is a capability adapter with the same rescan/overflow contract, gated after polling conformance.

Subscription state owns copied callback captures until close-and-join completes. User callbacks run outside locks and on the configured executor. Callback exceptions reach an error sink; they do not kill the watcher thread. Self-close requests stop but self-join is rejected. A callback never performs configuration publication itself; it submits a candidate to Configuration.

replace_file uses an exclusively created unpredictable sibling temporary file, bounded write loops, checked close/errors and rename on the same filesystem. Atomic visibility is distinct from durable replacement; durable mode syncs staged content, renames, then syncs the containing directory before acknowledgement. Failure after rename can mean visible-but-durability-unknown; return a phase-aware error and do not blindly overwrite on retry. Storage and Update retain their own commit protocols. Directory listing/read helpers gain explicit entry/byte limits and cancellation in the optional adapter. RAII temp factories enforce restrictive permissions and never recursively remove a directory they did not create and retain ownership of.

Capability queries return supported/unsupported/unavailable with diagnostic context. Metrics distinguish a real zero from unavailable sampling in NEW APIs. Native POSIX and standard filesystem facilities are initial choices; no external process or watcher library is required. Cross-platform backends are separate later conformance work.

Ordered implementation backlog

All feature rows are PLANNED.

ID Phase / depends on Intended scope Acceptance / recommended role
M-SYSTEM-01 P0 / current source Characterize zero timeout, SIGTERM resistance, full-duplex pipe and rename/fsync behavior; portable child fixtures Existing semantics recorded; tests use built fixture paths rather than /bin assumptions / sol_implementer
M-SYSTEM-02 P1 / M-SYSTEM-01; Functional errors Owned descriptors/Child, explicit spawn options, error pipe, bounded capture Exec failure distinct from exit 127; all early failures close/reap; caps enforced / astra_implementer
M-SYSTEM-03 P2 / M-SYSTEM-02; Async and IO foundation gates Full-duplex async communicate, stop escalation, joined process manager Multi-pipe pressure completes; timeout/child-exit race delivers once and reaps / astra_implementer
M-SYSTEM-04 P2 / M-SYSTEM-01; Async/Time injection gates Shared polling watcher, owned subscriptions, coalescing/rescan and callback errors Unwatch+join drains callbacks; replacement/deletion/overflow deterministic / sol_implementer
M-SYSTEM-05 P2 / M-SYSTEM-02 Explicit atomic/durable file replacement, safe temp factories, query bounds Fault-injected write/sync/rename errors report the actual phase and clean only owned temporaries / astra_implementer
M-SYSTEM-06 P3 / M-SYSTEM-03, M-SYSTEM-04, M-SYSTEM-05 Capability matrix, optional inotify, metrics validity, installed adapter checks Polling/backend conformance identical; unsupported platforms fail explicitly / sol_implementer

Validation, performance and migration

CURRENT aggregate command is ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60; not rerun here. The inherited two failures depend on absent /bin/echo and /bin/cat, not evidence that the proposed process contract passes. PROPOSED fixture executables must exercise ignored SIGTERM, delayed stdin consumption, simultaneous stdout/stderr, huge unbroken lines, inherited descriptors, child exit during stop and callback throw. Signal tests run in isolated processes to protect the test runner's mask. File tests inject short writes, failed fsync, rename collision, symlink replacement and full queues.

Measure spawn/wait p50/p95/p99, watcher detection latency versus polling interval, throughput, allocations, descriptor/thread counts, peak RSS/CPU and build cost under PERFORMANCE. A large output producer must keep retained bytes within its cap; an idle watcher must not busy-spin. No benchmarks ran for this plan.

Keep current namespaces (Void::Process, Void::FileSystem, Void::SystemInfo). Legacy run/run_streaming adapt into a managed Child only after their timeout/output changes are versioned; no silently reclassified child exits. Replace misleading durable claims on atomic_write through documentation/deprecation and a major-release policy, with new explicit visibility/durability choices. Preserve polling as a rollback backend selected before watching starts. Rollback of an effective file replacement requires application version recovery, not repeating a failed syscall. See MIGRATION, VALIDATION, DEPENDENCIES and DELIVERY.