cli: add safe owning binary heaps

Add std.heap with an exact explicit pure ordering operation, bounded
push, Copy-only peek, moving pop and empty-only free. Sift Copy indices
while complete owners remain in dense initialized storage; repair holes
through complete exchange. Reserve preserves layout on returned failure
and accounts for both old/new buffers and separately owned payloads.

Integrate normative contracts, RFC, references, bundle measurements,
independent heapq/permutation oracles and CLI/package/profile checks.

Validation: 1007 conformance cases; 34 heap GC fixtures and scheduled
stress; unit/Quick Reference, formatting, hosted smoke, 70 CLI checks,
109 source coverage constructs and unchanged AIR reference bundle.
This commit is contained in:
dev committed 2026-10-07 11:41:35 +03:00
1 parent 4114a39846
commit cfece6080c
51 files changed
+2192 -12

No files matched your search

+2
View File
@@ -123,3 +123,5 @@ RFC 0029 static function parameters (cl100k, relative to numeric maps): Quick Re
RFC 0030 general owning HashMap (cl100k, relative to static operations): Quick Reference 8,051 → 8,124 (+0.9%), other source docs 51,002 → 53,363 (+4.6%), full source excluding AIR 59,053 → 61,487 (+4.1%). library/std.md is 16,504 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe source functions use explicit static policies and complete key/value transfer, with no new language form, verifier/runtime state or diagnostic. Cumulative source growth is +80.9%, justified in the RFC without an empirical MCC claim; full policies/failure/dense-index invariants stay on demand.
RFC 0031 general owning HashSet (cl100k, relative to HashMap): Quick Reference 8,124 → 8,201 (+0.9%), other source docs 53,363 → 54,798 (+2.7%), full source excluding AIR 61,487 → 62,999 (+2.5%). library/std.md is 17,939 tokens; AIR remains 179,282 bytes / 51 sections. Nine safe wrappers return duplicate/full incoming keys and transfer stored keys through ordinary ownership rules. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +85.4%, justified by explicit ownership/accounting contracts without an empirical MCC claim.
RFC 0032 owning BinaryHeap (cl100k, relative to HashSet): Quick Reference 8,201 → 8,284 (+1.0%), other source docs 54,798 → 56,770 (+3.6%), full source excluding AIR 62,999 → 65,054 (+3.3%). library/std.md is 19,911 tokens; AIR remains 179,282 bytes / 51 sections. Eight safe source operations bind explicit pure order and sift Copy indices while complete owners remain in initialized storage. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +91.4%, justified by visible ordering/ownership/failure/accounting contracts without an empirical MCC claim.
+2
View File
@@ -367,6 +367,8 @@ The usual enum rules apply: missing arm `E7004`, wrong enum/payload `E7005`, unk
`std.hashset.HashSet<K,fn hash,fn equal>` uses the same policies for complete owning keys. Insert returns `present(input)` for duplicates, preserving the stored key, or `full(input)`; remove/pop move stored keys out. Only new/reserve allocate with explicit authority; free returns nonempty sets. Full contracts are in `/docs/library/std.md`.
`std.heap.BinaryHeap<T,fn before>` binds pure `fn(ref<T>,ref<T>)->bool effects []` as a stable strict weak order. Push returns full input; pop moves the priority root; peek requires T: Copy. Only new/reserve allocate with explicit authority; free returns nonempty heaps. Ties have no stable-order guarantee. Full contracts are in `/docs/library/std.md`.
`std.hash.fnv1a64` and `crc32c` hash byte slices without allocation; their `_extend` forms continue from a previous result. Hashes do not establish key equality or authentication. Exact algorithms and chunk/byte-order conventions are in `/docs/library/std.md`.
## 11. Package modules
+1 -1
View File
@@ -8,7 +8,7 @@ The other files in `/docs` hold the full rules. Open one only when this page is
| Need | Read |
|---|---|
| built-in bytes/math/text/formatting/hash, option/result, owning Vec/Deque, numeric/general maps and general sets, signatures and failure contracts | `/docs/library/std.md` |
| built-in bytes/math/text/formatting/hash, option/result, owning Vec/Deque, numeric/general maps, sets/heaps, signatures and failure contracts | `/docs/library/std.md` |
| initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` |
| whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` |
| generic declarations/applications, property constraints, static function contracts and specialization limits | `/docs/language/generics.md` |
+1 -1
View File
@@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
The [standard-library track](standard-library.md) implements fourteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its final GC/stress validation remains in progress (Q-037). STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. BinaryHeap remains STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
The [standard-library track](standard-library.md) implements fifteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
+17 -7
View File
@@ -20,7 +20,7 @@ Without external source dependencies, Aji should support ordinary CLI tools, sto
|---|---|---|
| Scalars, structs/enums, slices/arrays, explicit borrows | implemented | pure fixed-storage algorithms can start now |
| Heap/regions, I/O, files, TCP, clock/random, structured tasks/channels/mutex | implemented primitives | wrappers can reuse them, but their presence does not imply the complete APIs below |
| Built-in standard imports and enum types | STD-0/1a/2a/2b branch implementation | compiler-pinned, closed registry; fourteen modules; qualified enum types/constructors/patterns; no package lookup |
| Built-in standard imports and enum types | STD-0/1a/2a/2b branch implementation | compiler-pinned, closed registry; fifteen modules; qualified enum types/constructors/patterns; no package lookup |
| General modules/imported struct literals | STD-3 branch implementation (P6-3; RFC Proposed) | explicit manifest mapping, direct qualified names, ordinary verifier |
| User generics/structural constraints | STD-4 branch implementation (P6-4; RFC Proposed) | needed for reusable `Vec<T>`, `HashMap<K,V>`, option/result |
| `linear_aggregates` | STD-5 branch implementation (RFC Proposed) | whole-value owning structs/enums/fixed arrays; initialized buffer<T>/std.vec implemented by STD-6a/b |
@@ -57,13 +57,14 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob
| STD-6a | done (branch implementation; RFC 0024 Proposed) | dynamic initialized buffer<T> storage/drain contract (Q-036) | STD-4/5 | vertical allocate/grow/push/pop/view/free; allocation failures preserve state, returned owners consumed; no hidden destruction |
| STD-6b | done (branch implementation; RFC 0024 Proposed) | safe std.vec for Copy/owners/files/channel endpoints | STD-6a | explicit reserve, bounded push, moving pop/replace, empty-only free; deterministic and failure/cleanup tests |
| STD-6c | done (branch implementation; RFC 0025 Proposed) | safe std.deque for Copy/owners/files/endpoints | STD-6a/b | bounded ring, both ends, failure-preserving explicit growth, complete resource transfer and empty-only free |
| STD-6d | in progress (maps/set implemented; heap and final general-map GC remain) | HashMap, HashSet, BinaryHeap | STD-6a/b/c | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
| STD-6d | done (branch implementations; RFCs Proposed) | HashMap, HashSet, BinaryHeap | STD-6a/b/c | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
| STD-6d.1 | done (branch implementation; RFC 0026 Proposed) | pure std.hash: FNV-1a 64 / CRC32C, fresh/extend | STD-1b | four safe functions, exact byte/chunk conventions, independent public vectors and CLI/profile checks |
| STD-6d.2a | done (branch implementation; RFC 0027 Proposed) | pure built-in error construction prerequisite | STD-6d.1 | vertical error_values feature, no authority/effect/resource changes; preflight allocation validation |
| STD-6d.2 | done (numeric-key branch implementation; RFC 0028 Proposed) | U64Map<V> first; general HashMap<K,V> key policy Q-037 | STD-6d.1 | safe map with ownership/failure/collision tests and error_values prerequisite (RFC 0027); general-key gate remains open |
| STD-6d.2 | done (numeric-key branch implementation; RFC 0028 Proposed) | U64Map<V> first; general HashMap<K,V> key policy Q-037 | STD-6d.1 | safe map with ownership/failure/collision tests and error_values prerequisite (RFC 0027); general-key gate resolved by STD-6d.4/5 |
| STD-6d.3 | done (branch implementation; RFC 0029 Proposed) | explicit static hash/equality/order functions | STD-4 | exact callable contracts, ordinary AIR calls/workers and nominal operation identity; general collections remain required |
| STD-6d.4 | implementation validated; final GC/stress in progress (RFC 0030 Proposed) | general owning HashMap<K,V,H,E> | STD-6d.3 | dense complete entries, Copy probe indices, exact equality and returned key/value ownership |
| STD-6d.4 | done (branch implementation; RFC 0030 Proposed) | general owning HashMap<K,V,H,E> | STD-6d.3 | dense complete entries, Copy probe indices, exact equality and returned key/value ownership |
| STD-6d.5 | done (branch implementation; RFC 0031 Proposed) | general owning HashSet<K,H,E> | STD-6d.4 | exact membership, duplicate/full input ownership, moving extraction and empty-only free |
| STD-6d.6 | done (branch implementation; RFC 0032 Proposed) | owning BinaryHeap<T,B> | STD-6a/6d.3 | explicit pure order, complete resource extraction, bounded push, failure-preserving growth |
| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
| STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry |
| STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material |
@@ -139,16 +140,25 @@ RFC 0024 records storage/Vec validation. RFC 0025 records the deque API/budget m
## Hash foundation and next map contract
STD-6d.1/RFC 0026 adds safe std.hash with four byte-only fresh/continuation operations, no new semantics or heap authority. FNV/CRC constants and public vectors are independently verified; hashes never replace key equality. [The map design](../design/hash-map.md) specifies numeric-key U64Map<V>, bounded insert, returned replacement/full ownership, tombstone lookup, moving removal/drain and explicit peak-charged rehash. STD-6d.2/RFC 0028 implements safe std.map.U64Map<V> with ten operations, using explicit error construction (RFC 0027) for preflight validation. Independent dictionary traces, collision/tombstone/wrap cases, exact peak/refund accounting, owning/files/sender/task tests and rejected leaks/aliases/Copy uses cover the contract. Q-037 keeps general key policy explicit; HashMap<Key, Own<Value>>/HashSet/BinaryHeap remain required by STD-6d.
STD-6d.1/RFC 0026 adds safe std.hash with four byte-only fresh/continuation operations, no new semantics or heap authority. FNV/CRC constants and public vectors are independently verified; hashes never replace key equality. [The map design](../design/hash-map.md) specifies numeric-key U64Map<V>, bounded insert, returned replacement/full ownership, tombstone lookup, moving removal/drain and explicit peak-charged rehash. STD-6d.2/RFC 0028 implements safe std.map.U64Map<V> with ten operations, using explicit error construction (RFC 0027) for preflight validation. Independent dictionary traces, collision/tombstone/wrap cases, exact peak/refund accounting, owning/files/sender/task tests and rejected leaks/aliases/Copy uses cover the contract. Q-037 is now resolved by STD-6d.4/5; general HashMap<Key, Own<Value>>/HashSet and BinaryHeap validation are recorded below.
## General operation-selection prerequisite
STD-6d.3/RFC 0029 implements explicitly bound static functions with exact typed/effect contracts, forwarding, generic function arguments, nominal operation identity and named workers. It reuses ordinary AIR and preserves direct-import visibility, capability inputs, ownership and task loans. Source/AIR positives/rejections, recursive/cyclic contracts, GC/scheduler stress, CLI/profile/provenance checks and documentation budgets are recorded in the RFC. General HashMap/HashSet storage/API remains Q-037; BinaryHeap and STD-7 are still required.
STD-6d.3/RFC 0029 implements explicitly bound static functions with exact typed/effect contracts, forwarding, generic function arguments, nominal operation identity and named workers. It reuses ordinary AIR and preserves direct-import visibility, capability inputs, ownership and task loans. Source/AIR positives/rejections, recursive/cyclic contracts, GC/scheduler stress, CLI/profile/provenance checks and documentation budgets are recorded in the RFC. General HashMap/HashSet storage/API subsequently resolves Q-037, and BinaryHeap completes STD-6d; STD-7 remains required.
## General owning set verification
STD-6d.5/RFC 0031 implements safe HashSet<K,H,E> over the general map, with nine explicit operations. Duplicate insertion preserves every stored entry/bucket and returns the exact incoming key, including its resources; full does likewise for new keys. Remove/pop transfer complete stored keys, and nonempty free returns the whole set. Allocation, failure rollback, peak/refund accounting and dense pop order follow the map. No new language syntax, verifier/runtime state, diagnostic, AIR feature or trusted boundary is added.
All 973 conformance cases pass, including 26 set cases. Runtime fixtures pass collection before every instruction; the shared lookup fixture passes 12 seeds under quanta 1, 2, 7 and its own quantum. Independent Python set/representative oracles cover 80 operations across Copy/owning traces and check membership after each operation. Byte-buffer/file keys, exact duplicate-table preservation, returned owners, allocation failure/refunds/peaks and rejected leaks/moves/aliases/loans/policies/non-Share contents are covered. Unit/Quick Reference, formatting, hosted smoke, 53 CLI/profile/package/source/AIR checks, 106/106 source coverage constructs and bundle generation pass. RFC 0031 records documentation growth. The separate general-map full GC/stress process remains pending; BinaryHeap is the next collection increment, followed by STD-7 I/O/path.
All 973 conformance cases pass, including 26 set cases. Runtime fixtures pass collection before every instruction; the shared lookup fixture passes 12 seeds under quanta 1, 2, 7 and its own quantum. Independent Python set/representative oracles cover 80 operations across Copy/owning traces and check membership after each operation. Byte-buffer/file keys, exact duplicate-table preservation, returned owners, allocation failure/refunds/peaks and rejected leaks/moves/aliases/loans/policies/non-Share contents are covered. Unit/Quick Reference, formatting, hosted smoke, 53 CLI/profile/package/source/AIR checks, 106/106 source coverage constructs and bundle generation pass. RFC 0031 records documentation growth. The separate general-map full GC/stress process subsequently completed with all 33 cases passing. BinaryHeap validation follows below; STD-7 I/O/path is next.
## Owning binary heap verification
STD-6d.6/RFC 0032 implements eight safe std.heap operations with an exact explicit pure ordering function. Copy-index sifting preserves complete owners in dense initialized storage; moving pop repairs dense holes. Full push returns its input without callbacks, nonempty free returns the heap, and explicit reserve preserves values/layout/extraction order on every returned allocation failure. No new source/AIR semantics, diagnostics, verifier/runtime state or trusted boundary are added.
All 1007 conformance cases pass, including 34 heap fixtures. Heap runtime fixtures pass collection before every instruction; shared lookup, sender ownership transfer and restored task loans run 12 schedule seeds under quanta 1, 2, 7 and their own quantum. Independent heapq traces cover 160 operations over min/Copy and max/owning records, plus all 120 permutations of five values. Direct owners, owning byte buffers, files, sender endpoints, duplicates, empty/full/overflow, exact layout preservation under both reserve-failure phases, peaks/refunds/cross-authority accounting and rejected leaks/Copy/aliases/loans/policy/effects are covered. Unit/Quick Reference, formatting, hosted smoke, 70 CLI/source/AIR/package/profile/provenance checks, 109/109 source coverage constructs and bundle generation pass. RFC 0032 records documentation growth.
The long general-map GC/stress process also completed with 33/33; Q-037 and the collection gate STD-6d are resolved on this branch. I/O and lexical paths are STD-7; filesystem gaps, args/env and logs remain STD-8. This does not complete Std 0.1 or reopen the native backend phase.
+27 -2
View File
@@ -1,8 +1,8 @@
# Standard library API
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map/std.hashmap/std.hashset new/reserve.
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve.
Except std.vec/std.deque/std.map/std.hashmap/std.hashset new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
Except std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
| Module | Function signature | Result/failure |
|---|---|---|
@@ -348,3 +348,28 @@ Here HashSet abbreviates the applied type. Duplicate insertion preserves the sto
Only new/reserve allocate with mem.alloc and explicit authority. There is no automatic growth or cleanup. The visible representation is `map: std.hashmap.HashMap<K,bool,fn hash,fn equal>` with every live value true; callers must preserve spec 16 §2.15's complete invariant. Dense extraction/pop order, failure preservation, peak accounting and refunds follow the map. Each capacity slot charges hash + K + bool and two buckets: 51 bytes for u64, or 59 for Key{id:u64,owner:own<u64>}, plus the separately allocated payload. The [owning example](../../examples/std/hashset.aji) returns 42 with heap=mem.alloc:67.
Policies may run for membership and again for insertion, with no runtime dispatch or gained authority. Existing moves/aliases/task loans and Copy/Send/Share checks apply. Callback traps/fuel exhaustion are abnormal outcomes. Worst-case membership/insert/remove/pop is O(N) plus callbacks; growth is O(N²) under collisions. No sorted iteration or native-throughput guarantee is made.
## Owning binary heaps
Import `std.heap` and `std.option`. `BinaryHeap<T,fn before>` stores complete T with an explicit exact `fn(ref<T>,ref<T>) -> bool effects []` operation. before(a,b) means a has higher extraction priority. It must remain a stable strict weak order: irreflexive/transitive, with transitive incomparability. Equivalent items have deterministic extraction for a fixed operation sequence, without a stable tie-order promise. Use `<` for numeric minimum first or `>` for maximum first. Distinct bound operations give distinct nominal types; selection grants no authority.
Every call supplies `::<T,fn before>`; peek additionally requires T: Copy:
| Function arguments | Result |
|---|---|
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<T,fn before>: ok(BinaryHeap), err(alloc_error) |
| len(value: ref<BinaryHeap>) | usize live count |
| capacity(value: ref<BinaryHeap>) | usize maximum live count |
| reserve(value: mut<BinaryHeap>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
| push(value: mut<BinaryHeap>, item: T) | PushResult<T>: ok, full(T) |
| peek(value: ref<BinaryHeap>) | std.option.Option<T> copied root |
| pop(value: mut<BinaryHeap>) | std.option.Option<T> moving root extraction |
| free(value: BinaryHeap) | FreeResult<T,fn before>: ok, not_empty(BinaryHeap) |
Here BinaryHeap abbreviates the applied type. Use move for named linear inputs, mut for push/pop/reserve and ref for queries (ref q through a mut parameter). Full push preserves all state, returns the original input and calls no comparator. Empty pop/peek returns none; nonempty free returns the whole heap. Explicitly consume owning full/pop/not_empty results. Peek retains no borrow and cannot copy an owner; complete owning records, files and sender endpoints use pop. Only new/reserve allocate with mem.alloc and explicit authority; growth is never automatic.
The visible representation is entries: buffer<Entry<T>> / indices: buffer<usize>, Entry<T>{position:usize,value:T}. Both initialized lengths/capacities agree. Indices are a permutation of dense positions; each entry points back to its index position, and no child precedes its parent. Callers must preserve spec 16 §2.16's complete invariant. Sifting swaps Copy indices and inverse positions; pop repairs the dense hole through complete exchange. No default T or implicit destruction is needed.
New allocates empty entries then indices, refunding entries on second-allocation failure. Reserve allocates/copies new indices before growing entries; returned failure preserves both old buffers, values/positions/indices and extraction order, and refunds temporaries. Success preserves the layout and frees old indices explicitly. Peak quota includes both entry/index buffers and all external user allocations; refunds go to recorded authorities. Zero capacity is valid; size overflow returns budget_exceeded. On air64 each capacity slot costs sizeof(T)+16 bytes. The [owning example](../../examples/std/heap.aji) needs 32 bytes for one Item slot plus 8 for its payload: heap=mem.alloc:40.
Existing ownership/alias/task-loan/Send/Share rules apply with no unsafe boundary or new runtime semantics. Callback/fuel traps are abnormal. Abstract push/pop need O(log L) comparisons/swaps, peek O(1), reserve O(L) copies; interpreter prefix-copy/GC costs may add host work. There is no native-throughput guarantee.
+47
View File
@@ -0,0 +1,47 @@
# RFC 0032: Safe owning binary heap
Status: Proposed
Scope: STD-6d.6, safe library source after RFCs 0024/0029
## Motivation and normative changes
Spec 16 §2.16 supplies a bounded priority queue for arbitrary complete T with one explicit pure ref-value ordering operation. Copy and owning values share the same API and safe implementation. Ownership, allocation/failure and ordering contracts are visible to the verifier and caller.
## Preserved invariant
Dense entries own each live T exactly once. A Copy index permutation and inverse positions describe the heap; no child precedes its parent. Unused capacity owns no T. Callback laws are a stable strict weak order. Full push and every returned allocation failure preserve all state, and returned resources are explicitly consumed.
## Verifier / runtime rules
No new transfer function or runtime rule. Existing complete buffer/aggregate moves, exchange, ref/mut exclusion, task loans, exact static callable contracts, bounds, effects, Copy/Send/Share and consumption apply. Indices sift while owners remain in initialized storage; complete pop/exchange repairs a dense hole. All code is safe Aji lowering to ordinary AIR. Callback/fuel traps are abnormal; normal failures preserve layout/extraction order and refund recorded allocation authorities.
## Valid and rejected examples
An owning record orders by a Copy priority field. Push consumes the record; full returns it; pop moves it out for complete unpack and explicit resource consumption; nonempty free returns the whole heap. A Copy heap may peek; attempting peek of an owning T, ignoring full/pop/nonempty-free owners, missing move, borrowing across mutation/task loans, mismatched ordering policies/effects or sharing non-Share resources MUST reject through existing diagnostics. Executable examples and validation results are recorded below.
The [checked owning example](../../examples/std/heap.aji) moves a priority/owner record into one slot, pops/unpacks/takes the payload and frees the empty heap with a 40-byte grant. [Owning peek](../../tests/conformance/source/heap/peek_owner.aji) rejects E7005; [a leaked full return](../../tests/conformance/source/heap/full_leak.aji) rejects E3002; [a live task loan](../../tests/conformance/source/heap/loan.aji) rejects E4101. [Corrupt indices](../../tests/conformance/source/heap/invalid_indices.aji) trap T0008 through ordinary bounds checks, preserving safe-code memory safety.
## Diagnostics / compatibility / AIR
No new diagnostic, instruction, AIR feature, source syntax or verifier/runtime state. E7003/E7005, E3002, E2101/E4101, E3101 and E4001/E4002 remain ordinary checks. Addition of std.heap is compatible with existing modules and AIR format 0; imports grant no authority. No implicit allocation/destructor or unsafe/trusted boundary is introduced.
## Agent complexity impact
One strict-weak-order precondition, already expressible with static operation selection, plus an explicit priority-queue invariant. Eight operations mirror existing bounded containers; no inferred comparator, convenience auto-growth, borrowed-return facility or stable-sort concept. The Copy-only peek restriction follows existing lookup contracts. Dense/Copy-index storage avoids a new owner-swapping primitive, borrowed enum payloads or holes. Verifier state and syntax are unchanged; Quick Reference and full source documentation growth are measured below. No empirical MCC benefit is claimed.
Measured cl100k growth from RFC 0031: Quick Reference 8,201 → 8,284 (+1.0%); other source documentation 54,798 → 56,770 (+3.6%); full source excluding AIR 62,999 → 65,054 (+3.3%). library/std.md is 19,911 tokens. o200k groups are 8,317 / 56,955 / 65,272; qwen2.5 groups 8,534 / 58,278 / 66,812. AIR stays 179,282 bytes / 19 files / 51 sections; its source-bundle copy stays 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k growth over the 33,981 pre-std baseline is +91.4%, justified by the owning priority queue and explicit ordering/representation/failure/budget contracts. No new language form, verifier state or diagnostic; the Quick Reference has one short paragraph and full contracts stay on demand. Existing primitives suffice without changing AIR.
## Alternatives
Copy-only array heaps fail the owning resource gate. A vacancy/default T loses generality. Direct swapping owners could use extra scratch rotations, but adds transient value movement and proof complexity. Two initialized buffers make permutation swaps and complete extraction explicit with a documented 16-byte per-capacity metadata cost on air64. Opaque runtime collection magic enlarges the trusted boundary unnecessarily.
## Validation gate
Independent Python priority-queue traces; ascending/descending order, duplicate priorities, complete owning/files/endpoint values, dense-hole repair, empty/zero/full, capacity overflow, both allocation failure phases, exact peak/refunds/cross-authority accounting, rejected leaks/aliases/loans/Copy/effect/policies; source/AIR/package/profile consistency; GC and scheduler stress; unit/Quick Reference, formatting, full conformance, source coverage and reference budgets. I/O/path remain subsequent increments.
## Validation result
All 1007 conformance cases pass, including 34 heap fixtures. All runtime heap fixtures pass collection before every instruction; shared read-only lookup, sender heap transfer and task-loan restoration run 12 seeds under quanta 1, 2, 7 and their own quantum. Independent Python heapq oracles cover 160 min/Copy and max/owning operations; sorted oracles check all 120 permutations of five elements. Tests cover duplicate priorities, dense-hole repair, direct own<u64>, owning byte buffers, files/endpoints, returned full/pop/nonempty-free ownership, empty/zero/overflow, both growth failure phases, complete layout preservation, exact peak/refund and cross-authority accounting, absence of full-push callbacks and bounds traps for invalid representation. Existing diagnostics reject leaks/missing move/Copy/aliases/loans/effects/policies/non-Share sharing.
Unit/Quick Reference, formatting, hosted smoke, bundle generation, 109/109 source coverage constructs and 70 CLI checks pass. CLI checks compare source/AIR/profile/package behavior, reordered imports, audit output, selected-comparator provenance and std bounds-trap locations. The separate general-map GC/stress process also completed with 33/33, closing Q-037. Collections STD-6d are implemented and validated on this branch; Std 0.1, I/O/path and system adapters remain unfinished.
+32 -1
View File
@@ -10,7 +10,7 @@ APIs SHOULD offer one canonical operation for a common need, small documentation
## 2. Bootstrap module registry
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.hash`, `std.hashmap`, `std.hashset`, `std.map`, `std.math`, `std.option`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/hash.aji`, `std/hashmap.aji`, `std/hashset.aji`, `std/map.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque/std.map/std.hashmap/std.hashset declare effects [] and allocate no heap memory. std.vec/std.deque/std.map/std.hashmap/std.hashset new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13–§2.15); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.hash`, `std.hashmap`, `std.hashset`, `std.heap`, `std.map`, `std.math`, `std.option`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/hash.aji`, `std/hashmap.aji`, `std/hashset.aji`, `std/heap.aji`, `std/map.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap declare effects [] and allocate no heap memory. std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13–§2.16); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
### 2.1 `std.math`
@@ -285,3 +285,34 @@ Only new/reserve declare mem.alloc and take explicit heap authority. Insert chec
New/reserve failure, peak quota/refund, zero capacity, probing, collision equality, callback/fuel traps and visible representation invariants are exactly §2.14's rules. Each capacity slot charges hash plus complete K plus bool, and two buckets: for K=u64, N charges 51N bytes; separately owned K allocations remain separately charged. insert MAY evaluate H/E for membership and again for bounded map insertion; these pure stable operations grant no authority and cannot be inferred away. Once membership says absent, map replacement is unreachable under the valid representation/hash/equality laws; invalid laws may trap under ordinary abnormal-path semantics.
Existing buffers/aggregates/borrows, static callable identity, effects, Copy/Send/Share and ownership verification suffice. No new syntax, diagnostic, feature/opcode, verifier/runtime state, implicit allocation/destructor or trusted boundary is added. Deterministic/hosted behavior agrees and existing APIs/AIR meanings remain unchanged. Worst-case insertion/membership/removal/pop is O(N) plus callback work; growth is O(N²) worst-case collision work with existing interpreter prefix-copy costs. No sorted output, adversarial collision bound or native throughput promise is added.
### 2.16 `std.heap`: bounded owning binary heap
The registry MUST include std.heap at std/heap.aji, ordinary safe source. `BinaryHeap<T,B>` binds an explicit static `B: fn(ref<T>,ref<T>) -> bool effects []` (spec 15 §18), applied as `BinaryHeap<T,fn before>` and `::<T,fn before>`. T MAY contain owners, files or endpoints under ordinary member/Send/Share rules. Distinct bound operations give distinct nominal heap types. No default T, captured environment, runtime dispatch or implicit cleanup is added.
B(a,b) means a MUST precede b. B MUST be a stable strict weak order on live values: irreflexive and transitive, with transitive incomparability. Equivalent values have neither B(a,b) nor B(b,a); their extraction order is deterministic for a fixed operation sequence but MUST NOT be assumed stable. Changing a live value's relative order violates the representation precondition. Pure callbacks grant no authority; callback traps/fuel exhaustion are abnormal outcomes, with no returned-state preservation promise.
Eight operations use the two ordered arguments above; peek additionally requires T: Copy:
| Operation | Result / transfer |
|---|---|
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<T,B>: ok(BinaryHeap<T,B>), err(alloc_error) |
| len(value: ref<BinaryHeap<T,B>>) -> usize | live count |
| capacity(value: ref<BinaryHeap<T,B>>) -> usize | maximum live count |
| reserve(value: mut<BinaryHeap<T,B>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
| push(value: mut<BinaryHeap<T,B>>, item: T) | PushResult<T>: ok, full(original_input_T) |
| peek(value: ref<BinaryHeap<T,B>>) -> std.option.Option<T> | Copy root value, or none |
| pop(value: mut<BinaryHeap<T,B>>) -> std.option.Option<T> | moving extraction of root, or none |
| free(value: BinaryHeap<T,B>) | FreeResult<T,B>: ok, not_empty(BinaryHeap<T,B>) |
Only new/reserve declare mem.alloc and take explicit allocation authority. Push is bounded: full MUST preserve all state, return the exact input and evaluate no ordering callback; it never grows. Successful push/pop MUST restore the heap invariant; pop returns the root that preceded the operation, or none without mutation when empty. Peek copies only Copy T and retains no borrow. Nonempty free MUST return the complete unchanged heap. Every owning full/pop/not_empty result MUST be explicitly consumed.
The visible representation is `BinaryHeap<T,B> { entries: buffer<Entry<T>>, indices: buffer<usize> }`, `Entry<T> { position: usize, value: T }`. Both initialized lengths are L and capacities N, with L≤N. Indices form a permutation of 0..L; entries[indices[p]].position MUST equal p. For every nonroot p, B(value_at(p),value_at((p-1)/2)) MUST be false. Values are owned exactly once in the initialized dense prefix; unused capacity contains no live T. Copy indices permit sifting without copying owners, holes, temporary default values or borrowed enum payloads. Caller construction/mutation MUST preserve the complete invariant.
Push appends a complete entry and its Copy index, then sifts upward by swapping Copy indices and repairing positions. Pop removes the final Copy index, installs it at the root when nonempty, then sifts downward: compare the children, choose right only when it strictly precedes left, and swap only when the chosen child strictly precedes its parent. After ordering, pop the last dense entry; if it is not the removed root, exchange it into that dense hole and repair its Copy heap index using its recorded position. Return the complete removed T. Bounds and parent/child arithmetic MUST be checked before accesses; the nonleaf condition p<L/2 permits 2p+1 without overflow. No retained view escapes.
New allocates empty entries then empty indices; a returned second-allocation failure MUST free the temporary empty entries and refund its recorded authority. Zero capacity is valid. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate a new index buffer and copy the old live indices before ownership-preserving buffer.reserve on entries. Any returned failure MUST drain/free temporary Copy indices, preserve both original buffers, all values/positions/indices and extraction order, and refund temporary charges. After entries reserve succeeds, exchange the new indices into place and explicitly drain/free the old Copy indices; no callback or further recoverable allocation occurs. Growth preserves the heap layout and never shrinks.
Each capacity slot charges usize + complete T for Entry and usize for the index. On air64, T=u64 or own<u64> reserves 24N bytes, with separately owned payloads charged independently. Peak growth includes old/new entries, old/new indices and all user-owned allocations. Refunds follow each buffer's recorded authority, including growth through a different capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded.
Existing buffer/aggregate transfer/exchange, static contracts, borrow/task-loan exclusion, bounds, effects, Copy/Send/Share and resource verification suffice. Valid representations/successful callbacks do not trap during bookkeeping. Existing source/AIR meanings are unchanged; no new syntax, diagnostic, AIR feature/instruction, verifier/runtime state or trusted boundary is added. Deterministic/hosted behavior agrees. Abstract push/pop perform O(log L) comparisons and index swaps, peek is O(1), reserve copies O(L); interpreter prefix-copy/GC costs may add host work. No native-throughput or stable tie-order promise is made.