--- id: LSN-0090 ticket: pbs-sdk-list title: Mutable Lists and Stable Snapshot Cursors created: 2026-10-22 tags: [compiler-pbs, collections, snapshot-cursor, atomic-publication, runtime-conformance] --- ## Original problem and final result Owner: `compiler/pbs`. Transversal owners: `compiler/general` for neutral IR/PBX and the runtime provider for storage, faults, ownership and resource accounting. DSC-0090 implemented accepted DEC-0075 through PLN-0153, covering R1–R14. The workflow control artifacts are disposable; the [List/Cursor specification](../../../docs/compiler/pbs/specs/sdk-list-and-cursor.md) is the durable normative reference. PBS needed a resizable collection whose existing references remain valid, together with a traversal that survives later collection edits. Both now live in the executable SDK: ordinary generic `list`, the shared `Cursor` contract and private snapshot nodes. The compiler provides trusted private bindings and source projections; generic storage instructions support complete publication in the VM. Linked, Set and Map remain separate discussions. ## Separate collection identity, logical positions and physical storage A List is a shared object containing a private fixed-length array and logical size. Growth replaces the backing reference inside that same object. Existing aliases therefore continue to observe the collection after growth, reserve or trim. Size includes holes. Capacity alone does not create valid positions. For example, `new list(16)` has size zero; `resize(3)` creates three valid empty positions. Writing position zero then stores a present value without changing size. Zero and false remain present values. `clearAt` leaves a hole, while `removeAt` removes a position and shifts the complete suffix, including its holes. The complete API includes constructors, size/capacity, bracket access, add, insert, clearAt, removeAt, clear, resize, reserve, trim and cursor. The [specification](../../../docs/compiler/pbs/specs/sdk-list-and-cursor.md) defines their exact results, geometric growth, structural limits and fault classifications. Clear, shrink and removal erase discarded references; later growth cannot resurrect old values. Directly optional elements are rejected, including through grouping; an optional List remains valid. Applications are invariant, and argument values do not infer the element type. ## A snapshot freezes the sequence of references List capture scans its logical positions backwards and prepends one node per present occurrence. The resulting chain visits increasing source indices, skips holes and preserves duplicates. Nodes are private, immutable, singly linked and non-circular. Capture finishes before the Cursor is returned. There is no second array, source-slot alias or source collection reference needed for traversal. Replacing, inserting, removing, clearing or resizing the List cannot change this captured sequence. A captured object reference still identifies the same object, so later mutations of its fields remain visible. This distinction lets gameplay change its collections while a consumer walks a stable sequence. The private cursor object stores its current-node reference. It can replace that root as it advances without changing any node link. Once other owners and call frames release consumed nodes, the prefix becomes collectible. The current node retains the remaining suffix. ### Successor-based hasNext and a retained last element `current()` initially reports the first element. `hasNext()` asks whether that element has a successor. `next()` follows an existing successor and otherwise does nothing. | Snapshot/state | hasNext() | current() | | --- | --- | --- | | Empty, initially or after repeated next | false | none | | [A], initially or after repeated next | false | some(A) | | [A, B], initially | true | some(A) | | [A, B], after one or any further next | false | some(B) | Process current, then either advance or stop. A hasNext-only loop omits the last element. A loop waiting for current to become none never finishes a nonempty snapshot. The [distributed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/collections.pbs) captures 20 and 22 around a hole, clears the List, visits both captured values and returns 42. Current still contains 22 afterwards. The outer optional describes whether a node exists. A producer with optional T must preserve `some(none)` as a present node whose payload is none. A synthetic non-List producer qualifies that distinction independently of List's element rule. Future Linked/Set producers use Cursor; Map entries use Cursor>. Their construction rules and ordering guarantees belong to their own discussions. ## Prepare the whole mutation before publishing An insert without growth can shift many slots and update size. A remove also prepares an optional result and clears its old tail. Each operation needs a single failure boundary for all observable changes. The generic provider adds four operations, carried through common IR and PBX: | Operation | Purpose | | --- | --- | | INDEX_GUARD | Check a signed-long logical index against an exclusive limit | | ARRAY_CHECK_LENGTH | Validate a structural length without allocating | | ARRAY_COPY | Transfer complete stored groups with overlap-safe prestate semantics | | STORAGE_PUBLISH | Prepare and commit source-selected copy/fill ranges and two typed fields | The SDK chooses its indices, ranges, fill value, target backing and resulting size. The generic layer validates those operands and resource charges. It snapshots complete source groups into charged scratch before any write, then commits the selected copy, fill and field updates without allocation, callbacks, scheduler or GC interleaving. Its four immediate operands identify the Array/Struct types and two distinct fields. There is no exported preparation token or general transaction syntax. For growth, a private candidate array is allocated and populated first. For a no-growth edit, scratch and all argument/result carriers are prepared first. `removeAt` obtains its previous optional value before publication. Raw transfer keeps presence tags, full value groups and existing reference/carrier identity. Per-element public optional unpack/repack would add failure points and allocation costs while shifting. Refusal leaves backing identity, capacity, size and complete stored groups unchanged. Argument effects evaluated before the call remain ordinary source effects. Unpublished candidates and scratch follow normal ownership and budgets. The provider has no List/Cursor opcode, category or syscall; collection algorithms remain in [SDK source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs). ## Compiler and tooling integration Reserved SDK attributes carry trusted definition origin. Copying their names into a project cannot grant private primitive access, and a user struct named list does not acquire SDK indexing or constructor rules. The public barrel exports List and Cursor; backing fields, storage bindings, nodes and bracket adapters stay private. SDK executable functions and implementations use the ordinary generic pipeline. Supporting them exposed reusable shape requirements: optional recursive payload members, concrete contract methods, applicable implementations and native group field maps must survive specialization. Complete values include vec2, pixel, tuples, nested arrays, contracts and function references. List index/length arguments accept localized lossless int-to-long promotion. Receiver and arguments execute once in source order, including named arguments. General numeric conversion rules stay unchanged. Common aggregation, optimization, emission and preload verification retain all four publication operands; malformed types or fields are rejected even in unreachable instructions. Editor projections show concrete public List/Cursor methods, optional results, constructor overloads and SDK definitions. Hover/completion hide private adapters and backing fields. Installed JAR tests load the actual packaged SDK, normative spec and example outside the checkout, generate PBX and execute it in the provider. ## Evidence and practical limits The selected provider is clean commit `d9b9eeb171d2861ec660d4cf5703b0795eac49a9`. Studio changes were tested over base `76a8b074e89e17c7425220888eeec38427261d46`. Qualification used macOS 27.0.1 arm64, Rust 1.98.1/LLVM 22.1.8, the dev runtime profile with resource-diagnostics, capabilities NONE, Gradle 9.3.1 and the repository's Java 21 toolchain (Corretto 21.0.4). Ordinary and optimized producer paths were exercised. | Gate | Observed result | | --- | --- | | Provider bytecode and VM libraries | 6 + 302 passed; 2 existing measurement tests ignored | | Full Studio regression and installed knowledge | Passed; existing skipped tests retained | | Final frontend/editor, LSP, source generation and installed checks | Passed; both installed tests passed | | PBS List/Cursor through production verifier/VM | 27 cases in each producer mode: 54 passed | | Non-PBS common IR | 2 storage fixtures executed through production VM | | Whole-operation quota refusals | 71 attempts; independently observed prior List state preserved | | Cursor GC | Nodes/items: 1200/1200 → 1/1 → 1/1 → 0/0 | | Reexports and installed example execution | Both passed; final captured value 22 retained | | Provider catalogs and canonical mirrors | Clean pinned provider; catalog parity and all four mirrors match | The refusal matrix lowers GuestBytes, HandleSlots, AuxiliaryBytes and TemporaryBytes around candidate allocation, no-growth publication scratch, optional return preparation, node creation and frame/operand preparation. It compares the typed List fields and every backing group before and after each refusal, and verifies resource accounting returns to zero after VM drop. Generic provider tests also cover overlapping multi-slot transfers, late invalid fields/ranges, immutable Dynamic-box identity and malformed encodings. Controlled normal GC safepoints prove consumed-prefix reclamation, retention of the final value 1199 despite repeated next calls, and release after dropping the Cursor. No source or snapshot Array remains live for that payload type at those safepoints. Optional carriers and other legitimate owners still have their normal allocation and retention costs. Capturing n positions with k present values takes O(n) time and O(k) additional nodes; next follows one link in O(1). [Machine-readable evidence](runtime-conformance-evidence.json) records commands, source and PBX hashes, default ceilings, every lowered refusal quota, GC observations and tested provenance. New cases are mandatory; missing fixtures fail the harness. The full harness also reports two pre-existing response-schema gaps, LifecycleRole and NonFiniteValue, with original payloads preserved. These were not changed by this delivery. Qualification makes no release-profile or cross-platform claim. R1–R5 are covered by type/construction/bounds/mutation/capacity fixtures; R6–R9 by snapshot states, identity, non-List optional production and GC; R10–R11 by direct provider tests, common IR and the refusal matrix; R12 by editor/import/distribution gates; R13 by resource accounting and retention observations; R14 by the mandatory production corpus, full regressions and pinned provenance. ## Pitfalls to preserve in future work - Treat logical size and capacity separately. An index inside physical capacity can still require TRAP_OOB; a hole is an optional result only at a valid index. - Keep faults distinct from absence. Long overflow, invalid bounds and resource refusal cannot become none or a truncated index. - Prepare optional returns and temporary groups before publication. Individual Array instruction atomicity alone cannot prove whole-mutator atomicity. - Preserve complete stored groups while shifting. Public optional reboxing can change identity, roots, costs and refusal boundaries. - Follow the Cursor state table. Never advance a nonempty cursor past its last node or retain an initial-head root just to support an unrequested reset. - Account for node and optional-carrier allocation. A linked snapshot has no promise of lower memory use than an array or immediate quota recovery. - Carry all publication operands through linking and optimization. A lost second field identity can invalidate otherwise well-typed SDK calls after imports. - Keep privileged bindings origin-based and private. Names and copied attributes are insufficient authority. ## References and reproduction - [List/Cursor specification](../../../docs/compiler/pbs/specs/sdk-list-and-cursor.md) and [Array/optional foundation](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md). - [Common Registry/PBX specification](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md) and [canonical provider publication code](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/storage_publication.rs). - [Source fixture generator](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java), [neutral IR fixtures](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java) and [production harness instructions](../../../tools/pbx-conformance/README.md). - [Generic structs lesson](../DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md) and [generic contracts lesson](../DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md). Run `./gradlew test :prometeu-app:installedKnowledgeTest --console=plain` before `python3 tools/pbx-conformance/run.py --runtime ../runtime` so the complete fixture corpus, including the installed example, exists. Provider and catalog commands, their working directories and the tested configuration are in the evidence file.