Files
aji/docs/spec/03-memory-model.md
T
dev 48bb50724f spec: accept RFC 0005 and integrate Phase 1 memory model (P1-1, P1-2)
- RFC 0005 Accepted (revision 2)
- spec 07 §8.8 types and syntax; spec 07a contracts for features
  ownership and arrays; spec 08 §11-§14 borrows, facts, initialization,
  stage order; spec 03 frame storage, second-class borrows, static
  region generations
- grammar: from-returns, multi-result, new types and opcodes
- feature registry: ownership and arrays published; heap added and
  regions moved to Phase 2; borrow_joins reserved and unscheduled
- codes E2105-E2108, T0008
- Q-009, Q-010 resolved; Phase 1 and Phase 2 plans updated; Own test
  moved to phase 2
2026-10-04 13:10:08 +03:00

286 lines
7.6 KiB
Markdown

# 03. Memory and Ownership Model
This file is normative. Rationale is in RFC 0001.
## 1. Goals
Aji memory management must provide:
- memory safety without tracing GC;
- no implicit allocation;
- stable, inspectable ownership transitions;
- efficient bulk allocation;
- efficient transfer of complex mutable graphs between tasks;
- verifier-friendly alias rules;
- explicit boundaries for unsafe pointer work.
## 2. Core forms
```text
Own<T> individually owned dynamic allocation
Region bulk allocation/lifetime domain
Island<T> uniquely owned closed mutable graph
Frozen<T> deeply immutable graph
Arc<T> explicit shared ownership of Share data
ref<T> immutable borrow
mut<T> exclusive mutable borrow
Uninit<T> allocated but not yet initialized
addr<T> unsafe raw address
```
## 3. Safe-reference aliasing rule
For overlapping storage, safe code permits either:
```text
N immutable borrows: ref<T>
```
or:
```text
1 exclusive mutable borrow: mut<T>
```
but never both at the same time.
The verifier enforces the rule across control flow and task scopes.
## 4. Borrow lifetime
A borrow cannot outlive the storage from which it was derived.
Source syntax may infer local borrow lifetimes. Public APIs whose output lifetime depends on input lifetime must express the relationship.
Conceptually:
```aji
fn first<'a, T>(values: slice<'a, T>) -> Option<ref<'a, T>>
```
In AIR, borrows are second-class (spec 07 §8.8): they live only in SSA values and call arguments, never in aggregates, and a function returns a borrow only with an explicit `from %param` naming the borrow parameter it derives from (spec 08 §11.3). Every borrow created in a function is ended explicitly on every normal path (`borrow.end`). Source-level lifetimes lower to this form; source programs that need more are rejected by the frontend.
## 5. Provenance
Every safe reference has logical provenance including:
- originating allocation or region allocation;
- region generation if applicable;
- byte bounds;
- alignment guarantee;
- access mode.
Safe code cannot create a reference from an integer.
Safe pointer arithmetic cannot create a reference outside the originating allocation.
## 6. Stack storage
Normal locals live in the current activation frame.
Their references cannot escape the frame unless the language proves that the target execution context completes before the frame ends, as with structured child tasks.
In AIR, frame storage is `local.alloc`, permitted only in a function's entry block so the frame size is known before execution and bounded (spec 08 §11.5). A borrow derived from frame storage never leaves its call (`E2108`, spec 08 §11.3).
## 7. Own<T>
`Own<T>` is a move-only handle to an individually allocated object.
```aji
let node: Own<Node> = heap.alloc<Node>(alloc_cap)?;
```
Allocation MUST be explicit and fallible unless an explicitly trapping allocation primitive is used.
Access occurs through borrows:
```aji
borrow node as ref n { inspect(n); }
borrow node as mut n { n.value = 42; }
```
Deallocation consumes the owner:
```aji
heap.free(move node);
```
## 8. Regions
A `Region` owns many allocations and releases them collectively.
```aji
let r = region.create(allocator, limit = 16 MiB)?;
let n = region.alloc<Node>(mut r)?;
```
Individual region allocations are not freed separately.
A region may be reset or destroyed.
```aji
region.reset(mut r);
region.destroy(move r);
```
### 8.1 Region generations
A reset logically increments the region generation.
Any borrow or reference associated with a prior generation becomes invalid. Generations are checked statically only: a region cannot be reset or destroyed while a borrow derived from it is live, and use of a borrow from a prior generation is rejected (`E2104`). Safe code performs no runtime generation checks. Cyclic or arena-style graphs use `Island<T>` or indices (§14). (Decision Q-010; specified with the `regions` feature in Phase 2.)
### 8.2 Reset precondition
Reset MUST be rejected when an externally usable safe reference to the current generation remains live.
## 9. Slices
A safe slice logically contains:
```text
provenance + base + length
```
Immutable slice:
```text
slice<T>
```
Exclusive mutable slice:
```text
slice_mut<T>
```
Indexing is bounds checked unless eliminated by proof.
Non-trapping access returns `Option`.
### 9.1 Disjoint partitioning
Verifier-recognized operations such as:
```aji
let (left, right) = slice.split_mut(data, mid);
```
establish that the output regions do not overlap. This fact may justify concurrent mutable access.
## 10. Initialization policy
Allocation does not imply initialization unless the operation says so.
Examples:
```text
region.alloc_uninit<T> uninitialized
region.alloc_zeroed<T> byte-zero initialized where valid for T
region.alloc_value(value) initialized from explicit value
```
Zeroing is never silently inserted as a consequence of allocation.
## 11. Uninitialized memory
Uninitialized storage has type `Uninit<T>`.
It cannot be read.
A write that fully initializes storage changes its verifier state to initialized storage.
For arrays/buffers the verifier may track initialized prefixes or ranges.
## 12. Island<T>
An `Island<T>` is a uniquely owned, closed, transferable graph of mutable memory.
An island consists of:
- a root object of type `T`;
- one or more private allocation regions;
- internal references between island objects.
Properties:
- move-only ownership;
- mutable by the current owner;
- no external mutable aliases;
- no references from the island into ordinary foreign mutable memory, except explicitly modeled transferable capabilities;
- transferable between tasks without deep copy.
### 12.1 Internal references
Island graphs use verifier-recognized `iref<T>` handles for graph edges.
`iref<T>`:
- may point only inside the same island;
- may represent cycles;
- cannot be dereferenced without access to the owning island;
- cannot escape as a standalone safe reference.
### 12.2 Transfer
Moving an island into a channel or task transfers graph ownership.
After successful transfer the sender cannot access the island.
The operation is intended to be O(1) with respect to graph size.
## 13. Frozen<T>
`Frozen<T>` is a deeply immutable graph.
An island may be irreversibly frozen:
```aji
let immutable = island.freeze(move mutable_graph);
```
After freeze, no mutable reference may ever be obtained through safe Aji.
`Frozen<T>` is `Share` and `Send` when contained external resources permit sharing.
## 14. Arc<T>
`Arc<T>` provides explicit shared ownership for `Share` values.
Reference-count manipulation is explicit:
```aji
let another = arc.clone(config);
```
No operation silently increments a reference count.
Aji does not recommend `Arc` for arbitrary cyclic object graphs. Cycles should normally be represented inside an `Island<T>` or through stable handles/indices.
## 15. Stable addresses and pinning
Region and island allocations are address-stable until reset/destruction.
For individually owned objects that require address stability, Aji may provide `Pin<T>`.
Pinning is required for selected FFI, DMA and self-referential runtime structures.
## 16. Raw addresses
`addr<T>` is unsafe-only.
Raw addresses may be null, outlive safe lifetimes, perform arithmetic and cross FFI boundaries.
Dereference requires unsafe code and documented proof obligations.
## 17. Unsafe memory obligations
Unsafe code is responsible for establishing:
- allocation validity;
- alignment;
- initialization;
- lifetime;
- provenance assumptions required by the backend;
- aliasing discipline;
- synchronization where memory is shared concurrently.