11 KiB
Owning hash map design
Status: STD-6d.2 numeric-key and STD-6d.4/5 general-key branch implementations validated (RFCs 0028/0030/0031 Proposed); Q-037 resolved. Spec 16 §2.13–§2.15 is normative for std.map/std.hashmap/std.hashset. This document records design rationale and does not override the specification.
Key policy and scope
The eventual collection gate still requires HashMap<Key, Own>. At the numeric-map decision, type parameters supplied no hashing/equality operations (spec 15 §15); Copy supplies neither. RFC 0029/spec 15 §18 now supplies explicit static functions without runtime callbacks, methods, user traits or captured values. 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.
The initial branch increment was std.map.U64Map<V>: exact u64 keys, generic Copy or linear values, initialized buffer primitives and explicit error construction (RFC 0027). 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 was Q-037, now resolved by explicit static policies and dense complete owning entries (spec 16 §2.14–§2.15). Byte-key ownership uses that general owning representation contract. Do not name this specialization HashMap<K,V> or claim that it satisfies the general-key gate.
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 []. The numeric-key names/types below are implemented on the branch; spec 16 §2.13 is authoritative.
| 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 is 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. Executable valid/rejected examples are in tests/conformance/source/map; RFC 0028 records validation.
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
The numeric-key library adds no map-specific language concept, verifier state, syntax, diagnostic, callback, trait or runtime feature. Its separately implemented error construction prerequisite is RFC 0027. Key equality, probing and returned replacement ownership reuse 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 design stays outside the source/AIR bundles; RFC 0028 measures the normative API cost. No performance or Model Capability Compression result is inferred from fixtures or benchmark tasks.
General-key implementation
RFC 0030/spec 16 §2.14 introduces separate std.hashmap so std.map's numeric signatures remain compatible without overloads. Explicit H/E contracts support arbitrary complete owning keys and values. Dense initialized StoredEntry<K,V> slots plus Copy bucket indices permit shared key borrows, avoiding vacancy/default keys and borrowed-enum/partial-move features. Replacement returns the entire previous key/value; full returns the entire input pair. Removal exchanges the last entry into the hole and repairs its index; pop is reverse current dense order. Growth initializes new indices first, then uses failure-preserving buffer.reserve, rehashes cached hashes and frees old indices. This keeps failure exact while charging both layouts at the peak. The full library contract, rather than this historical numeric design, is normative. HashSet and BinaryHeap are later increments.