Files

178 lines
12 KiB
Markdown
Raw Permalink 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.
# IO native operations and backend plan
Status: NEW subsystem, all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
There is no existing IO module in the scoped baseline. Requirements R-003, R-006,
R-009, R-012 and R-014 apply; [architecture](../ARCHITECTURE.md) C-02–C-06 is
authoritative. Proposed source roots are NEW `include/Void/IO`, `src/IO` and
`tests/standalone/IO`; none is created by this plan.
## Source anchors and ownership
[Async Executor](../../../include/Void/Async/Executor.hpp) queues borrowed coroutine
handles today; [Task](../../../include/Void/Async/Task.hpp) owns/destroys its frame.
These require [Async's structured ownership gate](../modules/Async.md) before IO
can expose safe cancellable awaits. [System Process](../../../src/System/Process.cpp)
contains local nonblocking pipe/poll logic, and
[System FileWatcher](../../../src/System/FileWatcher.cpp) has a polling thread.
These are integration anchors, not an existing unified reactor. Current
[executor tests](../../../tests/standalone/Async/Executor.cpp) and
[process-stream tests](../../../tests/standalone/System/ProcessStream.cpp) supply
regressions when optional adapters migrate. These paths were graph-coverage checked
and important ownership/source bodies directly inspected.
IO owns native descriptors, transport readiness, partial transfer, buffers, operation
registration and backend shutdown. [Net](../modules/Net.md) owns DNS/protocol semantics,
connection reuse and TLS; IO never imports Net or Runtime. A portable contract with
an explicitly unsupported platform is preferable to pretending Linux facilities exist
elsewhere. Embedded applications inject their driver/executor/clock; Runtime is only
an optional owner of these same resources.
## NEW API sketch
Illustrative types, not compiling examples or delivered declarations:
```cpp
namespace Void::IO {
struct Transfer { std::size_t bytes; bool eof; };
struct BackendOptions { Limits limits; BackendPreference preference; };
class Driver; // explicit poll/run/stop/join
class ByteStream { // owns shared descriptor state
public:
Coro::Task<Result<Transfer>> read_some(
std::span<std::byte>, Async::OperationOptions = {});
Coro::Task<Result<Transfer>> write_some(
std::span<const std::byte>, Async::OperationOptions = {});
Coro::Task<Result<void>> close_and_join(Async::OperationOptions = {});
};
// read_exact / write_all are bounded composed operations on ByteStream.
// File::read_at / write_at / sync and socket accept/connect use the same options.
}
```
`Result` is Functional's shorthand. The sole OperationOptions type belongs to Async:
`std::stop_token` plus optional absolute steady deadline, with Time's injected clock
bound to the driver. No IO request context duplicates it. A caller holds borrowed spans
stable until the terminal result is delivered, including delayed backend cancellation
acknowledgement. An owning-buffer overload transfers Memory-owned buffer leases for
cross-component use. IO never retains a bare pointer beyond that lease.
Default one active read and one active write per stream; a second same-direction
operation returns busy rather than quietly changing ordering. Read zero indicates
EOF only when requested length is nonzero and the backend reports peer EOF; a zero-length
request succeeds immediately without probing EOF. Half-close affects one direction;
readable buffered data drains before EOF. Write success means accepted by the OS, not
received or durably stored by a peer. Transfer failures retain bytes already transferred
and native error cause. Exact/all compositions preserve progress and the original total
deadline; cancellation cannot undo transferred bytes.
## Initial Linux algorithms
Select native nonblocking sockets with level-triggered epoll, no EPOLLET. Readiness is
a hint; syscalls still handle EAGAIN, EINTR, short transfer, EOF and errors. Level-triggered
semantics avoid requiring every dispatch to drain a descriptor completely; the fairness
budget can yield while data remains ready. This follows the
[Linux epoll interface](https://man7.org/linux/man-pages/man7/epoll.7.html).
One driver thread owns interest updates and descriptor generations. Producers submit
bounded control messages and wake it through eventfd; an embedder may drive bounded
`poll_once` turns instead. Dispatch up to 64 ready descriptors and 64 KiB/direction per
descriptor per turn before yielding. Enable writable interest only with pending writes
to avoid idle busy loops. HUP/ERR still trigger final read/error inspection. Async
completion tickets transfer continuations to the supplied executor outside driver locks.
Registration token is `(slot, generation)`, not just the integer fd. Close invalidates
the slot, removes epoll interest, cancels pending operations and drains their backend
references before descriptor reclamation. Stale ready events cannot target a reused fd.
Stop callbacks enqueue retained control records; they never close a potentially reused
integer directly. Socket connect completion checks the socket error state; accept loops
obey the same fairness/admission budget. Platform-specific endpoint conversion remains
an IO/Net adapter detail until the Net endpoint contract is integrated.
Files initially use a bounded native blocking worker pool. Positional pread/pwrite
avoids shared offset races; default writes/syncs for one file are serialized in admission
order, and reads expose explicit offsets. Worker ownership retains descriptor and buffer
until the syscall returns. Cancelled queued work is removed before execution; an active
blocking syscall may continue. Deadline expiry records intent; result classification and
delivery wait for backend evidence and the end of buffer access. A sync that actually
succeeds returns success even after stop/expiry, so a higher-level commit can use that
evidence. A sync failure preserves its native cause and unknown-durability classification;
stop neither hides it nor turns it into success. Cancelled before execution is distinct
from executed with unknown effects. Do not promise hard shutdown bounds for stalled
filesystems.
## Completion state and shutdown
IO uses Async's operation control block rather than a second completion state machine.
Submission reserves global and per-descriptor quotas, attaches stop/timer registrations,
then exposes a retained backend request. Completion before suspension uses Async's
handshake. Stop/timeout requests cancellation; the operation owner classifies one result
from backend evidence under Async's single-delivery contract. Cancellation before a
syscall starts can return cancelled/timed-out with zero effects. A completed syscall
preserves its successful result or failure and byte/effect count, even after stop intent;
composed exact/all transfers may then stop before their next syscall and report cumulative
progress. Late sync success/failure must remain available to Storage/Update adapters.
Only terminal delivery is arbitrated once; no callback is delivered merely because stop
arrived while backend access or outcome classification was still pending.
Driver shutdown closes admission, cancels queued requests, asks active requests to
stop, drains readiness/control/completion lanes, joins file workers, then releases
descriptors/wake resources. It must keep the executor alive until all completion tickets
drain. `close_and_join` cannot free buffers when its own deadline expires; return an
incomplete-shutdown report through the owning driver and retain work. Blocking joins
are off-driver/off-worker operations; embedded drivers pump until their scopes join.
## Finite defaults and backend gate
Default limits per driver: 4,096 descriptors, 8,192 admitted operations including active
workers and pending completion delivery, 4,096 timers, 16 MiB owned buffer leases,
1,024 ordinary control submissions and four file workers with 256 queued file requests.
One pending read/write per stream counts toward all relevant quotas. Internal completion
slots are reserved per admitted operation. Control stop records coalesce by operation,
so cancellation cannot create an unbounded secondary queue. Reserve before allocation;
return overloaded on exhaustion. Caller-owned buffers count in operation size accounting
but remain the caller's allocation; telemetry separates owned and borrowed bytes.
Initial backend choice is fixed at driver creation. Optional io_uring is P3 work only
after epoll/file-worker conformance and measured need; it uses capability probes and the
same ownership/error model. Unsupported capability falls back before submission when
policy permits. Never retry a possibly effective write/sync on a different backend.
No libuv/Asio dependency is introduced. Existing Boost paths in Net remain until their
own interoperability/migration gate passes. Future non-Linux backends get independent
capability tables and the common operation conformance suite.
## Ordered implementation backlog
All rows are PLANNED; dependency references are capability gates where peer task IDs
are not owned by this document.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-IO-01 | P1 / Async operation ownership and Time clock gates | Portable transfer/error/driver API, buffer leases, descriptor and quota ownership | Mock backend completes/stops in every ordering with exactly one result and no borrowed-buffer escape / astra_implementer |
| S-IO-02 | P1 / S-IO-01 | Level-triggered epoll driver, wake/control path, generation-safe close and stream operations | Fragmentation/EAGAIN/EINTR/HUP/fd reuse and full queues do not lose completion or busy-spin / astra_implementer |
| S-IO-03 | P2 / S-IO-01 | Bounded positional file workers, serialization, sync and active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync success/failure after stop remains authoritative in the sole result / astra_implementer |
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, optional System/Net adapters | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
| S-IO-05 | P3 / S-IO-04; performance harness | Optional io_uring capability/backend gate and portability conformance specification | Same tests pass; denied/unsupported capability falls back only before submission; profile evidence justifies enablement / astra_implementer |
## Validation, measurements and migration
CURRENT source fixtures run through
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun here, and there are no IO tests/targets today. PROPOSED implementation adds
socketpair/loopback fixtures with tiny buffers, half-close, reset during write, no-data
idle soak, stop while completion queue is full, fd reuse with stale events, immediate
completion during await registration, and stalled file-worker tests with manually
released gates. Inject stop before sync execution and during it, then release success or
failure; verify the distinct results, single delivery and retained descriptor ownership.
Use injected clocks, syscall shims and isolated filesystem fixtures;
race/lifetime sanitizer checks are specified in [VALIDATION](../VALIDATION.md).
Measure operation p50/p95/p99, loopback/file throughput, wake/syscall counts, allocations,
peak owned bytes/RSS/CPU, descriptor leaks and build cost under latency/throughput/footprint
profiles in [PERFORMANCE](../PERFORMANCE.md). No backend benchmark ran here. Existing
System and Boost Net implementations migrate through explicit adapters with equivalent
partial-transfer/error tests. A backend rollback requires draining the old driver and
creating a new one; accepted operations are never replayed. See
[MIGRATION](../MIGRATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[Runtime](Runtime.md), [IPC](IPC.md), and [DELIVERY](../DELIVERY.md).