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

179 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.
# IPC framed local transport and resource isolation plan
Status: NEW subsystem; all feature work PLANNED. Baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
No existing IPC source module is assumed. NEW proposed roots are `include/Void/IPC`,
`src/IPC` and `tests/standalone/IPC`. Requirements R-003, R-006, R-009 and R-014
apply; [architecture](../ARCHITECTURE.md) C-02–C-06, C-09 and C-13 governs the design.
## Existing anchors and target boundary
[System Process](../../../include/Void/System/Process.hpp) and
[Process.cpp](../../../src/System/Process.cpp) already use subprocess pipes, output
capture and synchronous streaming callbacks. They do not provide framed request/reply
IPC, peer authorization or negotiated quotas. [Async Channel](../../../include/Void/Async/Channel.hpp)
is in-process blocking synchronization, not a process channel. These paths and their
[streaming](../../../tests/standalone/System/ProcessStream.cpp)/
[channel](../../../tests/standalone/Async/Channel.cpp) tests were coverage-checked;
the relevant Process partial declarations were directly read.
IPC owns local framing, handshake, peer policy and bounded request correlation over
[IO](IO.md) streams. [Binary](../modules/Binary.md) owns encoding primitives;
[Data](../modules/Data.md) owns optional payload schemas. [RPC](RPC.md) may compose
IPC as a transport; IPC never imports RPC, Runtime, Plugin or distributed coordination.
Process supervision stays System/Runtime-owned. Using IPC for plugin isolation requires
an application protocol and restart policy; it is not an ABI-compatible dlopen adapter.
## NEW API sketch and Linux transport choice
Illustrative additions, not compiling examples:
```cpp
namespace Void::IPC {
struct Limits { std::uint32_t frame_bytes, inflight_requests, queued_frames; };
struct PeerPolicy { AllowedIdentity identity; EndpointPermissions endpoint; };
class Session {
public:
Coro::Task<Result<Message>> request(
OwnedBytes payload, Async::OperationOptions = {});
Coro::Task<Result<void>> send(OwnedBytes, Async::OperationOptions = {});
Coro::Task<Result<void>> close_and_join(Async::OperationOptions = {});
};
// listen_local(path, PeerPolicy, Limits, injected_io) -> Result<Listener>;
// adopt_pipe_pair(owned_descriptors, trusted_child_identity, Limits) -> Result<Session>;
}
```
Use pathname Unix-domain SOCK_STREAM sockets on Linux first, with IO's nonblocking
level-triggered epoll backend. A stream does not preserve message boundaries; framing
is mandatory. The listener applies restrictive socket/directory permissions and
checks kernel-reported peer credentials against explicit policy. Linux credential and
pathname behavior is described by [unix(7)](https://man7.org/linux/man-pages/man7/unix.7.html).
Credentials identify the local OS peer; the host still authorizes operations. A PID
alone is not a durable identity or permission to access every service.
Default policy allows only the configured user ID checked against reported peer
credentials, not every local account.
Create endpoints beneath an application-owned directory with mode 0700 and socket mode
0600. Refuse an unexpected existing path/symlink; never unlink an arbitrary caller path.
Stale endpoint cleanup requires verified ownership and failed connection under a serialized
listener startup lock. Abstract namespace sockets are an explicit later option because
their access-control behavior differs. Anonymous pipe-pair transport is initially limited
to descriptors created for a supervised child; it inherits the same framing and quotas
without pretending it has socket peer credentials. No shared-memory transport in P2.
## Wire format and handshake
NEW V1 framing uses a fixed 24-byte header, encoded field-by-field in big-endian order;
never send a native C++ struct or assume its packing:
| Offset / bytes | Field | Rule |
| --- | --- | --- |
| 0 / 4 | Magic | ASCII `VDIP` |
| 4 / 2 | Version | 1; reject unsupported major before payload allocation |
| 6 / 2 | Flags/type | Low byte: hello=1, request=2, response=3, error=4, cancel=5, one-way=6, goaway=7; high byte zero |
| 8 / 4 | Payload length | Excludes header; capped by negotiated limit |
| 12 / 4 | Stream ID | Must be zero in V1; streaming/multiplexed flow control is a later versioned capability |
| 16 / 8 | Request ID | Nonzero for request/response/cancel; zero for connection control/one-way |
Incremental parser states are header → validate → reserve bytes → payload → dispatch.
Handle fragmented headers, multiple coalesced frames and EOF mid-frame. Validate magic,
version, flags, length and request ID before allocation. Oversized/malformed frames close
the connection with a bounded protocol error; do not attempt unbounded resynchronization.
Only dispatch a complete frame. Payload encoding is opaque bytes unless an explicitly
negotiated Data/Binary schema is selected; general JSON acceptance never relaxes signed
StrictJson contracts.
Both peers first exchange hello frames, each at most 4 KiB, with protocol version,
capabilities, frame/concurrency limits and application-protocol ID/version. Choose the
minimum supported limits, fail required-capability mismatch and complete within a
5-second injected steady deadline. Authenticate/authorize peer before admitting user
requests. Default session is full-duplex request/reply: each side chooses monotonically
increasing nonzero IDs from its own outgoing namespace, and message direction/type
disambiguates replies. IDs are not reused during a session; exhaustion triggers goaway
and reconnect. One-way sends report only local write completion, never remote execution.
## Ownership, cancellation and quotas
Session owns its stream, parser buffers, pending request map, send queue and Async scope.
OwnedBytes retains Memory storage until IO completes; received Message owns its payload
through handler return. No string_view into a recycled parser buffer escapes. Handlers
run on the injected executor outside session/map locks. Retain correlation entries
until the single terminal result is selected, and remove them on all failure paths.
Async OperationOptions supplies std::stop_token and the total absolute steady deadline;
no IPC-specific context. Cancellation removes a queued unsent request or emits one
bounded cancel frame for an admitted request. Remote cancellation is advisory: it cannot
undo effects and requires an acknowledgement to establish remote quiescence. A locally
timed-out request can have an unknown remote outcome. Do not automatically resend it
after reconnect. Applications use idempotency keys for retryable effects. A bounded
tombstone set recognizes late responses; never complete a reused ID or deliver twice.
Defaults: 1 MiB payload/frame, 64 in-flight outgoing requests/session, 64 active incoming
handlers/session, 128 queued output frames, 4 MiB queued output bytes, 2 MiB receive
buffer/session, 256 late-response tombstones and 128 sessions/listener. Listener global
owned-buffer budget defaults 64 MiB; global permits are reserved as well as per-session
permits, preventing the product of local caps from escaping the global budget. User
admission rejects overload; optional capacity waiting is cancellable with 128 waiters.
Output control frames have a reserved 8 KiB/16-frame lane and coalesce duplicate cancels.
When handler capacity is full, reject new complete requests with overload using reserved
capacity rather than blocking all reads and deadlocking bidirectional replies. Bound
per-peer request rate to a configurable default 1,000 requests/second with burst 128;
violations receive bounded error/goaway. Waiting payload bytes and active handlers count
toward quotas. Default idle session deadline 60 seconds, header/payload progress timeout
5 seconds within the total request deadline; no byte trickle can restart that total.
V1 does not transfer file descriptors, arbitrary object references or shared memory.
Ancillary descriptor passing is a later explicitly negotiated feature with descriptor
quotas and ownership checks. Current transport scope therefore excludes confused ownership
of received file handles. Connection loss faults all pending calls with transport-lost
and known/unknown effect metadata; it does not imply a failed remote commit.
## Shutdown and backend evolution
Close listener admission, send goaway, stop new user sends/requests, drain already admitted
responses under the caller deadline, request handler stop, join callbacks and IO, then
release stream/path ownership. Joining is off the session's own handler strand unless
already drained; self-join is rejected. Incomplete shutdown retains handler/IO owners.
Peer crash mid-frame releases all reserved bytes after IO stops accessing them.
Native Unix sockets/pipes and Binary framing are selected over an external messaging
library to keep protocol and quotas Void-owned. Windows named pipes and local TCP are
future capability adapters with identical framing/error conformance and explicit peer
identity differences. Shared-memory rings need a later measured gate defining crash
ownership, atomics/layout and buffer reclamation; they are not an implicit fast path.
## Ordered implementation backlog
All rows are PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-IPC-01 | P1 / Binary codec, Async ownership and IO stream gates | Versioned codec, incremental parser and global/per-session permits | Every fragmentation/coalescing/length boundary respects quotas before allocation / sol_implementer |
| S-IPC-02 | P2 / S-IPC-01; System ownership gate | Unix listener, pathname lifecycle, credential policy and supervised pipe adoption | Wrong user/path/symlink rejected; failed startup removes only owned endpoint / astra_implementer |
| S-IPC-03 | P2 / S-IPC-02 | Handshake, request correlation, bounded handlers/cancel/tombstones and goaway | Late response/timeout/loss delivers once; saturated bidirectional sessions still process control / astra_implementer |
| S-IPC-04 | P3 / S-IPC-03; Runtime/Plugin process-host specification | Joined shutdown, isolated-worker reference protocol and diagnostics | Worker crash faults pending calls without replay; retained payloads/handlers drain within ownership rules / sol_implementer |
| S-IPC-05 | P3 / S-IPC-04; measured transport need | Portable transport capability specification and optional descriptor-passing design gate | Common conformance on each supported backend; unsupported identity/feature never silently downgrades / astra_implementer |
## Validation, performance and migration
CURRENT aggregate source-regression command:
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
not rerun; no IPC tests exist today. PROPOSED checks need NEW fixtures: frame-byte
fragmentation/fuzzing, maximum/overflowing length, duplicate ID, invalid hello, slow
header, peer death after effect before reply, cancellation before/after send, request
flood/global cap, bidirectional overload, unauthorized credentials, stale socket path,
callback throw and shutdown with live response buffers. No real credentials enter
fixtures or traces. Use isolated user/path fixtures where the test environment permits.
Measure round-trip p50/p95/p99, frame throughput, allocations/copies, peak RSS/CPU,
descriptor count, queue occupancy and build cost under [PERFORMANCE](../PERFORMANCE.md).
No performance claims or benchmark runs accompany this plan. There is no legacy IPC
API; System process-stream output remains text until explicitly adapted to a framed
worker. Wire upgrades negotiate before requests; reject incompatible version, retain
old reader fixtures and reconnect only after draining. No automatic request replay
on protocol/backend rollback. See [MIGRATION](../MIGRATION.md),
[VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
[RPC](RPC.md), and [DELIVERY](../DELIVERY.md).