From b8d4ab4d4ca022bb99b09cfd99be14cbf8c73b34 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 14:20:40 +0300 Subject: [PATCH] spec: accept RFC 0008 and integrate heap, regions and budgets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - spec 03 §18-§21: allocation authority and live-byte budgets, heap (own.new/array/take/free), regions (create/new/array/reset/destroy, static generations, E2104 on live references) - spec 05 §11.2, 07 §8.9, 07a summary, 08 §11.2 region allocation paths and the ok-parameter exception to borrow_joins - registries: alloc_error, mem.alloc budget form, mandatory deterministic budget; heap and regions published --- docs/reference/air-features.md | 6 +- docs/reference/capabilities.md | 4 +- docs/rfcs/0008-heap-and-regions.md | 3 +- docs/spec/03-memory-model.md | 120 +++++++++++++++++++++++ docs/spec/05-effects-and-capabilities.md | 4 + docs/spec/07-air.md | 2 + docs/spec/07a-air-instructions.md | 18 ++++ docs/spec/08-verifier.md | 4 +- 8 files changed, 154 insertions(+), 7 deletions(-) diff --git a/docs/reference/air-features.md b/docs/reference/air-features.md index 9df7b90..1af41a4 100644 --- a/docs/reference/air-features.md +++ b/docs/reference/air-features.md @@ -36,11 +36,11 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It | `borrow_joins` | reserved | — | `ownership` | borrow-typed block parameters (spec 08 §11.6); unscheduled | | `channels` | reserved | 3 | `ownership` | bounded and rendezvous channels with ownership transfer | | `effects` | published | 2 | — | flat effect checking of `effects [...]` for `call` and `intrinsic` (E3101, spec 05 §9) | -| `heap` | reserved | 2 | `capabilities`, `effects`, `ownership` | `Own`, `own.alloc`, `own.free`, move-only values | -| `islands` | reserved | 4 | `capabilities`, `effects`, `ownership`, `regions` | `Island`, `iref`, transfer, freeze, `Frozen` | +| `heap` | published | 2 | `capabilities`, `effects`, `ownership`, `resources` | `own`, `own_array`, `own.*`, built-in `alloc_error`, `mem.alloc` budgets and `budget` narrowing (spec 03 §18–§19) | +| `islands` | reserved | 4 | `capabilities`, `effects`, `heap`, `ownership`, `regions`, `resources` | `Island`, `iref`, transfer, freeze, `Frozen` | | `linear_aggregates` | reserved | — | `capabilities`, `effects`, `ownership`, `resources` | resource types as struct fields, enum payloads and array elements; unscheduled | | `ownership` | published | 1 | — | frame storage `local`, second-class borrows `ref`/`mut`, `from` returns, initialization (spec 07 §8.8, spec 07a, spec 08 §11, §13) | -| `regions` | reserved | 2 | `capabilities`, `effects`, `ownership` | `Region`, static generations, region allocation, reset and destroy | +| `regions` | published | 2 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `region`, `region.*`, static generations (spec 03 §20) | | `resource_joins` | reserved | — | `capabilities`, `effects`, `ownership`, `resources` | joins whose incoming edges carry different resource states (spec 06 §6.3); unscheduled | | `resources` | published | 2 | `capabilities`, `effects`, `ownership` | linear resources `file`, `file`, `file`, `listener`, `stream`; built-in `io_error`; I/O intrinsics (spec 06 §6–§7, `reference/intrinsics.md`) | | `sync` | reserved | 3 | `ownership` | `Mutex`, `RwLock`, linear guards | diff --git a/docs/reference/capabilities.md b/docs/reference/capabilities.md index c74435c..1462a6f 100644 --- a/docs/reference/capabilities.md +++ b/docs/reference/capabilities.md @@ -9,7 +9,7 @@ Normative registry of capability kinds for AIR format 0 (spec 05 §10). A kind n | `fs.write` | `fs.write` | absolute path prefix | `prefix` | | `io.read` | `io.read` | none | — | | `io.write` | `io.write` | none | — | -| `mem.alloc` | `mem.alloc` | byte budget | `budget` (RFC 0008) | +| `mem.alloc` | `mem.alloc` | byte budget of live allocations; mandatory in the `deterministic` profile | `budget` | | `mem.map` | `mem.map` | none | — | | `net.connect` | `net.connect` | none | — | | `net.listen` | `net.listen` | none | — | @@ -26,6 +26,7 @@ Narrowing forms marked with an RFC are registered when that RFC is accepted; unt | Enum | Variants | |---|---| | `cap_error` | `invalid_restriction`, `not_subset`, `unsupported_restriction` | +| `alloc_error` | `budget_exceeded`, `out_of_memory` | | `io_error` | `not_found`, `permission_denied`, `already_exists`, `invalid_input`, `no_space`, `broken_pipe`, `connection_refused`, `connection_reset`, `address_in_use`, `address_unavailable`, `timed_out`, `other` | Variant sets of published built-in enums are frozen (spec 07 §8.7). @@ -35,6 +36,7 @@ Variant sets of published built-in enums are frozen (spec 07 §8.7). | Kind | Form | Argument | `ok` | `err` (`cap_error`) | |---|---|---|---|---| | `fs.read`, `fs.write` | `prefix` | `path: slice`, absolute, no empty/`.`/`..` components | same kind scoped to `path` | `invalid_restriction` if malformed; `not_subset` if not inside the current scope | +| `mem.alloc` | `budget` | `n: usize` | child authority with limit `n`, charges propagate to every ancestor; nothing reserved | `not_subset` if `n` exceeds the parent's limit | ## Instantiation diff --git a/docs/rfcs/0008-heap-and-regions.md b/docs/rfcs/0008-heap-and-regions.md index 73f0cff..756b187 100644 --- a/docs/rfcs/0008-heap-and-regions.md +++ b/docs/rfcs/0008-heap-and-regions.md @@ -1,8 +1,9 @@ # RFC 0008: Heap Allocation, Regions and Allocation Budgets -Status: Proposed (revision 2: owner review applied) +Status: Accepted (revision 2, after owner review) Scope: AIR format 0, features `heap` and `regions`; `mem.alloc` narrowing Language version: 0.1 +Integrated into: spec 03 §18–§21; spec 05 §11.2; spec 07 §8.9; spec 07a; spec 08 §11.2, §11.6; `reference/capabilities.md`, `reference/air-features.md` Supersedes: — Builds on RFC 0005 (frame storage, second-class borrows), RFC 0006 (capabilities) and RFC 0007 (linear values, fallible terminators). Realizes spec 03 §7–§8 under the decision Q-010 (static region generations). diff --git a/docs/spec/03-memory-model.md b/docs/spec/03-memory-model.md index 07a0ebd..88633f4 100644 --- a/docs/spec/03-memory-model.md +++ b/docs/spec/03-memory-model.md @@ -283,3 +283,123 @@ Unsafe code is responsible for establishing: - provenance assumptions required by the backend; - aliasing discipline; - synchronization where memory is shared concurrently. + +## 18. Allocation authority in AIR (feature `heap`) + +Decision record: RFC 0008. + +Invariants: + +1. **No implicit allocation, no implicit free.** Memory is obtained only by an allocating instruction with a `cap` operand (directly or through a region created from one), and returned only by `own.free`, `region.reset` or `region.destroy`. +2. **Linearity.** `own`, `own_array` and `region` are linear values with the rules of spec 06 §6 (consumed exactly once on every normal path; `E3002`, `E2001`, `E2002`). +3. **No dangling access.** Heap and region memory is reached only through second-class borrows, which cannot outlive the owner (heap) or the region generation (regions). There are no runtime generation checks. +4. **Bounded memory.** Every allocation is charged against a budget held by the authority object of the capability. The budget limits the bytes that are **live at the same time**. +5. **Shared quota.** Copies of a capability refer to one authority object and share one budget; narrowing creates a child budget whose charges also count against every ancestor. +6. **No hidden destruction of linear values.** `own.free`, `own.take`, `region.reset` and `region.destroy` can never make a linear value disappear: until `linear_aggregates` is specified, values stored in `own`, `own_array` and region allocations MUST NOT transitively contain linear values (resources, owners, regions). + +### 18.1 Budget semantics + +A `cap` refers to an authority object with a `limit` (bytes, or unlimited) and a counter `used`. An allocation of `b` accounted bytes succeeds only if `used + b ≤ limit` holds for the object and every ancestor; it then adds `b` to `used` of each. Freeing returns the bytes to the same objects: + +```text +alloc 10 MiB → used = 10 MiB +free 10 MiB → used = 0 +``` + +The budget is a limit on simultaneously live memory, not a cumulative execution quota. + +*Live allocation* and *live reference* are different things. A region allocation stays charged until `region.reset` or `region.destroy`, even after every borrow of it has ended: `borrow.end` never returns quota, because the region still holds the memory. Implementations MAY additionally report `total_allocated_bytes`, `peak_live_bytes` and `allocation_count` in audit reports; these never affect semantics. + +Accounted bytes are those of spec 08 §7.1: `own` charges `accounted_size(T)`, `own_array` charges `n × accounted_size(T)` with checked arithmetic (overflow fails the allocation with `budget_exceeded`). Allocator overhead is not charged. + +### 18.2 Instantiation + +The scope of a `mem.alloc` grant is the byte limit (`--grant heap=mem.alloc:67108864`). In the `deterministic` profile the limit is **mandatory** (a grant without it is `not_instantiated` with reason `invalid_scope`), so every deterministic run has bounded memory. In the `hosted` profile an absent limit means unlimited by the program; the host may still fail an allocation (`out_of_memory`). + +### 18.3 Narrowing form `budget` + +`cap.narrow.budget %c, %n, ok -> @ok, err -> @err` (`%n: usize`) creates a child authority object with `limit = n` and parent `%c`. The `err` edge receives `not_subset` if `n` exceeds the parent's limit. Two copies of either capability share their object's budget. + +Narrowing reserves nothing. Children of one parent may have limits that add up to more than the parent's (a 64 MiB parent with two 48 MiB children); they then compete for the parent's real 64 MiB, because every charge to a child is also a charge to the parent: + +```text +allocate 10 MiB through child → child.used += 10, parent.used += 10 +free it → child.used -= 10, parent.used -= 10 +``` + +### 18.4 Errors + +`alloc_error` is a built-in enum with the variants `budget_exceeded` (the budget of the capability or an ancestor would be exceeded) and `out_of_memory` (the host could not provide memory; never produced by the `deterministic` profile). Its variant set is frozen on publication. + +## 19. Heap in AIR (feature `heap`) + +Depends on `capabilities`, `effects`, `ownership`, `resources`. + +### 19.1 Types + +| Type | Meaning | Accounted size of the handle | +|---|---|---| +| `own` | one heap object of value type `T` | 8 | +| `own_array` | `n` heap elements of value type `T`, `n` chosen at runtime | 16 | + +Both are linear and not copyable; as members of aggregates they need `linear_aggregates` (`E0006`). + +### 19.2 Instructions + +| Instruction | Operands → result | Effect | Notes | +|---|---|---|---| +| `own.new %v, %c, ok -> @ok, err -> @err` | `T`, `cap` → `@ok(%o: own)`, `@err(%e: alloc_error)` | `mem.alloc` | object initialized with `%v` | +| `own.array %n, %v, %c, ok -> @ok, err -> @err` | `usize`, `T`, `cap` → `@ok(%a: own_array)` | `mem.alloc` | every element initialized with `%v` | +| `own.take %o` | `own` (consumed) → `T` | — | moves the value out, frees the allocation, returns the bytes | +| `own.free %o` | `own` or `own_array` (consumed) | — | returns the bytes to the budget | +| `borrow.ref` / `borrow.mut` | `own` → `ref` / `mut`; `own_array` → `slice` / `slice_mut` | — | the owner is the borrow root | + +Heap memory is always initialized, so no initialization tracking is needed. `own.free` or `own.take` while a borrow of the owner is live is `E2101`. `own.take` is the inverse of `own.new` (`T → own → T`); an `own_array` has no `take`, since a runtime-sized array is not an SSA value. + +`T` in `own` and `own_array` must be a value type; a linear `T` (for example `own>` or `own>`) needs `linear_aggregates` (`E0006` reason `feature_not_declared`), which will define extraction and destruction of nested linear values. An owner is passed to a function by value (moving it) or by borrow (lending it), exactly like a resource. + +## 20. Regions in AIR (feature `regions`) + +Depends on `capabilities`, `effects`, `heap`, `ownership`, `resources`. + +### 20.1 Type and lifetime + +`region` is a linear value owning many allocations that share one lifetime. It is created from a capability, allocated from through a **shared** borrow, and reset or destroyed directly: + +| Instruction | Operands → result | Effect | Notes | +|---|---|---|---| +| `region.create %c, ok -> @ok, err -> @err` | `cap` → `@ok(%r: region)`, `@err(%e: alloc_error)` | `mem.alloc` | allocations of the region are charged to `%c` | +| `region.new %rb, %v, ok -> @ok, err -> @err` | `ref`, `T` → `@ok(%p: mut)` | `mem.alloc` | fresh object initialized with `%v` | +| `region.array %rb, %n, %v, ok -> @ok, err -> @err` | `ref`, `usize`, `T` → `@ok(%s: slice_mut)` | `mem.alloc` | fresh array | +| `region.reset %r` | `region` (not consumed) | — | frees every allocation of the generation, returns all their bytes, starts a new generation | +| `region.destroy %r` | `region` (consumed) | — | frees every allocation and the region, returns all their bytes | + +Values stored by `region.new`/`region.array` must be value types (no linear values), for the same reason as for `own`. + +Budget accounting of a region, normatively: + +```text +region.new / region.array → used += allocation charge +borrow.end of an allocation → used unchanged +region.reset → used -= every allocation of the generation +region.destroy → used -= every allocation of the region +``` + +### 20.2 Verifier rules (static generations, Q-010) + +- A region allocation `%p` is an owned borrow whose parent is the shared region borrow `%rb` and whose path is a fresh element unique to that allocation. Allocations are therefore disjoint from each other, and the exclusive borrow `mut` of a fresh object does not conflict with the shared parent (this is the one place where an exclusive child of a shared borrow is permitted, because the storage is new). +- `region.reset %r` and `region.destroy %r` are exclusive accesses to the region value. If a **live reference** into the region exists — any live borrow derived from `%r`, in particular a live borrow of an allocation — the instruction is `E2104` (`memory.region_generation`): reset or destroy would invalidate a live reference. Allocations whose borrows have all ended are not an obstacle; destroying them is what `reset` and `destroy` are for. +- Ending `%rb` while one of its allocations is live is `E2102`, so no allocation outlives the borrow it came from. +- A function may return a region allocation with `from %rb` when `%rb` is a `ref` parameter (spec 08 §11.3 applies unchanged: the root is the parameter). Frame-derived borrows still never escape (`E2108`). + +No reference to a region allocation exists after `reset` or `destroy`, so safe code performs no generation checks at runtime. + +### 20.3 Not in this RFC + +Allocations cannot contain borrows (borrows are second-class), so linked structures inside a region use indices; cyclic owned graphs are islands (Phase 4). + +## 21. Runtime + +- Authority objects for `mem.alloc` carry `limit`, `used` and `parent`. Narrowing appends a child. Charges walk the parent chain. +- `own` is a cell holding a value; `own_array` a cell holding an array of `n` values. A region keeps a generation counter and the bytes charged by its current generation. +- In the `deterministic` profile memory is bounded by the mandatory budgets, so the interpreter's own memory use is bounded by a function of the module and its grants. diff --git a/docs/spec/05-effects-and-capabilities.md b/docs/spec/05-effects-and-capabilities.md index 1fb3eb5..d54da8b 100644 --- a/docs/spec/05-effects-and-capabilities.md +++ b/docs/spec/05-effects-and-capabilities.md @@ -263,6 +263,10 @@ A fallible intrinsic delivers its results as the parameters of `@ok` (count and The catalogue of intrinsics is [`../reference/intrinsics.md`](../reference/intrinsics.md). +### 11.2 Allocation budgets + +The authority object of a `cap` carries a budget of simultaneously live bytes, shared by all copies and charged along the chain of narrowings; see spec 03 §18. + ## 12. Runtime - A capability is represented as an index into a host-owned table of (kind, scope) entries. The index is not observable by the program. diff --git a/docs/spec/07-air.md b/docs/spec/07-air.md index 7a336ae..ec57056 100644 --- a/docs/spec/07-air.md +++ b/docs/spec/07-air.md @@ -260,6 +260,8 @@ Any other change to format 0 — a different meaning, typing rule, trap behavior Feature `resources`: `file`, `file`, `file`, `listener`, `stream` are linear, authority-bearing resource types (spec 06 §6). +Feature `heap`: `own` and `own_array` (linear owners, `T` a value type) and the built-in enum `alloc_error`. Feature `regions`: `region` (linear). Rules: spec 03 §18–§21. Linear values — resources, owners and regions — follow the consumption rules of spec 06 §6.2–§6.3. + ### 8.8 Types and syntax of the features `ownership` and `arrays` Feature membership: `local`, `ref`, `mut` and the `from` clause belong to `ownership`; `array`, `slice`, `slice_mut` and multi-result binding belong to `arrays`. Using them without declaring the feature is `E0006` reason `feature_not_declared`. diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md index 86d5b5a..eed22cf 100644 --- a/docs/spec/07a-air-instructions.md +++ b/docs/spec/07a-air-instructions.md @@ -228,6 +228,24 @@ Intrinsics have an infallible form (`[%r =] intrinsic …`) and a fallible termi Resource types and their consumption rules: spec 06 §6. Resources are used through `borrow.ref`/`borrow.mut` (which accept a resource value as root) and consumed by closing intrinsics, by-value resource parameters, resource block parameters and `ret`. +## Feature `heap` and feature `regions` + +Instructions, budget accounting and verifier rules: spec 03 §18–§20. Summary: + +| Instruction | Form | Effect | +|---|---|---| +| `own.new %v, %c, ok -> @ok, err -> @err` | terminator, `@ok(own)`, `@err(alloc_error)` | `mem.alloc` | +| `own.array %n, %v, %c, ok -> @ok, err -> @err` | terminator, `@ok(own_array)`, `@err(alloc_error)` | `mem.alloc` | +| `%v = own.take %o` | consumes `own`, yields `T` | — | +| `own.free %o` | consumes `own` or `own_array` | — | +| `region.create %c, ok -> @ok, err -> @err` | terminator, `@ok(region)`, `@err(alloc_error)` | `mem.alloc` | +| `region.new %rb, %v, ok -> @ok, err -> @err` | terminator, `@ok(mut)`, `@err(alloc_error)` | `mem.alloc` | +| `region.array %rb, %n, %v, ok -> @ok, err -> @err` | terminator, `@ok(slice_mut)`, `@err(alloc_error)` | `mem.alloc` | +| `region.reset %r` | region not consumed | — | +| `region.destroy %r` | consumes region | — | + +`borrow.ref`/`borrow.mut` accept owners and regions as roots: `own` gives `ref`/`mut`, `own_array` gives `slice`/`slice_mut`, `region` gives `ref`/`mut`. + ## Run result `aji run` executes the function `@main`, whose parameters MUST all be capabilities, bound by name at instantiation (spec 05 §10.2); without the `capabilities` feature it takes no parameters. On return it reports `{"status":"returned","value":V}` where `V` renders the returned value as JSON: diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md index 51f6011..9df4ad0 100644 --- a/docs/spec/08-verifier.md +++ b/docs/spec/08-verifier.md @@ -174,7 +174,7 @@ Normative rules for frame storage and second-class borrows. Decision record: RFC Every borrow has a **root** (a `local` or a lent parameter), a **path** from the root (field names, a slice range, or an element), a **mode** (`ref`/`mut`) and a **parent** (none for borrows taken directly from a local or a parameter). -- Two paths overlap unless they diverge at different fields of the same struct, or they are the two results of one `slice.split` (and descendants of each). +- Two paths overlap unless they diverge at different fields of the same struct, at the two results of one `slice.split`, or at two different region allocations (spec 03 §20.2) (and descendants of each). - Element borrows (`borrow.index`) and sub-slices of the same parent all overlap each other. - Creating a borrow conflicts with every live borrow whose path overlaps when either is `mut` (`E2101`). - A borrow with live children is **frozen**: it may still create further children that do not conflict, but it cannot be read, written or ended while a live child conflicts with that use (`E2101`, `E2102` for ending). @@ -207,7 +207,7 @@ Each function's frame storage is the sum of the accounted sizes (§7.1) of its ` ### 11.6 Borrow-typed block parameters -Borrow-typed block parameters are reserved for the feature `borrow_joins`. Without it they are rejected with `E0006` reason `feature_not_declared`. Using a feature gate, rather than a permanent type error, keeps the door open without breaking the format-0 freeze (spec 07 §8.7). +Borrow-typed block parameters are reserved for the feature `borrow_joins`, with one exception: the single parameter of the `ok` target of `region.new`/`region.array` (spec 03 §20), provided every edge into that block is such an `ok` edge. Without it they are rejected with `E0006` reason `feature_not_declared`. Using a feature gate, rather than a permanent type error, keeps the door open without breaking the format-0 freeze (spec 07 §8.7). ## 12. Bounds facts (feature `arrays`)