11 KiB
id, ticket, title, created, tags
| id | ticket | title | created | tags | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| LSN-0094 | pbs-sdk-map-keyval | Map presence, key identity and captured associations | 2026-10-26 |
|
Map presence, key identity and captured associations
Worker: Lesson Worker. Owner domain: compiler/pbs.
Discussion: DSC-0093, accepted DEC-0079 implemented by PLN-0157 (R1–R12).
The normative contract is SDK Map and Keyval.
The evidence record preserves reproduction commands, source
and fixture fingerprints, raw logs and requirement coverage after housekeeping.
Original problem
Map needed to distinguish association existence from the content of its value, define which object represents an equivalent key, and transport read-only entries without exposing mutable hash storage. Set had already delivered reusable Identity and hashing, while List supplied a shared snapshot Cursor. Neither delivery automatically determined Map's API, representation or mutation guarantees.
The accepted result is a source SDK Map with its own bucket nodes, an ordinary generic Keyval association, optional lookup/previous-value results and independent entry snapshots. The implementation uses existing typed Registry/PBX/VM contracts; the runtime checkout was not modified.
Separate presence from payload
m[key], put(entry) and remove(key) return optional V. The outer optional
answers whether an entry existed. V may itself be optional:
| Stored state | Lookup or previous-value result |
|---|---|
| No association | none |
| Present association, V=none | some(none) |
| Present association, V=some(42) | some(some(42)) |
For example, inside a function:
let scores = new map<str, optional int>();
scores["pending"] = none;
if scores.containsKey("pending") {
if let payload = scores["pending"] {
// payload is optional int and is currently none.
}
}
Assigning none does not remove an entry. remove is the structural operation.
Zero/false are present values, and faults never become none. K directly optional
is rejected consistently with Set; independent keyval<K,V> remains an ordinary
generic struct and can hold optional components. The restriction on
array<optional T> does not prohibit a V field in a private node.
Preserve the stored key representative
Default Identity follows the Set policy: scalar/String values use their specified value domains; eligible objects use instance identity; contracts use their validated receiver. Unsupported defaults require an explicit Identity. V needs no equality/hash capability.
A content strategy can consider distinct objects equivalent. If a map already stores object A and a write supplies equivalent object B, replacement changes only V. A remains the key returned by subsequent snapshots; size and capacity do not change. To make B the representative, remove and reinsert. This rule avoids silently replacing object identity while updating an association's value.
An explicit strategy must remain coherent and stable while keys are stored. Remove keys from affected collections before changing relevant content or policy configuration, then reinsert. Cached hashes do not repair unstable equality.
Keyval is an association, not a storage node
new keyval<K,V>(key, value) constructs a normal generic SDK struct. It has private
fields and only key()/value() accessors, with no mutators. Assignment shares its
instance and payload references. Separately constructed keyvals remain distinct
under default instance identity even when their components match.
Map.put reads those components and returns the previous V. It does not retain the input Keyval as an editable table node. Internal Map nodes store cached long hash, K, mutable V and next link. This keeps storage mutation private and avoids one public Keyval allocation per internally stored association.
Keyval is shallowly read-only: its association is fixed, but referenced objects remain shared and mutable. An old captured value does not follow replacement with a new object; mutating the old object itself is still visible through aliases.
Share policies and helpers without a universal table
Map and Set share Identity, hash primitives, private bucket/size/growth arithmetic and the Cursor implementation. They retain separate node types and algorithms. Map is not implemented over Set or Linked, and there is no universal Element.
Empty Map construction is lazy. First inclusion creates 8 buckets, growth occurs above 3/4 occupancy and doubles up to Array's u32 structural maximum. Chaining may continue above that bucket count within checked signed-long size and provider quotas. Removal does not shrink; clear releases the table and restores lazy state.
Full signed-long hashes select buckets using remainder plus positive correction, without abs or int narrowing. Rehash copies independent topology using cached hashes and complete K/V groups; it never calls Identity or edits old published links during preparation. Old and candidate tables/nodes coexist under normal quota accounting. Search still has a linear worst case.
Capture associations independently of later mutation
Map.cursor returns Cursor<keyval<K,V>>. Each association costs a new Keyval and
an immutable private snapshot node, plus applicable carriers. Capture takes
O(B+N) work and O(N) extra storage, returns only when complete, calls no strategies
and retains no editable Map node or bucket position.
The shared Cursor table is unchanged: current starts on the first captured entry; hasNext tests for a successor; next without one retains the last entry. Only an empty-born Cursor has absent current. Consume current before checking whether to advance.
Later insertion, replacement, removal, clear or rehash cannot rewrite captured associations. Order is unspecified. Consumed prefixes may become unreachable, while the final current remains retained until its Cursor releases it. The real GC corpus observes 1,200 -> 1 -> 1 -> 0 snapshot nodes and Keyvals, retaining 2,400 -> 2 -> 2 -> 0 distinct key/value objects. The Map-node count is zero after capture ownership leaves the source collection, confirming no source-node link.
Prepare even typed absence before structural writes
The quota corpus exposed an easy source-level mistake: return none can lower
to instructions that allocate a private typed-default carrier. Returning it after
inserting a node therefore introduced a fallible allocation after publication,
despite the source text looking like a trivial constant.
The insertion path now prepares the typed absent previous value before structural writes and returns that prepared local afterward. Existing-entry put/remove also prepare their complete optional previous-value carriers before replacement or unlinking. Optimized and ordinary producers qualify these phases independently.
This preparation is not a transaction. Read/write indexing, containsKey, put and remove use a guard against Identity-driven reentry on the same Map, including aliases. clear is also blocked during callbacks; size/isEmpty/cursor may inspect the consistent prior structure. Normal returns release the guard. Callback faults may leave it installed while associations remain unchanged.
Before structural writes, refusal preserves old associations/topology but does not undo callbacks, arguments, guard writes or provisional allocation. After structural writes start, faults may retain earlier writes and incomplete invariants, with no rollback or safe-reuse guarantee. A separate test-only quota probe after candidate-table installation demonstrates table=16/nodes=7 while old size=6 and guard=true. It does not ship in the SDK or represent a natural refusal frequency. Budget/debugger pauses remain resumable instruction boundaries.
Compiler and editor integration pitfalls
- Map keys are K, not positional long indices. Semantic analysis and lowering must select Map handling before Array/List/Linked promotion, passing every key slot.
- Indexed reads are optional V while indexed assignment expects V. Contextual generic construction on a key/value expression must use that operand's expected application, not the outer lookup optional.
- A chained
optionalCall().hasSome()has a boolean outer context, but that must not erase the uniquely resolved optional return or change the receiver's lowering context. This front corrected both resolution and receiver lowering. - Keyval privacy must hold in completion, hover, navigation and signature help,
while private
thisfields remain available inside their owner. Unknown editor receivers must produce no invented members or null-name resolution failures. - Contextual constructors record application provenance on the entire NewExpr span; signature help must resolve that concrete application as well as explicit angular type applications. Imported aliases keep original SDK definitions.
- Generic default constructors must not invalidate explicit-strategy applications for keys without default Identity. Keep K and V restrictions independent.
Qualification and maintenance references
The complete regression and installed-JAR gates passed. Both production runtime profiles executed all 88 mandatory Map PBX fixtures: 64 paired behavior/expected fault cases, 16 natural-resource fixtures, 2 separate injected-fault fixtures, 4 GC fixtures covering both producers and 2 import/installed examples. Each profile observed 328 natural refusals before structural writes, 2 post-publication test injections, 8 snapshot GC observations and 10 collection GC observations.
Qualification is local macOS/arm64 against unchanged provider
dcf6561ea73446e0a3e1cf1c73eda20923b38df0. It does not establish a performance
threshold, other-host qualification or installed game readiness. Existing unrelated
disabled JUnit cases and upstream headless-schema gaps remain explicit in the
evidence and are not counted as new Map conformance.