- spec 06 §6-§7: feature resources, consumption and verifier rules, io_error - spec 05 §11.1 fallible intrinsic form; spec 07 §8.7 frozen built-in enum variants, §8.9 resource types; spec 07a resources and run record fields; spec 11 §8 execution profiles, blocked outcome, result channel - reference/intrinsics.md: formal catalogue; capabilities.md: io_error and fs prefix narrowing - features: resources published, linear_aggregates reserved
274 lines
16 KiB
Markdown
274 lines
16 KiB
Markdown
# RFC 0007: I/O Intrinsics, I/O Errors and Linear Resources
|
|
|
|
Status: Accepted (revision 2, after owner review)
|
|
Scope: AIR format 0, feature `resources`; intrinsic and narrowing registries of `capabilities`
|
|
Language version: 0.1
|
|
Integrated into: spec 05 §11.1; spec 06 §6–§7; spec 07 §8.7, §8.9; spec 07a; spec 11 §7–§8; `reference/intrinsics.md`, `reference/capabilities.md`, `reference/air-features.md`
|
|
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. Profiles never invent results the program did not ask for: a run that can make no further progress ends with the environment outcome `blocked`, not with an I/O error.
|
|
|
|
## 1. Feature `resources`
|
|
|
|
Depends on `capabilities`, `effects`, `ownership`.
|
|
|
|
### 1.1 Types
|
|
|
|
| Type | Meaning | Accounted size |
|
|
|---|---|---|
|
|
| `file<read>` | file opened for reading | 8 |
|
|
| `file<write>` | file opened for writing (created or truncated) | 8 |
|
|
| `file<append>` | file opened for appending | 8 |
|
|
| `listener` | listening TCP socket | 8 |
|
|
| `stream` | connected TCP stream | 8 |
|
|
|
|
The mode of a file is part of its type, so using a file in the wrong mode is a verifier error, not a runtime failure: `fs.read` takes `mut<file<read>>`; `fs.write_all` and `fs.sync` take `mut<file<write>>` or `mut<file<append>>`.
|
|
|
|
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`). A closing intrinsic consumes the resource **regardless of its result**: on both the `ok` and the `err` edge the resource is dead, and closing it again is `E2002`. After a failed close the state of the underlying host handle is unspecified, so no retry is possible;
|
|
- 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<file>` / `mut<file>`.
|
|
|
|
### 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` | an explicit timeout expired (reserved for timers in Phase 3; no Phase 2 operation produces it) |
|
|
| `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. Host error numbers are not part of AIR semantics: a runtime may attach them as diagnostic metadata outside the run record's values, never in a way the program can observe.
|
|
|
|
**Frozen variant sets.** The variants of a published built-in enum never change: adding one would make an existing exhaustive `enum.switch` without `default` non-exhaustive, turning an accepted module into a rejected one (spec 07 §8.7). This is why `timed_out` is reserved now although nothing produces it yet.
|
|
|
|
## 3. Intrinsic forms
|
|
|
|
Two forms extend RFC 0006 §3:
|
|
|
|
```text
|
|
[%r =] intrinsic <name>(%a…) ; infallible
|
|
intrinsic <name>(%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<io.write>`, `bytes: slice<u8>` | — | `io.write` |
|
|
| `io.stderr_write` | `c: cap<io.write>`, `bytes: slice<u8>` | — | `io.write` |
|
|
| `io.stdin_read` | `c: cap<io.read>`, `buf: slice_mut<u8>` | `n: usize` (0 = end of input) | `io.read` |
|
|
|
|
Writes are all-or-error: on `@ok` every byte was written.
|
|
|
|
### Files (`fs.*`)
|
|
|
|
Paths are `slice<u8>` 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<fs.read>`, `path` | `f: file<read>` | `fs.read` |
|
|
| `fs.create` | `c: cap<fs.write>`, `path` | `f: file<write>` (truncated or new) | `fs.write` |
|
|
| `fs.open_append` | `c: cap<fs.write>`, `path` | `f: file<append>` (created if missing) | `fs.write` |
|
|
| `fs.read` | `b: mut<file<read>>`, `buf: slice_mut<u8>` | `n: usize` (0 = end of file) | `fs.read` |
|
|
| `fs.write_all` | `b: mut<file<write>>` or `mut<file<append>>`, `bytes: slice<u8>` | — | `fs.write` |
|
|
| `fs.sync` | `b: mut<file<write>>` or `mut<file<append>>` | — | `fs.write` |
|
|
| `fs.close` | `f: file<M>` for any mode (consumed on both edges) | — | — |
|
|
|
|
An error from `fs.close` reports a failed final flush; the file is closed either way.
|
|
|
|
### TCP (`net.*`)
|
|
|
|
Addresses are `slice<u8>` text `host:port` with a numeric IPv4 host (format 0).
|
|
|
|
| Intrinsic | Operands | `@ok` | Effect |
|
|
|---|---|---|---|
|
|
| `net.listen` | `c: cap<net.listen>`, `addr` | `l: listener` | `net.listen` |
|
|
| `net.accept` | `b: mut<listener>` | `s: stream` | `net.listen` |
|
|
| `net.connect` | `c: cap<net.connect>`, `addr` | `s: stream` | `net.connect` |
|
|
| `net.recv` | `b: mut<stream>`, `buf: slice_mut<u8>` | `n: usize` (0 = peer closed) | `net.read` |
|
|
| `net.send_all` | `b: mut<stream>`, `bytes: slice<u8>` | — | `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<clock.read>` | `u64` nanoseconds | `clock.read` |
|
|
| `random.fill` | `c: cap<random.read>`, `buf: slice_mut<u8>` | — | `random.read` |
|
|
|
|
### Narrowing forms
|
|
|
|
| Kind | Form | Argument | Result |
|
|
|---|---|---|---|
|
|
| `fs.read`, `fs.write` | `prefix` | `path: slice<u8>`, 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, which is printed on stdout | the process's real streams; the run record is written to a separate result channel (below) |
|
|
| 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; an operation that would wait for an event that can never occur ends the run with the environment outcome `blocked` (below) | 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 |
|
|
|
|
**Quiescence.** In the `deterministic` profile, when an operation would wait, no other execution unit can run, and no future deterministic event can complete the wait, the run ends with the environment outcome
|
|
|
|
```json
|
|
{"status":"blocked","kind":"no_future_event","function":"…","block":"…","inst":0}
|
|
```
|
|
|
|
and `aji run` exits with code 7. This is not an `io_error` and not a trap: the program did not ask for a timeout, so none is invented. In the `hosted` profile the same operation simply blocks. A program that needs a timeout states it explicitly (timers and `select`, Phase 3). The outcomes are now:
|
|
|
|
```text
|
|
program outcome: returned, trapped
|
|
environment outcome: not_instantiated, limit_exceeded, blocked
|
|
```
|
|
|
|
**Result channel.** In the `hosted` profile the program owns stdout and stderr, so the run record cannot share them unambiguously. The machine-readable record goes to a separate channel: `aji run --profile hosted --result-file PATH` (a `--result-fd N` form may follow; `ajid` has its own control channel). Without `--result-file` the CLI may print a human-readable summary on stderr after the program ends; that summary is not a machine interface.
|
|
|
|
## Valid example
|
|
|
|
```text
|
|
module example.hello
|
|
air 0
|
|
lang 0.1
|
|
features [arrays, capabilities, effects, ownership]
|
|
|
|
fn @main(%out: cap<io.write>) -> void
|
|
effects [io.write]
|
|
entry:
|
|
%msg = local.alloc array<u8, 6>
|
|
... ; 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<read>):
|
|
ret ; E3002: %f is never closed
|
|
```
|
|
|
|
```text
|
|
opened(%f: file<read>):
|
|
intrinsic fs.close(%f), ok -> @a, err -> @b
|
|
a:
|
|
%m = borrow.mut %f ; E3001: %f was closed
|
|
b(%e: io_error):
|
|
intrinsic fs.close(%f), ok -> @c, err -> @d ; E2002: closed on the err edge too
|
|
```
|
|
|
|
```text
|
|
opened(%f: file<read>):
|
|
%m = borrow.mut %f
|
|
intrinsic fs.write_all(%m, %s), ok -> @a, err -> @b ; E1001: needs mut<file<write>> or mut<file<append>>
|
|
```
|
|
|
|
```text
|
|
%f2 = copy %f ; E1001: resources are not copyable
|
|
```
|
|
|
|
```text
|
|
type @Log = struct { f: file<append> } ; 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. New environment outcome `blocked` (exit code 7).
|
|
|
|
## 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<T, E>` 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.
|
|
- **Synthetic `timed_out` for a `recv` that can never complete** (revision 1): gives one program different logical results in different profiles. Rejected for the `blocked` environment outcome.
|
|
- **Run record on stderr in the hosted profile** (revision 1): cannot be parsed unambiguously next to program stderr. Rejected for a separate result channel.
|
|
- **Untyped `file` with runtime mode checks** (revision 1): wrong-mode use found at runtime. Rejected for `file<read|write|append>`.
|
|
|
|
## Unresolved questions
|
|
|
|
None. Decided: UDP and IPv6 are deferred; no proven variants of `fs.read`/`net.recv` (a `.proven` form exists only where the verifier removes a specific safety check, as for `borrow.index.proven`).
|