# 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 individually owned dynamic allocation Region bulk allocation/lifetime domain Island uniquely owned closed mutable graph Frozen deeply immutable graph Arc explicit shared ownership of Share data ref immutable borrow mut exclusive mutable borrow Uninit allocated but not yet initialized addr unsafe raw address ``` ## 3. Safe-reference aliasing rule For overlapping storage, safe code permits either: ```text N immutable borrows: ref ``` or: ```text 1 exclusive mutable borrow: mut ``` 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> ``` 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 `Own` is a move-only handle to an individually allocated object. ```aji let node: Own = heap.alloc(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(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` 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 ``` Exclusive mutable slice: ```text slice_mut ``` 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 uninitialized region.alloc_zeroed 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`. 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 An `Island` 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` handles for graph edges. `iref`: - 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 `Frozen` 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` is `Share` and `Send` when contained external resources permit sharing. ## 14. Arc `Arc` 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` 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`. Pinning is required for selected FFI, DMA and self-referential runtime structures. ## 16. Raw addresses `addr` 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.