Files
aji/docs/design/hash-map.md
T
dev 89c63c306b cli: add standard hashes and propose owning map contract
Embed std.hash with four ordinary safe byte functions: FNV-1a 64 and
Castagnoli CRC-32C, each with fresh and numeric continuation forms.
Specify exact constants, empty/chunk semantics, arbitrary continuation
states, target-independent numeric results and explicit serialization.
No heap allocation, authority, AIR, verifier or runtime change.

Propose the next U64Map<V> contract: exact key equality, bounded insert,
returned replacement/full ownership, tombstones, moving drain and
failure-preserving peak-charged rehash. Keep general HashMap<K,V> key
hash/equality policy open as Q-037. A checked slot prerequisite confirms
read-only Copy key/state fields over Option<V>, with explicit accounting
for both tags and owning payload cleanup; no map module is registered.

Validation: unit tests, 797 full conformance cases, 12 new fixtures;
all 11 hash cases with per-instruction collection and 12 schedule seeds
across four quanta, plus owning slot collection; 84 source/AIR, package
and hosted CLI checks; independent forward-polynomial CRC and arbitrary
precision FNV oracles for 286 inputs / 1144 results; 95/95 source coverage;
Zig formatting, whitespace and reference generation. Published vectors
come from RFC 9923 and RFC 3720, with explicit numeric/wire conventions.

Reference cost: source excluding AIR 53,993 -> 55,281 cl100k (+2.4%);
Quick Reference 7,747 -> 7,806 (+0.8%); AIR remains 175,736 bytes.
Map design remains outside both bundles. No empirical MCC or native
throughput claim; CRC initially uses eight bit steps per byte.
2026-10-07 00:53:50 +03:00

9.5 KiB

Owning hash map contract proposal

Status: proposed STD-6d design; no map module is implemented or registered yet. Spec 16 defines the available std.hash API only. This document fixes the next implementation scope and review cases; it does not override the specification.

Key policy and scope

The eventual collection gate still requires HashMap<Key, Own>. Current type parameters are types, not hashing/equality operations (spec 15 §15); Copy supplies neither. Source has no callbacks, methods, user traits or value generic parameters. Treating a digest as key identity is incorrect because different keys can collide. Adding a language feature solely to make this API look generic would add more agent concepts before establishing their general value.

Start with std.map.U64Map<V>: exact u64 keys, generic Copy or linear values, existing source primitives only. Users with genuine numeric identifiers can use it directly. Bytes/struct keys cannot be converted to digests and then treated as unique numeric keys; general key hashing/equality is Q-037. Byte-key ownership needs a separate owning representation contract. Do not name this specialization HashMap<K,V> or claim that it satisfies the general-key gate.

Proposed public API

Ten generic functions, each explicitly specialized ::<V>; only new/reserve declare effects [mem.alloc] and take cap<mem.alloc>. All other functions declare effects []. Names/types below are proposed, unavailable calls today.

Function Result/ownership
new<V>(capacity: usize, heap: cap<mem.alloc>) NewResult<V>::ok(U64Map<V>) / err(alloc_error)
len<V>(map: ref<U64Map<V>>) -> usize occupied entries
capacity<V>(map: ref<U64Map<V>>) -> usize guaranteed maximum entries before new-key insert returns full
reserve<V>(map: mut<U64Map<V>>, capacity: usize, heap: cap<mem.alloc>) ReserveResult::ok / err(alloc_error); <= current capacity is an unchanged no-op
insert<V>(map: mut<U64Map<V>>, key: u64, value: V) InsertResult<V>::inserted / replaced(V) / full(V)
contains<V>(map: ref<U64Map<V>>, key: u64) -> bool presence without copying V
get<V: Copy>(map: ref<U64Map<V>>, key: u64) -> std.option.Option<V> copied value or none
remove<V>(map: mut<U64Map<V>>, key: u64) -> std.option.Option<V> moves out value or none; missing key leaves state unchanged
pop<V>(map: mut<U64Map<V>>) -> std.option.Option<Entry<V>> moves out one key/value or none; Entry has key: u64 and value: V
free<V>(map: U64Map<V>) FreeResult<V>::ok / not_empty(U64Map<V>)

Insert first searches for exact key equality. Replacing an existing key succeeds even when full and returns the old complete value; the new input is consumed exactly once. A new key at capacity returns its unchanged input without modifying any slot or metadata. It never allocates or grows. Keys 0 and 2^64-1 are ordinary valid keys, not empty/tombstone sentinels. pop permits explicit cleanup without requiring a Copy value, iterator or returned borrow; no clear/drop helper is planned.

Representation, lookup and accounting

Use initialized buffer<Slot<V>>, with Slot an ordinary struct containing key: u64, state: SlotState and value: Option. SlotState is a Copy enum empty/deleted/occupied. Copy key/state fields remain readable through ref even when V is linear (spec 15 §16); a linear enum containing the key/value would not support observational lookup with existing enum.switch. The representation therefore needs no borrowed-enum or partial-move feature. A capacity N uses exactly 2N physical slots and limits live entries to N. N=0 has zero slots and no live entries; no modulo is evaluated. Capacity multiplication/byte-charge overflow returns existing budget_exceeded, before allocation or mutation. Slot quota includes the key, SlotState tag and Option tag/maximum payload, including vacant/deleted slots; no hidden allocation owns payloads. Manual field construction/mutation must preserve the documented invariant, as for Vec/Deque.

A deterministic hash hashes exactly eight little-endian key bytes using std.hash.fnv1a64; it never hashes host padding or object addresses. Linear probing begins at hash modulo the physical slot count, visits at most that count, and advances with an overflow-free wrapped index. Hash only chooses the probe start; occupied keys always compare by exact u64 equality. Lookup passes deleted slots and stops at empty or after the full bounded probe. Insert remembers the first deleted slot but continues searching for an existing key until empty/end, so deletion cannot create a duplicate. At least half the slots are non-occupied, but deletion may leave no empty slots: deleted-only probe termination must work.

Remove/pop exchange a complete Option for none, set the Copy state to deleted, decrement length and return user ownership. No tombstone compaction is required during remove/pop; this keeps them allocation-free and avoids partial holes. When logically empty, free examines/consumes all physical slots; invalid metadata cannot make it normally discard an occupied value. This is explicit internal cleanup only. pop chooses the first occupied physical index, so order is deterministic for the operation history, not insertion or key order. Rehash may change that order; callers requiring sorted output must sort explicitly.

Reserve first allocates and initializes the whole new table, while the old table and every user owner remain unchanged. Failure refunds temporary storage to its authority and preserves old slots, length, capacity and iteration order exactly. Once allocation succeeds, no recoverable operation may fail: exchange each complete occupied slot into the new table in old physical-index order, then explicitly consume internal none payloads and free old empty/deleted storage. Peak quota includes both full tables plus separately charged user owners. Refund the old table to its recorded authority, even when reserve uses another capability. A successful growth clears tombstones and preserves every key/value association. Do not build this on buffer.reserve alone: rehash needs both old and new layouts until transfer finishes.

Expected probing depends on collisions/history; worst-case lookup/insert/remove is O(N). Pop/empty free inspect O(N) slots. New/reserve perform O(N) slot work, with possible O(N²) rehash collision work and the interpreter's existing prefix-copy overhead. Fixed non-cryptographic FNV is not an adversarial hashing guarantee. Fuel and capacity bound work explicitly; no random seed or ambient entropy is introduced.

Ownership and implementation gate

Preserved invariant: every live entry holds one complete V, occupied count equals length, keys are unique, and each occupied slot is reachable by its probe sequence. Occupied state corresponds exactly to some(V); vacant/deleted states correspond to none and own no V. Unused keys remain initialized Copy values, never identity sentinels. Existing aggregate/enum availability, exchange, slice bounds, mutable exclusion and task-loan rules verify every operation. Runtime uses ordinary deterministic AIR, initialized buffer accounting and no new instruction. No new diagnostic is expected: bad moves/leaks use E7003/E2002/E3002, alias/task conflicts E2101/E4101, Copy/Send/Share restrictions E7005/E4002. User owners, files and endpoints remain subject to ordinary resource/task rules; no destructor closes them. Existing AIR/APIs retain meaning; map support would be an additive registry entry, with its spec/reference delivered alongside code.

The checked slot prerequisite already demonstrates read-only key/state access without consuming an owning payload, complete extraction and explicit cleanup; it does not implement a map. A valid owning use creates U64Map<own>, inserts a moved owner under key 7, handles replaced/full payloads, removes or pops and explicitly consumes the returned owner, then handles empty free. Rejected uses omit the move, ignore a linear replaced/full/pop result, copy an owner through get, free without consuming not_empty, mutate while a slice/task loan exists or share a file-valued map with workers. These become executable conformance examples with the implementation; this proposal is not evidence that they run today.

Before marking the specialization done, test exact collisions, tombstones before matching keys, wraparound, a table with no empty slots, full-table replacement, zero capacity and all scalar keys. Compare mixed operations and all associations with an independent Python dict oracle. Include Copy/owner/file/sender cleanup, repeated reuse, peak-charge failure, exact failure-state preservation, cross-authority refunds and invalid-representation safety. Verify canonical AIR/package/hosted behavior, GC after each instruction and schedules for valid workers. Integrate normative rules in spec 16 and the API reference, register the module, measure bundle costs and report the remaining general-key gate explicitly.

Agent complexity impact

This proposal adds no language concept, verifier state, syntax, diagnostic, callback, trait or runtime feature. The future library adds key equality, probing and returned replacement ownership; the latter reuses existing complete-value patterns. Ten operations avoid independent entry/cursor/borrow lifetimes. Public representation invariants increase documentation needs, so full details belong on demand. This draft stays outside the source/AIR bundles; the runnable hash increment measures its own cost in RFC 0026. No performance or Model Capability Compression result is inferred from the proposal or from benchmark tasks.