diff --git a/docs/rfcs/0007-io-and-linear-resources.md b/docs/rfcs/0007-io-and-linear-resources.md new file mode 100644 index 0000000..832ee18 --- /dev/null +++ b/docs/rfcs/0007-io-and-linear-resources.md @@ -0,0 +1,241 @@ +# RFC 0007: I/O Intrinsics, I/O Errors and Linear Resources + +Status: Proposed +Scope: AIR format 0, feature `resources`; intrinsic and narrowing registries of `capabilities` +Language version: 0.1 +Supersedes: — + +Builds on RFC 0005 (borrows) and RFC 0006 (effects, capabilities). Heap allocation and regions follow in RFC 0008 and reuse the linearity rules defined here. + +## Motivation + +Phase 2 must let a verified program talk to the outside world — console, files, TCP — without exceptions, hidden destructors, ambient authority or leaked handles, and with outcomes that are reproducible in the `deterministic` profile. That needs three things RFC 0006 left open: a catalogue of intrinsics, a representation of I/O failure, and resource handles that must be released exactly once. + +## Invariants + +1. **Linearity.** A resource value (`file`, `listener`, `stream`) is consumed exactly once on every normal path: by a closing intrinsic, by passing it to a by-value resource parameter or block parameter, or by returning it. It is never used after consumption and never silently dropped. +2. **No implicit release.** No resource is closed by scope exit, by a trap path being taken, or by any hidden action. Paths ending in `trap` end the program; the runtime then releases host resources as part of terminating the execution instance, which is not observable by the program. +3. **Explicit failure.** Every operation that can fail for external reasons delivers either its results or an `io_error` to block parameters. Failure is never a trap and never an exception. +4. **Object capabilities.** An open resource carries the authority it was opened with; operations on it need its effect but no further capability operand. Opening a resource requires a capability. +5. **Determinism.** In the `deterministic` profile every intrinsic has a fully specified result; the same module, grants, inputs and fuel produce the same run record. + +## 1. Feature `resources` + +Depends on `capabilities`, `effects`, `ownership`. + +### 1.1 Types + +| Type | Meaning | Accounted size | +|---|---|---| +| `file` | open file | 8 | +| `listener` | listening TCP socket | 8 | +| `stream` | connected TCP stream | 8 | + +Resource types are **linear** and **authority-bearing** (RFC 0006 §2.1): not copyable (`copy` is `E1001`), not zeroable, not comparable, not serializable. + +In format 0, resource types MUST NOT appear as struct fields, enum payloads or array elements; that requires the reserved feature `linear_aggregates` (`E0006` reason `feature_not_declared` without it). They may appear as function parameters, return types, block parameters and as operands of borrow instructions. + +### 1.2 Consumption + +A resource value is **consumed** by exactly one of: + +- a closing intrinsic (`fs.close`, `net.close_stream`, `net.close_listener`); +- being a `call` argument for a parameter of resource type (ownership moves to the callee); +- being a branch argument (`br`, `cbr`, `switch`, default targets) for a block parameter of resource type; +- `ret`. + +Every other operand use of a resource is a **non-consuming use**, which is only permitted through borrows: `borrow.ref %f` / `borrow.mut %f` take a resource SSA value as their root, exactly as for a `local` (RFC 0005), and produce `ref` / `mut`. + +### 1.3 Verifier rules + +The resource state of each resource value — `owned`, `consumed by close`, `consumed by transfer` — is tracked on every reachable path with the same discipline as borrows (spec 08 §11.4): + +| Rule | Code | +|---|---| +| owned resource live at `ret` (other than the returned one) | `E3002` (`resource.leak`) | +| resource state differs between edges into a block | `E3002` | +| resource consumed again after any consumption | `E2002` (`ownership.double_consume`) | +| non-consuming use after consumption by a closing intrinsic | `E3001` (`resource.use_after_consume`) | +| non-consuming use after consumption by transfer | `E2001` (`ownership.use_after_move`) | +| resource consumed while a borrow of it is live | `E2101` | + +Resource parameters of the current function are owned by it (they were moved in). Resource block parameters own their argument. + +## 2. I/O errors + +`io_error` is a built-in enum (spelled without `@`, used with `enum.switch io_error %e, …`): + +| Variant | Meaning | +|---|---| +| `not_found` | path or address does not exist | +| `permission_denied` | the host refused, or the path is outside the capability's scope | +| `already_exists` | exclusive creation of an existing path | +| `invalid_input` | malformed path or address (relative path, `.`/`..` component, unparsable address) | +| `no_space` | storage exhausted | +| `broken_pipe` | the peer closed while writing | +| `connection_refused` | nobody listens at the address | +| `connection_reset` | the peer reset the connection | +| `address_in_use` | listen address taken | +| `address_unavailable` | listen or connect address not available to this host | +| `timed_out` | the operation cannot complete (see §5 for the deterministic profile) | +| `other` | any host error not listed above | + +The mapping from host errors to variants is part of each profile's specification; `other` keeps the set closed. + +## 3. Intrinsic forms + +Two forms extend RFC 0006 §3: + +```text +[%r =] intrinsic (%a…) ; infallible +intrinsic (%a…), ok -> @ok, err -> @err ; fallible: a terminator +``` + +A fallible intrinsic delivers its results as the parameters of `@ok` (count and types per registry; `E5002`/`E1001`) and a single `io_error` to `@err`. The registry says which form each intrinsic has; using the other form is `E1001`. Resource operands consumed by an intrinsic are consumed on both edges. + +## 4. Intrinsic catalogue + +`c` = capability operand, `b` = borrowed resource operand, results are `@ok` parameters. + +### Console (`io.*`) + +| Intrinsic | Operands | `@ok` | Effect | +|---|---|---|---| +| `io.stdout_write` | `c: cap`, `bytes: slice` | — | `io.write` | +| `io.stderr_write` | `c: cap`, `bytes: slice` | — | `io.write` | +| `io.stdin_read` | `c: cap`, `buf: slice_mut` | `n: usize` (0 = end of input) | `io.read` | + +Writes are all-or-error: on `@ok` every byte was written. + +### Files (`fs.*`) + +Paths are `slice` holding an absolute path whose components are not empty, `.` or `..` (otherwise `invalid_input`). A path outside the capability's scope is `permission_denied`. + +| Intrinsic | Operands | `@ok` | Effect | +|---|---|---|---| +| `fs.open_read` | `c: cap`, `path` | `f: file` | `fs.read` | +| `fs.create` | `c: cap`, `path` | `f: file` (truncated or new) | `fs.write` | +| `fs.open_append` | `c: cap`, `path` | `f: file` (created if missing) | `fs.write` | +| `fs.read` | `b: mut`, `buf: slice_mut` | `n: usize` (0 = end of file) | `fs.read` | +| `fs.write_all` | `b: mut`, `bytes: slice` | — | `fs.write` | +| `fs.sync` | `b: mut` | — | `fs.write` | +| `fs.close` | `f: file` (consumed) | — | — | + +Reading a file opened for writing, or writing one opened for reading, is `permission_denied`. `fs.close` consumes the file on both edges; an error reports a failed final flush. + +### TCP (`net.*`) + +Addresses are `slice` text `host:port` with a numeric IPv4 host (format 0). + +| Intrinsic | Operands | `@ok` | Effect | +|---|---|---|---| +| `net.listen` | `c: cap`, `addr` | `l: listener` | `net.listen` | +| `net.accept` | `b: mut` | `s: stream` | `net.listen` | +| `net.connect` | `c: cap`, `addr` | `s: stream` | `net.connect` | +| `net.recv` | `b: mut`, `buf: slice_mut` | `n: usize` (0 = peer closed) | `net.read` | +| `net.send_all` | `b: mut`, `bytes: slice` | — | `net.write` | +| `net.close_stream` | `s: stream` (consumed) | — | — | +| `net.close_listener` | `l: listener` (consumed) | — | — | + +All network operations block the calling execution unit (Phase 3 adds `thread.block` handling and task-aware I/O). + +### Clock and random (infallible) + +| Intrinsic | Operands | Result | Effect | +|---|---|---|---| +| `clock.monotonic` | `c: cap` | `u64` nanoseconds | `clock.read` | +| `random.fill` | `c: cap`, `buf: slice_mut` | — | `random.read` | + +### Narrowing forms + +| Kind | Form | Argument | Result | +|---|---|---|---| +| `fs.read`, `fs.write` | `prefix` | `path: slice`, absolute | `ok`: same kind scoped to `path`; `err`: `invalid_restriction` if `path` is malformed, `not_subset` if it is not inside the current scope | + +## 5. Profiles + +The run record gains fields for observable output. `aji run` uses the **deterministic** profile by default; `--profile hosted` uses the real host. + +| Aspect | `deterministic` | `hosted` | +|---|---|---| +| stdout / stderr | captured; reported as `"stdout"` / `"stderr"` strings in the run record | the process's real streams; the run record goes to stderr as the last line | +| stdin | from `--stdin TEXT` (empty by default) | real stdin | +| files | in-memory file system seeded by `--vfs PATH=TEXT`; files written during the run are reported as `"files"` in the run record | real file system, limited by capability scopes | +| network | in-process loopback: `net.connect` to a listening address of the same run queues a connection that `net.accept` returns; sends are buffered; a `recv` that could only block forever yields `timed_out` | real sockets | +| clock | the number of instructions executed so far (1 ns per instruction) | real monotonic clock | +| random | PRNG seeded by `--seed N` (default 0), algorithm fixed by the spec | host CSPRNG | + +## Valid example + +```text +module example.hello +air 0 +lang 0.1 +features [arrays, capabilities, effects, ownership] + +fn @main(%out: cap) -> void +effects [io.write] +entry: + %msg = local.alloc array + ... ; store "hello\n" + %r = borrow.ref %msg + %s = slice.make %r + intrinsic io.stdout_write(%out, %s), ok -> @done, err -> @failed +done: + borrow.end %s + borrow.end %r + ret +failed(%e: io_error): + borrow.end %s + borrow.end %r + trap +``` + +Run: `aji run --grant out=io.write hello.air` → `{"status":"returned","value":null,"stdout":"hello\n"}`. + +## Rejected examples + +```text + intrinsic fs.open_read(%c, %p), ok -> @opened, err -> @fail +opened(%f: file): + ret ; E3002: %f is never closed +``` + +```text +opened(%f: file): + intrinsic fs.close(%f), ok -> @a, err -> @b +a: + %m = borrow.mut %f ; E3001: %f was closed +``` + +```text + %f2 = copy %f ; E1001: resources are not copyable +``` + +```text +type @Log = struct { f: file } ; E0006: needs feature linear_aggregates +``` + +## Diagnostics + +Existing codes now specified for resources: `E2001`, `E2002`, `E3001`, `E3002` (§1.3), `E3201` (wrong capability kind for an intrinsic), `E3101` (intrinsic effect). New built-in enum `io_error`. No new codes. + +## Compatibility + +Additive under spec 07 §8.7: the new feature `resources` (and reserved `linear_aggregates`), new intrinsic and narrowing registry entries, new run-record fields and profile options. The default profile of `aji run` becomes `deterministic`; previous runs produced no I/O, so their records are unchanged except for the added empty `stdout`/`stderr` fields — to keep records byte-identical, those fields are present only when the program declares `capabilities`. + +## Spec integration + +On acceptance: spec 06 (linear resources, §1 and §3 realized), spec 05 §10–§11 (narrowing forms, intrinsic forms), spec 07 §8.9 (types), spec 07a (feature `resources`, intrinsic catalogue, run record fields), spec 08 (stage order: resources with borrows), spec 11 (profiles), `reference/intrinsics.md` (formal catalogue), `reference/capabilities.md` (`prefix`, `io_error`), `reference/air-features.md` (`resources` published, `linear_aggregates` reserved), plan Phase 2. + +## Alternatives considered + +- **Ownership-passing I/O** (every operation consumes the handle and returns it): linear without borrows, but every helper would have to return the handle together with its result, which needs linear aggregates. Borrowing the resource keeps helpers simple and matches spec 06 examples (`fs.read(ref input, …)`). +- **A generic `result` type**: more general, but needs generics in AIR. The terminator form delivers results the same way `enum.switch` and `cap.narrow` do and cannot be misused. +- **Traps on I/O failure**: rejected; external failure is expected and must be handled (spec 06 §5). +- **Hosted profile by default**: makes the default run non-reproducible and mixes program output with the machine-readable record. + +## Unresolved questions + +- Whether format 0 should include UDP and IPv6 (proposed: later). +- Whether `fs.read`/`net.recv` should also have proven-length variants avoiding the copy into a separate buffer (proposed: not needed).