rfc: 0008 heap allocation, regions and allocation budgets (Proposed)

own<T>/own_array<T> (heap), region with shared-borrow allocation and
static generations (E2104 on reset/destroy with live allocations),
cap<mem.alloc> budgets limiting live bytes and shared by copies,
hierarchical cap.narrow.budget, alloc_error, mandatory deterministic
budget.
This commit is contained in:
dev committed 2026-10-04 14:09:27 +03:00
1 parent 7a74be3cf7
commit 75dfaac1a6
1 file changed
+182
+182
View File
@@ -0,0 +1,182 @@
# RFC 0008: Heap Allocation, Regions and Allocation Budgets
Status: Proposed
Scope: AIR format 0, features `heap` and `regions`; `mem.alloc` narrowing
Language version: 0.1
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).
## Motivation
Frame storage is bounded by `max_local_frame` and every value by `max_value_size`. Programs need memory whose size is decided at runtime (a 64 MiB buffer, a variable number of objects) and whose lifetime is not tied to one call. Spec 03 provides two mechanisms — individually owned objects and bulk regions — and spec 05 requires allocation to be authorized. This RFC realizes both without a garbage collector, hidden destructors or implicit authority.
Three concepts stay separate:
```text
own<T>, own_array<T> individual ownership (feature heap)
region bulk lifetime (feature regions)
cap<mem.alloc> authority + memory quota (feature heap, registry of capabilities)
```
## Invariants
1. **No implicit allocation, no implicit free.** Memory is obtained only by an allocating instruction with a `cap<mem.alloc>` operand (directly or through a region created from one), and returned only by `own.free`, `region.reset` or `region.destroy`.
2. **Linearity.** `own<T>`, `own_array<T>` 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.
## 1. Allocation authority (feature `heap`)
### 1.1 Budget semantics
A `cap<mem.alloc>` 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. 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<T>` charges `accounted_size(T)`, `own_array<T>` charges `n × accounted_size(T)` with checked arithmetic (overflow fails the allocation with `budget_exceeded`). Allocator overhead is not charged.
### 1.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`).
### 1.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.
### 1.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.
## 2. Heap (feature `heap`)
Depends on `capabilities`, `effects`, `ownership`, `resources`.
### 2.1 Types
| Type | Meaning | Accounted size of the handle |
|---|---|---|
| `own<T>` | one heap object of value type `T` | 8 |
| `own_array<T>` | `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`).
### 2.2 Instructions
| Instruction | Operands → result | Effect | Notes |
|---|---|---|---|
| `own.new %v, %c, ok -> @ok, err -> @err` | `T`, `cap<mem.alloc>` → `@ok(%o: own<T>)`, `@err(%e: alloc_error)` | `mem.alloc` | object initialized with `%v` |
| `own.array %n, %v, %c, ok -> @ok, err -> @err` | `usize`, `T`, `cap<mem.alloc>` → `@ok(%a: own_array<T>)` | `mem.alloc` | every element initialized with `%v` |
| `own.free %o` | `own<T>` or `own_array<T>` (consumed) | — | returns the bytes to the budget |
| `borrow.ref` / `borrow.mut` | `own<T>` → `ref<T>` / `mut<T>`; `own_array<T>` → `slice<T>` / `slice_mut<T>` | — | the owner is the borrow root |
Heap memory is always initialized, so no initialization tracking is needed. `own.free` while a borrow of the owner is live is `E2101`. An owner is passed to a function by value (moving it) or by borrow (lending it), exactly like a resource.
## 3. Regions (feature `regions`)
Depends on `capabilities`, `effects`, `heap`, `ownership`, `resources`.
### 3.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<mem.alloc>` → `@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<region>`, `T` → `@ok(%p: mut<T>)` | `mem.alloc` | fresh object initialized with `%v` |
| `region.array %rb, %n, %v, ok -> @ok, err -> @err` | `ref<region>`, `usize`, `T` → `@ok(%s: slice_mut<T>)` | `mem.alloc` | fresh array |
| `region.reset %r` | `region` (not consumed) | — | frees every allocation, returns the bytes, starts a new generation |
| `region.destroy %r` | `region` (consumed) | — | frees every allocation and the region |
### 3.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<T>` 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 any borrow derived from `%r` is live — in particular any allocation of the current generation — the instruction is `E2104` (`memory.region_generation`): those references would belong to an invalidated generation.
- 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<region>` parameter (RFC 0005 §5.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.
### 3.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).
## 4. Runtime and interpreter
- Authority objects for `mem.alloc` carry `limit`, `used` and `parent`. Narrowing appends a child. Charges walk the parent chain.
- `own<T>` is a cell holding a value; `own_array<T>` 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.
## Valid example
```text
fn @main(%heap: cap<mem.alloc>, %src: cap<fs.read>) -> void
effects [fs.read, mem.alloc]
entry:
region.create %heap, ok -> @have_region, err -> @no_memory
have_region(%r: region):
%rb = borrow.ref %r
%n = const.usize 65536
%z = const.u8 0
region.array %rb, %n, %z, ok -> @have_buf, err -> @no_buf
have_buf(%buf: slice_mut<u8>):
... ; read files into %buf
borrow.end %buf
borrow.end %rb
region.destroy %r
ret
...
```
## Rejected examples
```text
have_buf(%buf: slice_mut<u8>):
region.reset %r ; E2104: %buf belongs to the current generation
```
```text
have_obj(%o: own<u64>):
ret ; E3002: %o is never freed
```
```text
have_obj(%o: own<u64>):
own.free %o
%b = borrow.ref %o ; E2001: %o was consumed by own.free
```
```text
cap.narrow.budget %heap, %huge, ok -> @a, err -> @b ; err edge: not_subset when %huge > limit
```
## Diagnostics
Existing codes, now specified for memory: `E2001`, `E2002`, `E2101`, `E2102`, `E2104`, `E3002`, `E3101` (allocating without `mem.alloc`), `E3201`. New built-in enum `alloc_error`. No new codes.
## Compatibility
Additive under spec 07 §8.7: features `heap` and `regions` are reserved today; their registry entries gain `resources` (and `regions` gains `heap`) in the dependency closure before publication; `islands` updates its closure accordingly. `mem.alloc` gains the narrowing form `budget`.
## Spec integration
On acceptance: spec 03 §7–§8 (heap and regions realized), spec 05 §10 (budget semantics, `budget` form, instantiation rule), spec 07 §8.9 (types), spec 07a (instructions), spec 08 §11 (region allocations, `E2104`), spec 11 §8 (deterministic memory bound), `reference/capabilities.md` (`budget`, `alloc_error`, mandatory deterministic scope), `reference/air-features.md`.
## Alternatives considered
- **Cumulative budget** (allocations never returned to the quota): an execution quota rather than a memory limit; fuel already bounds execution. Rejected.
- **Runtime generation checks** for region references: rejected by Q-010.
- **Region allocation through `mut<region>`**: an exclusive borrow per allocation would freeze the region while any allocation is live, so only one allocation could exist at a time. A shared borrow with fresh, disjoint allocation paths keeps allocations independent and still makes `reset`/`destroy` conflict with every live allocation.
- **Uninitialized heap allocation** with initialization tracking per object: more verifier state for little gain at this stage; `own.new`/`own.array` initialize from a value.
- **Implicit default budget in the deterministic profile**: a hidden policy; an explicit limit in the grant is required instead.
## Unresolved questions
- Whether `own<T>` should support moving the value out (`own.take`, freeing the cell) in format 0, or only borrowing and freeing.
- Whether a region should accept its own byte limit at creation in addition to the capability's budget (proposed: no — narrow the capability with `budget` first).