--- id: LSN-0093 ticket: pbs-sdk-set title: Reusable identity and source Set buckets created: 2026-10-25 tags: [compiler-pbs, collections, hashing, identity, runtime-integration] --- ## Original problem and ownership Owner: `compiler/pbs`; propagation: `compiler` and `vm-arch`. Set needed a precise equality policy before membership could become an executable SDK algorithm. Mutable objects must retain instance identity by default, while an explicit strategy can intentionally merge distinct objects by content. Importing hash metadata alone did not make source hashing, typed reference queries or Set available to PBS consumers. AGD-0094 converged into accepted DEC-0078 and implementation PLN-0156. The user accepted the recommendations, authorized the decision and plan, and requested implementation. These identifiers record provenance; normative behavior now lives in the [Set/Identity specification](../../../docs/specs/compiler-languages/pbs/23.%20SDK%20Set%20and%20Identity%20Specification.md). Completed workflow scaffolding is removed by the discussion CLI. The runtime provider is `dcf6561ea73446e0a3e1cf1c73eda20923b38df0`, consumed unchanged. No runtime source, documentation, catalog, manifest, lockfile or commit was changed. Cargo projects/targets used for qualification live outside its checkout. Ordinary Studio builds use versioned local SDK/catalog resources. ## Consolidated decision and final result `@sdk:collections` exports invariant ordinary `set` and nominal `Identity`. Identity supplies `hash(T)->long` and `equals(T,T)->bool`. Set exports add/contains/remove/clear/size/isEmpty/cursor, with either a default constructor or an explicit service/struct strategy. Constructor arguments do not infer T. Defaults use value equality for int/long/bool, exact UTF-8 content for str, finite Float equality with normalized signed zeros, and instance identity for struct/array/Fn/Random. Contract identity uses its fully validated receiver, independent of the view/implementation. Tuples and other native values require an explicit strategy. Direct optional elements, including grouped optionals, are invalid; optional Sets and optional fields within elements remain valid. ```pbs import {set, Cursor} from @sdk:collections; declare struct Enemy(pub mut health: int); fn sample() -> long { let a = new Enemy(20); let b = new Enemy(20); let enemies: set = new set(); enemies.add(a); enemies.add(b); // A distinct instance, despite equal fields. enemies.add(a); // False; keeps the first stored reference. a.health = 42; // Instance identity is stable across mutation. let saved: Cursor = enemies.cursor(); enemies.clear(); // The snapshot still retains the shared Enemy references. return enemies.size(); } ``` An explicit content strategy may collapse a and b. It must be an equivalence relation, remain stable while stored, and satisfy equal values => equal hashes. Remove from every affected collection before changing content used by that policy, then reinsert. Cached hashes do not freeze mutable equality. The compiler does not prove purity or coherence and does not deep-copy payloads. The shared public policy is reusable by Map. Map/keyval API and representation remain a separate discussion; Set does not impose its physical table on Map. ## Patterns and algorithms ### Integrate neutral identity before the collection Common IR now represents REF_IDENTITY_HASH 0x97 and REF_IDENTITY_EQ 0x98 with static source TypeIds. Lowering derives complete group widths; encoding uses one/two little-endian TypeIds. Producer verification checks eligible categories even in dead code and consumes the complete operands. Existing conversion instructions retain their narrower categories. The exact eligible categories are Struct, Array, Fn, Trait and Random. Trait queries validate receiver plus ImplementationId, including valid zero, before using receiver identity. Equality validates both operands left-to-right: an absent or different left operand cannot hide an invalid right operand. Invalid/stale values remain faults. Digests neither root objects nor provide persistent IDs. The new `@sdk:hash` facade exposes i64/f64/text plus explicitly applied referenceHash/referenceEquals. Origin-checked private bindings select default hash/equality at concrete logical types. Unsupported default construction is a localized diagnostic; the unreachable default branch of an explicitly configured Set does not reject valid tuple/native strategies. User declarations with matching names or attributes receive no SDK privilege. The source-to-PBX-to-production-VM hash gate ran before Set algorithms were written. The initial gate covered 60 scalar/String oracle executions and 14 reference executions; later qualification expanded admission/right-side and discarded-reference cases. Temporal gate provenance and retained final logs are distinguished in [the evidence record](evidence/README.md). ### Cache full hashes and build independent growth candidates Private `_SetNode` stores a full signed long hash, complete T and next link. Buckets are an optional array. Empty construction has no table; the first successful inclusion allocates eight buckets. Above 75% next occupancy, capacity doubles, clamped to Array's u32 maximum. At that maximum, chains may continue within checked signed-long size and resource limits. Removal does not shrink; clear releases the table and returns to lazy empty state. Use signed remainder followed by correction for negative values. Taking abs of Long.MIN_VALUE or narrowing a digest to int breaks valid inputs, and clamped capacity is not necessarily a power of two. Duplicate detection precedes growth. Rehash copies independent nodes from cached hashes, preserving original links and shared payload references until installation. It invokes no strategy callbacks. Ordinary insertion does not copy the whole table. Capture likewise never calls hash/equals. The six-to-seven growth case simultaneously retained six old nodes, six copied nodes and the inserted node, plus both tables. GuestBytes high-water rose from 21,304 to 44,192 in the measured fixture. These are charged fixture/session peaks, including generic carriers and call preparation, not a universal per-Set bound or a timing benchmark. Detailed resource vectors are retained with the evidence. ### Separate guard writes from structural mutation add/contains/remove install a guard before invoking Identity. Reentrant add/remove/clear/contains on the same Set, including aliases, terminate through TRAP_EXPLICIT. size/isEmpty/cursor may inspect the consistent pre-mutation structure during callbacks and do not invoke Identity. Normal return releases the guard; a callback fault may leave it installed. Prepare checks, callbacks, next size, nodes/tables and complete values before structural stores. Then apply ordinary sequential stores without user callbacks. The [shared failure-phase contract](../../../docs/specs/compiler-languages/pbs/23.%20SDK%20Set%20and%20Identity%20Specification.md#guard-mutation-phases-and-faults) is essential: | Outcome | Meaning | | --- | --- | | Refusal before structural writes | Old elements/topology survive; guard, callback effects and provisional allocations are not rolled back | | Successful return | Size, table, groups, links and guard satisfy all invariants | | Fault after structural writes | Earlier writes and incomplete invariants may remain; no recovery, safe-reuse or rollback guarantee | The natural quota corpus observed 282 refusals across paired producer variants, all before structural mutation. That observation does not prove post-write faults impossible. A separately named test-only in-memory SDK variant inserts an Array allocation after the real table installation. Its quota fault leaves capacity 16, seven reachable nodes, old size six and the active guard. The failed instruction itself preserves its entry state. Production SDK source contains no such probe. Budget/debugger pauses are resumable instruction boundaries. They do not make a source method an atomic observation region. ### Reuse the entire snapshot protocol Capture builds one private immutable singly linked snapshot node per element. It scans B buckets and N nodes, costs O(B+N) work and O(N) extra nodes, and returns only a complete Cursor. Payload references stay shared; later Set mutation cannot rewrite the captured sequence. There is no iteration-order promise. A nonempty Cursor starts at its first value, hasNext tests a successor, and next without a successor retains the final value. Only empty-born cursors have absent current. Real GC safepoints verified snapshot node/payload retention 1,200 -> 1 -> 1 -> 0, and source Set node reclamation 64 -> 61 -> 0 -> 0. ### Preserve logical identity across specialization and modules This consumer exposed several reusable compiler pitfalls. Concrete implementations from the same generic family share a source span; deduplicating by span alone loses later applications. Deduplication now includes logical owner and contract keys. Raw TypeRef equality would instead distinguish incidental spans and produce duplicates. An already specialized type used as another module's generic argument still needs its defining dependency. Scoped if-let bindings, member receiver shapes and field assignment paths must also carry their symbolic types through specialization. Expected value contexts now reject mismatched nominal generic applications, such as list assigned to list; Set and ordinary user generic structs obey the same invariant rule. Negative integer literals retain contextual long typing during overload selection instead of falling through to an incorrect call path. ## Validation and limits of evidence The [evidence record](evidence/README.md) preserves commands, raw compressed logs, SHA-256 manifests, generated fixture fingerprints and the regression report. Source fixtures execute through the production loader/VM with ordinary and optimized PBS output, independently of Rust debug/release profiles. Installed examples compile outside the checkout using installDist JARs and their PBX runs on the same unchanged provider. LSP projections expose concrete signatures and hide fields/private helpers. Qualification is local macOS/arm64. It does not claim other hosts, installed game deployment, adversarial hash resistance or a performance threshold. Existing upstream headless-schema gaps are printed explicitly by the harness; their historical exceptions are not counted as schema conformance. Existing disabled JUnit cases are listed separately from the mandatory runtime corpus. ## Pitfalls to avoid - Do not compare carrier handles to implement logical tuple/value equality. - Do not reinterpret valid zero/false payloads as absence. - Do not make dead generic default branches reject explicit strategies. - Do not invoke strategy callbacks during rehash/capture or structural updates. - Do not translate resource faults into false/none or silently reset a faulted guard. - Do not infer whole-method rollback from single-instruction refusal preservation. - Do not present test-only fault injection as a natural production allocation. - Do not feed new named corpora through a legacy catch-all fixture verifier; each mandatory corpus has its own assertions and count. ## References - [Set/Identity/hash specification](../../../docs/specs/compiler-languages/pbs/23.%20SDK%20Set%20and%20Identity%20Specification.md). - [Shared Cursor specification](../../../docs/specs/compiler-languages/pbs/21.%20SDK%20List%20and%20Cursor%20Specification.md). - [Common Registry/PBX specification](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md). - [SDK collection source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs). - [Set source fixtures](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java). - [Conformance tooling and reproduction](../../../../tooling/scripts/pbx-conformance/README.md). - [Sequential mutation predecessor](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md).