Skip to main content

semi_persistent_containers_verus/
sparse_set.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Semi-persistent sparse set with stable IDs, composed from three verified
4//! `Vec`s:
5//!   - `dense`:   packed values `[0, n)`, no gaps   (`Vec<T, Idx, S>`)
6//!   - `sparse`:  id → position                      (`Vec<Idx, Idx, Inline>`)
7//!   - `indices`: position → id                      (`Vec<Idx, Idx, Inline>`)
8//!
9//! ## The real invariant (`wf`)
10//! Let `cap = sparse.len() = indices.len()`, `n = dense.len() <= cap`.
11//!   1. `indices` is a PERMUTATION of `[0, cap)`: each `indices[p] < cap`, and
12//!      `indices` is injective (hence bijective position→id).
13//!   2. INVERSE-ON-LIVE: for live positions `p in [0, n)`,
14//!      `sparse[indices[p]] == p`.
15//! Positions `[n, cap)` are the FREE region — recently-removed ids parked for
16//! recycling; their `sparse` entries may be stale, which is harmless because
17//! injectivity (1) stops a free id from passing the liveness test.
18//!
19//! From this:
20//!   - **liveness**: `contains(id) = id<cap && sparse[id]<n &&
21//!     indices[sparse[id]]==id` holds iff `id` is some `indices[p]` with `p<n`
22//!     (proved: a free id fails the test by injectivity).
23//!   - **stable identity**: a live id's value is `dense[sparse[id]]`; other
24//!     ops keep that mapping (remove's swap updates `sparse[last_id]`).
25//!   - **id recycling**: `remove` parks the freed id at `indices[n-1]`; `add`
26//!     recycles exactly `indices[n]` and repairs its `sparse` entry.
27//!   - **semi-persistence**: `mark`/`restore` delegate to the three inner
28//!     vectors; restore composition gives back the marked state.
29//!
30//! Inherits the crate's `Copy + Default` convention (dense `T` and `Idx` both
31//! need `Default` for `Vec::restore`'s resize regrow).
32
33use vstd::prelude::*;
34
35use crate::diff_store::DiffStore;
36use crate::index_like::IndexLike;
37use crate::inline_store::InlineStore;
38use crate::tagged::Tagged;
39use crate::vec::{ShrinkPolicy, Vec as SpVec, VecToken};
40
41verus! {
42
43/// Token bundling one `VecToken` per inner vector.
44#[derive(Copy, Clone)]
45pub struct SparseSetToken {
46    pub(crate) dense: VecToken,
47    pub(crate) sparse: VecToken,
48    pub(crate) indices: VecToken,
49}
50
51impl SparseSetToken {
52    pub open(crate) spec fn dense_frame_idx_spec(self) -> nat {
53        self.dense.frame_idx as nat
54    }
55
56    pub open(crate) spec fn sparse_frame_idx_spec(self) -> nat {
57        self.sparse.frame_idx as nat
58    }
59
60    pub open(crate) spec fn indices_frame_idx_spec(self) -> nat {
61        self.indices.frame_idx as nat
62    }
63}
64
65/// Semi-persistent sparse set with stable IDs.
66pub struct SparseSet<T, Idx, S, const TRACK: bool = true>
67where
68    T: Sized + Copy,
69    Idx: IndexLike + Tagged,
70    S: DiffStore<T, Idx, TRACK>,
71{
72    pub(crate) dense: SpVec<T, Idx, S, TRACK>,
73    pub(crate) sparse: SpVec<Idx, Idx, InlineStore<Idx, Idx>, TRACK>,
74    pub(crate) indices: SpVec<Idx, Idx, InlineStore<Idx, Idx>, TRACK>,
75}
76
77impl<T, Idx, S, const TRACK: bool> SparseSet<T, Idx, S, TRACK>
78where
79    T: Sized + Copy,
80    Idx: IndexLike + Tagged,
81    S: DiffStore<T, Idx, TRACK>,
82{
83    /// The packed values currently in the set, in dense order.
84    pub open(crate) spec fn dense_view(&self) -> Seq<T> {
85        self.dense.view()
86    }
87
88    pub open(crate) spec fn cap_spec(&self) -> nat {
89        self.sparse.view().len()
90    }
91
92    /// Sparse column (spec counterpart; fields are `pub(crate)` — privacy closeout).
93    pub open(crate) spec fn indices_view(&self) -> Seq<Idx> {
94        self.indices.view()
95    }
96
97    pub open(crate) spec fn sparse_snapshots_view(&self) -> Seq<Seq<Idx>> {
98        self.sparse.snapshots_view()
99    }
100
101    pub open(crate) spec fn indices_snapshots_view(&self) -> Seq<Seq<Idx>> {
102        self.indices.snapshots_view()
103    }
104
105    pub open(crate) spec fn dense_depth_spec(&self) -> nat {
106        self.dense.depth_spec()
107    }
108
109    pub open(crate) spec fn sparse_view(&self) -> Seq<Idx> {
110        self.sparse.view()
111    }
112
113    /// Dense-column reference (spec counterpart, for `data()`'s ensures).
114    pub open(crate) spec fn dense_ref(&self) -> &SpVec<T, Idx, S, TRACK> {
115        &self.dense
116    }
117
118    /// Per-component restorability of the composite token — the atomic
119    /// prevalidation predicate `is_valid_token` answers.
120    pub open(crate) spec fn is_restorable_spec(&self, token: SparseSetToken) -> bool {
121        &&& self.dense.is_restorable_spec(token.dense)
122        &&& self.sparse.is_restorable_spec(token.sparse)
123        &&& self.indices.is_restorable_spec(token.indices)
124    }
125
126    /// Composite mark preconditions (headrooms on all three columns).
127    pub open(crate) spec fn can_mark_spec(&self) -> bool {
128        &&& self.dense.view().len() < Idx::max_nat()
129        &&& self.sparse.view().len() < Idx::max_nat()
130        &&& self.indices.view().len() < Idx::max_nat()
131        &&& self.dense.depth_spec() < u32::MAX
132        &&& self.sparse.depth_spec() < u32::MAX
133        &&& self.indices.depth_spec() < u32::MAX
134    }
135
136    /// Composite restore preconditions: per-component validity + structural
137    /// coordinates + headrooms (everything in `restore`'s requires except
138    /// the snapshot-wf clause, which quantifies over the actual snapshots).
139    pub open(crate) spec fn restore_pre_spec(&self, token: SparseSetToken) -> bool {
140        &&& self.dense.is_token_valid_spec(token.dense)
141        &&& token.dense_frame_idx_spec() < self.dense.depth_spec()
142        &&& self.dense.depth_spec() < u32::MAX
143        &&& self.dense.fork_count_spec() + 1 <= u32::MAX
144        &&& self.sparse.is_token_valid_spec(token.sparse)
145        &&& token.sparse_frame_idx_spec() < self.sparse.depth_spec()
146        &&& self.sparse.depth_spec() < u32::MAX
147        &&& self.sparse.fork_count_spec() + 1 <= u32::MAX
148        &&& self.indices.is_token_valid_spec(token.indices)
149        &&& token.indices_frame_idx_spec() < self.indices.depth_spec()
150        &&& self.indices.depth_spec() < u32::MAX
151        &&& self.indices.fork_count_spec() + 1 <= u32::MAX
152    }
153
154    /// The three column snapshots a token names (spec counterpart for restore's
155    /// contract).
156    pub open(crate) spec fn snap_at(&self, token: SparseSetToken) -> (Seq<T>, Seq<Idx>, Seq<Idx>) {
157        (self.dense.snapshots_view()[token.dense_frame_idx_spec() as int],
158         self.sparse.snapshots_view()[token.sparse_frame_idx_spec() as int],
159         self.indices.snapshots_view()[token.indices_frame_idx_spec() as int])
160    }
161
162    /// Dense snapshot stack (spec counterpart).
163    pub open(crate) spec fn dense_snapshots_view(&self) -> Seq<Seq<T>> {
164        self.dense.snapshots_view()
165    }
166
167    /// Add-capacity headroom (spec counterpart for `add`'s requires).
168    pub open(crate) spec fn can_add_spec(&self) -> bool {
169        &&& self.dense.view().len() + 1 < Idx::max_nat()
170        &&& self.sparse.view().len() + 1 < Idx::max_nat()
171        &&& self.indices.view().len() + 1 < Idx::max_nat()
172    }
173
174    pub open(crate) spec fn n_spec(&self) -> nat {
175        self.dense.view().len()
176    }
177
178    /// The structural sparse-set invariant (permutation + inverse-on-live),
179    /// on top of the three inner vectors' own well-formedness.
180    pub open(crate) spec fn wf(&self) -> bool {
181        let sparse = self.sparse.view();
182        let indices = self.indices.view();
183        let cap = self.cap_spec();
184        let n = self.n_spec();
185        &&& self.dense.wf()
186        &&& self.sparse.wf()
187        &&& self.indices.wf()
188        &&& indices.len() == cap
189        &&& n <= cap
190        // (1a) indices in range [0, cap)
191        &&& (forall|p: int| 0 <= p < cap ==> (#[trigger] indices[p]).as_nat() < cap)
192        // (1b) indices injective ⇒ permutation of [0, cap)
193        &&& (forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q ==>
194                (#[trigger] indices[p]).as_nat() != (#[trigger] indices[q]).as_nat())
195        // (2) inverse on the live region [0, n)
196        &&& (forall|p: int| 0 <= p < n ==>
197                sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p)
198    }
199
200    /// `id` is live: allocated, its position is in `[0, n)`, and the position
201    /// maps back to it. (Proved equivalent to "id == indices[p] for p < n".)
202    pub open(crate) spec fn contains_spec(&self, id: Idx) -> bool {
203        let sparse = self.sparse.view();
204        let indices = self.indices.view();
205        let n = self.n_spec();
206        &&& id.as_nat() < sparse.len()
207        &&& sparse[id.as_nat() as int].as_nat() < n
208        &&& indices[sparse[id.as_nat() as int].as_nat() as int].as_nat() == id.as_nat()
209    }
210
211    // ===================================================================
212    // Abstraction: the sparse set IS a ghost set of live ids together with a
213    // hand-rolled index pool of recycled ids (user-requested refinement). The
214    // permutation invariant (`wf`) is exactly what makes this abstraction sound.
215    // ===================================================================
216
217    /// The abstract set of live ids: the image of `indices` over `[0, n)`.
218    ///
219    /// `ISet`, not `Set`: since vstd made `Set` inherently finite, its
220    /// comprehension constructor returns `Option<Set>` (`None` on an infinite
221    /// predicate). `ISet::new` is total with the same membership axiom the old
222    /// `Set::new` had, so the comprehension layer uses `ISet` and finiteness
223    /// stays where it always was — a proved property (`lemma_image_prefix_card`),
224    /// not a construction obligation.
225    pub open(crate) spec fn id_set(&self) -> ISet<nat> {
226        let indices = self.indices.view();
227        ISet::new(|id: nat| exists|p: int| 0 <= p < self.n_spec()
228            && (#[trigger] indices[p]).as_nat() == id)
229    }
230
231    /// The index pool of recycled-but-not-reallocated ids: `indices[n .. cap)`,
232    /// as a sequence (the parking order; `add` reuses the slot at position `n`,
233    /// `remove` parks at `n-1`). Its multiset is the free ids.
234    pub open(crate) spec fn free_pool(&self) -> Seq<nat> {
235        let indices = self.indices.view();
236        Seq::new((self.cap_spec() - self.n_spec()) as nat,
237            |k: int| indices[self.n_spec() as int + k].as_nat())
238    }
239
240    /// Membership refinement: the runtime liveness test decides exactly the
241    /// abstract set. (⟸ uses inverse-on-live; ⟹ uses the round-trip test.)
242    pub(crate) proof fn lemma_contains_iff_id_set(&self, id: Idx)
243        requires self.wf(),
244        ensures self.contains_spec(id) <==> self.id_set().contains(id.as_nat()),
245    {
246        let indices = self.indices.view();
247        let sparse = self.sparse.view();
248        let n = self.n_spec();
249        if self.contains_spec(id) {
250            // position p = sparse[id] < n witnesses membership.
251            let p = sparse[id.as_nat() as int].as_nat() as int;
252            assert(0 <= p < n && indices[p].as_nat() == id.as_nat());
253        }
254        if self.id_set().contains(id.as_nat()) {
255            // some p<n has indices[p]==id; inverse-on-live ⇒ sparse[id]==p<n,
256            // and indices[sparse[id]]==indices[p]==id ⇒ contains_spec.
257            let p = choose|p: int| 0 <= p < n && (#[trigger] indices[p]).as_nat() == id.as_nat();
258            assert(sparse[indices[p].as_nat() as int].as_nat() == p);  // inverse
259            assert(id.as_nat() < sparse.len());  // id == indices[p] < cap == sparse.len()
260        }
261    }
262
263    /// Set and pool are DISJOINT and together exhaust the allocated id space:
264    /// every id in `[0, cap)` is either live or free, never both. (Direct from
265    /// the permutation invariant: `indices` bijects positions to ids, the live
266    /// positions `[0,n)` give the set, the free positions `[n,cap)` give the
267    /// pool.)
268    pub(crate) proof fn lemma_set_pool_partition(&self)
269        requires self.wf(),
270        ensures
271            // disjoint
272            forall|id: nat| self.id_set().contains(id) ==> !self.free_pool().contains(id),
273            // every allocated id is in exactly one
274            forall|id: nat| id < self.cap_spec() ==>
275                (self.id_set().contains(id) || self.free_pool().contains(id)),
276    {
277        let indices = self.indices.view();
278        let n = self.n_spec();
279        let cap = self.cap_spec();
280        // disjoint: a live id has a witness p<n; a pooled id has witness k with
281        // position n+k >= n. Same id at two positions violates injectivity.
282        assert forall|id: nat| self.id_set().contains(id) implies
283            !self.free_pool().contains(id) by {
284            let p = choose|p: int| 0 <= p < n && (#[trigger] indices[p]).as_nat() == id;
285            if self.free_pool().contains(id) {
286                let k = choose|k: int| 0 <= k < (cap - n)
287                    && (#[trigger] self.free_pool()[k]) == id;
288                assert(indices[n + k].as_nat() == id);
289                assert(p != n + k);  // p < n <= n+k
290                // injectivity: indices[p] != indices[n+k], contradiction.
291                assert(indices[p].as_nat() != indices[n + k].as_nat());
292            }
293        }
294        // exhaustive: id < cap. By surjectivity of the permutation (in-range +
295        // injective on a finite set ⇒ bijective), id == indices[p] for some
296        // p < cap; p < n ⇒ live, else pooled.
297        assert forall|id: nat| id < cap implies
298            (self.id_set().contains(id) || self.free_pool().contains(id)) by {
299            lemma_perm_surjective(indices, cap as int, id);
300            let p = choose|p: int| 0 <= p < cap && (#[trigger] indices[p]).as_nat() == id;
301            if p < n {
302                assert(self.id_set().contains(id));
303            } else {
304                assert(self.free_pool()[p - n] == id);
305                assert(self.free_pool().contains(id));
306            }
307        }
308    }
309
310    pub fn len(&self) -> (n: Idx)
311        requires self.wf(),
312        ensures n.as_nat() == self.dense_view().len(),
313    {
314        self.dense.len()
315    }
316
317    pub fn is_empty(&self) -> (b: bool)
318        requires self.wf(),
319        ensures b == (self.dense_view().len() == 0),
320    {
321        self.dense.is_empty()
322    }
323
324    /// Liveness test. Returns exactly `contains_spec(id)`.
325    pub fn contains(&self, id: Idx) -> (b: bool)
326        requires self.wf(),
327        ensures b == self.contains_spec(id),
328    {
329        let cap = self.sparse.len();
330        if id.as_usize() >= cap.as_usize() {
331            return false;
332        }
333        let pos = self.sparse.get_index(id);
334        let nlen = self.dense.len();
335        if pos.as_usize() >= nlen.as_usize() {
336            return false;
337        }
338        let idx_at = self.indices.get_index(pos);
339        idx_at.as_usize() == id.as_usize()
340    }
341
342    /// Value of a live id (through the stable indirection).
343    pub fn get(&self, id: Idx) -> (v: T)
344        requires self.wf(),
345        ensures self.contains_spec(id)
346            ==> v == self.dense_view()[self.sparse_view()[id.as_nat() as int].as_nat() as int],
347    {
348        // Total-with-documented-panic: liveness is an explicit branch. A dead
349        // id previously read a stale dense slot silently (production asserts;
350        // the verified core relied on the erased requires).
351        if !self.contains(id) {
352            crate::guard::refuse("SparseSet::get: id not present");
353        }
354        let pos = self.sparse.get_index(id);
355        self.dense.get_index(pos)
356    }
357
358    /// Value of a live id whose liveness the caller has already established
359    /// (pub(crate): the aggregate checks once, or holds it as a proof fact,
360    /// and reads without the public form's re-check).
361    pub(crate) fn get_live(&self, id: Idx) -> (v: T)
362        requires
363            self.wf(),
364            self.contains_spec(id),
365        ensures
366            v == self.dense_view()[self.sparse_view()[id.as_nat() as int].as_nat() as int],
367    {
368        let pos = self.sparse.get_index(id);
369        self.dense.get_index(pos)
370    }
371
372    /// Overwrite a live id's value, liveness already established (the
373    /// pub(crate) counterpart of `set`, same effects without the re-check).
374    pub(crate) fn set_live(&mut self, id: Idx, value: T)
375        requires
376            old(self).wf(),
377            old(self).contains_spec(id),
378        ensures
379            final(self).wf(),
380            final(self).cap_spec() == old(self).cap_spec(),
381            final(self).n_spec() == old(self).n_spec(),
382            final(self).sparse_view() == old(self).sparse_view(),
383            final(self).indices_view() == old(self).indices_view(),
384            final(self).dense_view() == old(self).dense_view().update(
385                old(self).sparse_view()[id.as_nat() as int].as_nat() as int, value),
386            final(self).id_set() == old(self).id_set(),
387            final(self).free_pool() == old(self).free_pool(),
388            final(self).dense_snapshots_view() == old(self).dense_snapshots_view(),
389            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view(),
390            final(self).indices_snapshots_view() == old(self).indices_snapshots_view(),
391    {
392        let pos = self.sparse.get_index(id);
393        self.dense.set_index(pos, value);
394        proof {
395            assert(self.sparse.view() == old(self).sparse.view());
396            assert(self.indices.view() == old(self).indices.view());
397            assert(self.dense.view().len() == old(self).dense.view().len());
398        }
399    }
400
401    /// Overwrite a live id's value in place (position and id unchanged).
402    pub fn set(&mut self, id: Idx, value: T)
403        requires old(self).wf(),
404        ensures
405            final(self).wf(),
406            old(self).contains_spec(id) ==> {
407                &&& final(self).cap_spec() == old(self).cap_spec()
408                &&& final(self).n_spec() == old(self).n_spec()
409                &&& final(self).sparse_view() == old(self).sparse_view()
410                &&& final(self).indices_view() == old(self).indices_view()
411                &&& final(self).dense_view() == old(self).dense_view().update(
412                        old(self).sparse_view()[id.as_nat() as int].as_nat() as int, value)
413                &&& final(self).id_set() == old(self).id_set()
414                &&& final(self).free_pool() == old(self).free_pool()
415            },
416            // snapshot-stack framing (eclasses: the aggregate's archive is
417            // keyed on the component stacks).
418            final(self).dense_snapshots_view() == old(self).dense_snapshots_view(),
419            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view(),
420            final(self).indices_snapshots_view() == old(self).indices_snapshots_view(),
421    {
422        // Total-with-documented-panic: see `get`.
423        if !self.contains(id) {
424            crate::guard::refuse("SparseSet::set: id not present");
425        }
426        let pos = self.sparse.get_index(id);
427        self.dense.set_index(pos, value);
428        proof {
429            // dense.set changes only dense's values, not lengths; sparse and
430            // indices are untouched, so the permutation + inverse carry.
431            assert(self.sparse.view() == old(self).sparse.view());
432            assert(self.indices.view() == old(self).indices.view());
433            assert(self.dense.view().len() == old(self).dense.view().len());
434        }
435    }
436
437    /// Add a value, returning a stable id. If a free slot exists (`n < cap`),
438    /// recycle the id parked at `indices[n]`; otherwise allocate a fresh id
439    /// `== n`. The new element occupies dense position `n`.
440    pub(crate) fn add(&mut self, value: T) -> (id: Idx)
441        requires
442            old(self).wf(),
443            old(self).can_add_spec(),
444        ensures
445            final(self).wf(),
446            final(self).n_spec() == old(self).n_spec() + 1,
447            // the returned id is now live
448            final(self).contains_spec(id),
449            // ABSTRACT EFFECT: the live set gains exactly `id`, which was not
450            // live before.
451            !old(self).id_set().contains(id.as_nat()),
452            final(self).id_set() =~= old(self).id_set().insert(id.as_nat()),
453            // INDEX-POOL REUSE: if a free id was available, `add` recycles the
454            // one parked at the pool front (LIFO with `remove`), and the pool
455            // shrinks by that element; otherwise a fresh id `== old cap` is
456            // allocated and the (empty) pool stays empty.
457            old(self).free_pool().len() > 0 ==>
458                (id.as_nat() == old(self).free_pool()[0]
459                 && final(self).free_pool() =~= old(self).free_pool().drop_first()),
460            old(self).free_pool().len() == 0 ==>
461                (id.as_nat() == old(self).cap_spec() && final(self).free_pool().len() == 0),
462            // capacity: recycling keeps it, a fresh id grows it by one, and
463            // either way the minted id is within the old capacity.
464            id.as_nat() <= old(self).cap_spec(),
465            final(self).cap_spec() == if old(self).free_pool().len() == 0 {
466                old(self).cap_spec() + 1
467            } else {
468                old(self).cap_spec()
469            },
470            // the stored value is readable back at the new id.
471            final(self).dense_view()[
472                final(self).sparse_view()[id.as_nat() as int].as_nat() as int] == value,
473            // survivors: every previously live id stays live with its value.
474            forall|k: Idx| #[trigger] old(self).contains_spec(k)
475                ==> final(self).contains_spec(k)
476                    && final(self).dense_view()[
477                            final(self).sparse_view()[k.as_nat() as int].as_nat() as int]
478                        == old(self).dense_view()[
479                            old(self).sparse_view()[k.as_nat() as int].as_nat() as int],
480            // snapshot-stack framing (eclasses: the aggregate's archive is
481            // keyed on the component stacks).
482            final(self).dense_snapshots_view() == old(self).dense_snapshots_view(),
483            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view(),
484            final(self).indices_snapshots_view() == old(self).indices_snapshots_view(),
485    {
486        let ghost old_n = self.dense.view().len();
487        let ghost old_cap = self.sparse.view().len();
488        let pos = self.dense.len();
489        self.dense.push(value);
490
491        let cap = self.sparse.len();
492        if pos.as_usize() < cap.as_usize() {
493            // Recycle: indices[pos] is the first free id (pos == old_n).
494            let recycled_id = self.indices.get_index(pos);
495            self.sparse.set_index(recycled_id, pos);
496            proof {
497                let sparse = self.sparse.view();
498                let indices = self.indices.view();
499                let n = self.dense.view().len();  // old_n + 1
500                assert(indices == old(self).indices.view());
501                assert(n == old_n + 1);
502                assert(pos.as_nat() == old_n);
503                // indices unchanged ⇒ permutation (1a,1b) carry.
504                // inverse-on-live now needs to hold for p in [0, old_n+1):
505                //  - p < old_n: indices[p] != recycled_id (= indices[old_n], and
506                //    injectivity with p != old_n), so sparse[indices[p]] is
507                //    unchanged == p (old inverse).
508                //  - p == old_n: indices[old_n] == recycled_id and we just set
509                //    sparse[recycled_id] = old_n == pos.
510                assert forall|p: int| 0 <= p < n implies
511                    sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p by {
512                    if p == old_n as int {
513                        assert(indices[p].as_nat() == recycled_id.as_nat());
514                        assert(sparse[recycled_id.as_nat() as int].as_nat() == old_n);
515                    } else {
516                        assert(indices[p].as_nat() != indices[old_n as int].as_nat());
517                        assert(indices[old_n as int].as_nat() == recycled_id.as_nat());
518                        assert(sparse[indices[p].as_nat() as int]
519                            == old(self).sparse.view()[indices[p].as_nat() as int]);
520                    }
521                }
522                // returned id (recycled_id) is live: sparse[recycled_id]=old_n<n,
523                // indices[old_n]==recycled_id.
524                assert(recycled_id.as_nat() < old_cap);
525
526                // --- abstract effect: set gains recycled_id, pool drops front.
527                // indices unchanged, n: old_n -> old_n+1. id_set is the image of
528                // [0,n); the only new position is old_n, whose value is
529                // recycled_id == old free_pool[0].
530                assert(old(self).free_pool().len() > 0);   // old_n < old_cap
531                assert(old(self).free_pool()[0] == recycled_id.as_nat()) by {
532                    assert(old(self).indices.view()[old_n as int].as_nat()
533                        == recycled_id.as_nat());
534                }
535                assert(!old(self).id_set().contains(recycled_id.as_nat())) by {
536                    // recycled_id at position old_n >= old_n; a live witness p
537                    // would be < old_n, violating injectivity.
538                    if old(self).id_set().contains(recycled_id.as_nat()) {
539                        let p = choose|p: int| 0 <= p < old_n
540                            && (#[trigger] old(self).indices.view()[p]).as_nat()
541                                == recycled_id.as_nat();
542                        assert(old(self).indices.view()[p].as_nat()
543                            != old(self).indices.view()[old_n as int].as_nat());
544                    }
545                }
546                assert(self.id_set() =~= old(self).id_set().insert(recycled_id.as_nat())) by {
547                    assert forall|v: nat| #![auto] self.id_set().contains(v)
548                        <==> old(self).id_set().insert(recycled_id.as_nat()).contains(v) by {
549                        if self.id_set().contains(v) {
550                            let p = choose|p: int| 0 <= p < n
551                                && (#[trigger] indices[p]).as_nat() == v;
552                            if p < old_n { } else { assert(v == recycled_id.as_nat()); }
553                        }
554                    }
555                }
556                assert(self.free_pool() =~= old(self).free_pool().drop_first()) by {
557                    // both have length old_cap - old_n - 1; element k of the new
558                    // pool is indices[(old_n+1)+k] == old pool element k+1.
559                    assert(self.free_pool().len() == old(self).free_pool().drop_first().len());
560                    assert forall|k: int| #![auto] 0 <= k < self.free_pool().len() implies
561                        self.free_pool()[k] == old(self).free_pool().drop_first()[k] by {
562                        assert(self.free_pool()[k] == indices[(old_n + 1) + k].as_nat());
563                        assert(old(self).free_pool().drop_first()[k]
564                            == old(self).free_pool()[k + 1]);
565                    }
566                }
567            }
568            recycled_id
569        } else {
570            // Fresh id == pos == old_n == old_cap.
571            self.sparse.push(pos);
572            self.indices.push(pos);
573            proof {
574                let sparse = self.sparse.view();
575                let indices = self.indices.view();
576                let cap = sparse.len();   // old_cap + 1
577                let n = self.dense.view().len();  // old_n + 1, and old_n == old_cap
578                assert(pos.as_nat() == old_n);
579                assert(old_n == old_cap);
580                assert(cap == old_cap + 1);
581                assert(indices[old_cap as int].as_nat() == pos.as_nat() == old_cap);
582                // (1a) in range: old entries < old_cap < cap; new entry == old_cap < cap.
583                assert forall|p: int| 0 <= p < cap implies (#[trigger] indices[p]).as_nat() < cap by {
584                    if p < old_cap { } else { assert(indices[p].as_nat() == old_cap); }
585                }
586                // (1b) injective: new value old_cap differs from all old (< old_cap).
587                assert forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q implies
588                    (#[trigger] indices[p]).as_nat() != (#[trigger] indices[q]).as_nat() by {
589                    if p < old_cap && q < old_cap {
590                    } else {
591                        // one is the new slot (value old_cap), the other old (< old_cap).
592                    }
593                }
594                // (2) inverse-on-live for [0, old_cap+1): old positions carry
595                // (sparse extended, prefix unchanged); new position old_cap has
596                // indices[old_cap]==old_cap and sparse[old_cap]==pos==old_cap.
597                assert forall|p: int| 0 <= p < n implies
598                    sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p by {
599                    if p < old_n as int {
600                        assert(indices[p] == old(self).indices.view()[p]);
601                        assert(indices[p].as_nat() < old_cap);
602                        assert(sparse[indices[p].as_nat() as int]
603                            == old(self).sparse.view()[indices[p].as_nat() as int]);
604                    } else {
605                        assert(p == old_cap as int);
606                        assert(indices[p].as_nat() == old_cap);
607                        assert(sparse[old_cap as int].as_nat() == pos.as_nat() == old_cap);
608                    }
609                }
610                // --- abstract effect: fresh allocation. old pool was empty
611                // (old_n == old_cap), new id == old_cap, new pool empty too.
612                assert(old(self).free_pool().len() == 0);   // old_cap - old_n == 0
613                assert(!old(self).id_set().contains(old_cap as nat)) by {
614                    // a live witness p < old_n would have indices[p] < old_cap.
615                    if old(self).id_set().contains(old_cap as nat) {
616                        let p = choose|p: int| 0 <= p < old_n
617                            && (#[trigger] old(self).indices.view()[p]).as_nat() == old_cap as nat;
618                    }
619                }
620                assert(self.id_set() =~= old(self).id_set().insert(old_cap as nat)) by {
621                    assert forall|v: nat| #![auto] self.id_set().contains(v)
622                        <==> old(self).id_set().insert(old_cap as nat).contains(v) by {
623                        if self.id_set().contains(v) {
624                            let p = choose|p: int| 0 <= p < n
625                                && (#[trigger] indices[p]).as_nat() == v;
626                            if p < old_n {
627                                assert(indices[p] == old(self).indices.view()[p]);
628                            } else {
629                                assert(v == old_cap);
630                            }
631                        }
632                        // reverse: old members keep their witness; old_cap is at
633                        // position old_n == old_cap.
634                        if old(self).id_set().contains(v) {
635                            let q = choose|q: int| 0 <= q < old_n
636                                && (#[trigger] old(self).indices.view()[q]).as_nat() == v;
637                            assert(indices[q] == old(self).indices.view()[q]);
638                            assert(0 <= q < n);
639                        }
640                        if v == old_cap as nat {
641                            assert(indices[old_cap as int].as_nat() == old_cap);
642                            assert(0 <= old_cap < n);
643                        }
644                    }
645                }
646                assert(self.free_pool().len() == 0);  // cap == n == old_cap+1
647            }
648            pos
649        }
650    }
651
652    /// Remove a live id. Swap-removes its dense slot with the last element and
653    /// parks the freed id at the new boundary `indices[n-1]` (the first free
654    /// slot), preserving the permutation by a transposition.
655    pub fn remove(&mut self, id: Idx)
656        requires old(self).wf(),
657        ensures
658            final(self).wf(),
659            // Every clause is conditional on liveness at entry; a dead id
660            // refuses at the branch and reaches none of this.
661            old(self).contains_spec(id) ==> {
662                &&& final(self).n_spec() == old(self).n_spec() - 1
663                &&& final(self).cap_spec() == old(self).cap_spec()
664                // ABSTRACT EFFECT: the live set loses exactly `id`.
665                &&& final(self).id_set() =~= old(self).id_set().remove(id.as_nat())
666                // INDEX-POOL PARKING: the freed id is pushed to the pool FRONT
667                // (so the next `add` recycles it — LIFO), the rest shifts back.
668                &&& final(self).free_pool() =~= old(self).free_pool().insert(0, id.as_nat())
669                // survivors: every other live id stays live with its value
670                // (the swap-remove moves the last dense slot, not its id map).
671                &&& (forall|k: Idx| #[trigger] old(self).contains_spec(k)
672                        && k.as_nat() != id.as_nat()
673                        ==> final(self).contains_spec(k)
674                            && final(self).dense_view()[
675                                    final(self).sparse_view()[k.as_nat() as int].as_nat() as int]
676                                == old(self).dense_view()[
677                                    old(self).sparse_view()[k.as_nat() as int].as_nat() as int])
678            },
679            // snapshot-stack framing (eclasses: the aggregate's archive is
680            // keyed on the component stacks).
681            final(self).dense_snapshots_view() == old(self).dense_snapshots_view(),
682            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view(),
683            final(self).indices_snapshots_view() == old(self).indices_snapshots_view(),
684    {
685        // Total-with-documented-panic: see `get`.
686        if !self.contains(id) {
687            crate::guard::refuse("SparseSet::remove: id not present");
688        }
689        let ghost old_n = self.dense.view().len();
690        let ghost old_cap = self.sparse.view().len();
691        let ghost old_sparse = self.sparse.view();
692        let ghost old_indices = self.indices.view();
693        let pos = self.sparse.get_index(id);
694        let nlen = self.dense.len();
695        // last_pos = n - 1 (n >= 1 since id is live ⇒ pos < n).
696        proof { nlen.lemma_as_nat_bounded(); }
697        let last_pos = match Idx::try_from_usize(nlen.as_usize() - 1) {
698            Some(x) => x,
699            None => { assert(false); return; },
700        };
701
702        if pos.as_usize() != last_pos.as_usize() {
703            let last_id = self.indices.get_index(last_pos);
704            let last_val = self.dense.get_index(last_pos);
705            proof {
706                // From inverse-on-live: indices[pos]==id and sparse[last_id]==last_pos.
707                assert(pos.as_nat() < old_n);          // id live
708                assert(old_indices[pos.as_nat() as int].as_nat() == id.as_nat());
709                assert(last_pos.as_nat() == old_n - 1);
710                assert(old_sparse[old_indices[(old_n - 1) as int].as_nat() as int].as_nat()
711                    == (old_n - 1));  // inverse at last_pos
712                assert(last_id.as_nat() == old_indices[(old_n - 1) as int].as_nat());
713            }
714            self.dense.set_index(pos, last_val);
715            self.indices.set_index(pos, last_id);
716            self.indices.set_index(last_pos, id);
717            self.sparse.set_index(last_id, pos);
718            self.dense.pop();
719            proof {
720                let sparse = self.sparse.view();
721                let indices = self.indices.view();
722                let n = self.dense.view().len();   // old_n - 1
723                let cap = sparse.len();
724                assert(n == old_n - 1);
725                assert(cap == old_cap);
726                // indices' is old_indices with [pos]:=last_id, [last_pos]:=id —
727                // a transposition of the values at pos and last_pos (old
728                // indices[pos]==id, indices[last_pos]==last_id), so still a
729                // permutation of [0, cap).
730                assert(indices =~= old_indices.update(pos.as_nat() as int, last_id)
731                    .update(last_pos.as_nat() as int, id));
732                // (1a) in range: values unchanged as a multiset.
733                assert forall|p: int| 0 <= p < cap implies (#[trigger] indices[p]).as_nat() < cap by {
734                    if p == pos.as_nat() {
735                        assert(indices[p].as_nat() == last_id.as_nat());
736                        assert(old_indices[(old_n - 1) as int].as_nat() < old_cap);
737                    } else if p == last_pos.as_nat() {
738                        assert(indices[p].as_nat() == id.as_nat());
739                        assert(old_indices[pos.as_nat() as int].as_nat() == id.as_nat());
740                    } else {
741                        assert(indices[p] == old_indices[p]);
742                    }
743                }
744                // (1b) injective: a transposition of an injective seq.
745                lemma_transposition_injective(old_indices, indices,
746                    pos.as_nat() as int, last_pos.as_nat() as int, cap as int);
747                // (2) inverse-on-live for [0, n) = [0, old_n - 1):
748                assert forall|p: int| 0 <= p < n implies
749                    sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p by {
750                    if p == pos.as_nat() {
751                        // indices[pos]==last_id, sparse[last_id]:=pos.
752                        assert(indices[p].as_nat() == last_id.as_nat());
753                        assert(sparse[last_id.as_nat() as int].as_nat() == pos.as_nat());
754                    } else {
755                        // p < n-1... actually p in [0,n) with p != pos, and
756                        // p != last_pos (since last_pos == old_n-1 == n >= p+? );
757                        // p < n = old_n-1 < last_pos, so p != last_pos.
758                        assert(p < (old_n - 1));
759                        assert(p != last_pos.as_nat());
760                        assert(indices[p] == old_indices[p]);
761                        // indices[p] != last_id (injective, p != last_pos), so
762                        // sparse[indices[p]] unchanged from old (only last_id set).
763                        assert(old_indices[p].as_nat() != old_indices[(old_n - 1) as int].as_nat());
764                        assert(indices[p].as_nat() != last_id.as_nat());
765                        assert(sparse[indices[p].as_nat() as int]
766                            == old_sparse[indices[p].as_nat() as int]);
767                        assert(old_sparse[old_indices[p].as_nat() as int].as_nat() == p);
768                    }
769                }
770            }
771        } else {
772            // Removing the last live element: just shrink. The id stays parked
773            // at indices[last_pos] = indices[n-1] (now the first free slot).
774            self.dense.pop();
775            proof {
776                let sparse = self.sparse.view();
777                let indices = self.indices.view();
778                let n = self.dense.view().len();  // old_n - 1
779                assert(n == old_n - 1);
780                assert(indices == old_indices);
781                assert(sparse == old_sparse);
782                // sparse/indices untouched; inverse-on-live shrinks to [0,n).
783                assert forall|p: int| 0 <= p < n implies
784                    sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p by {
785                    assert(p < old_n);
786                }
787            }
788        }
789        // --- abstract effect (both branches): set loses `id`, pool gains it
790        // at the front. Branch-uniform facts established locally above:
791        //   - indices[n].as_nat() == id  (id parked at the new pool front);
792        //   - for every OLD live position q < old_n with old value v != id, the
793        //     NEW indices still has v at some position < n (proved per branch
794        //     into `old_to_new_live` below);
795        //   - the prefix relation for the pool tail.
796        proof {
797            let indices = self.indices.view();
798            let n = self.dense.view().len();   // old_n - 1
799            assert(n == old_n - 1);
800            assert(indices[n as int].as_nat() == id.as_nat());
801            // id is NOT in the new live image (it sits at position n; a live
802            // witness q < n would collide by injectivity).
803            assert(!self.id_set().contains(id.as_nat())) by {
804                if self.id_set().contains(id.as_nat()) {
805                    let q = choose|q: int| 0 <= q < n && (#[trigger] indices[q]).as_nat() == id.as_nat();
806                    assert(indices[q].as_nat() != indices[n as int].as_nat());
807                }
808            }
809            assert(self.id_set() =~= old(self).id_set().remove(id.as_nat())) by {
810                assert forall|v: nat| #![auto] self.id_set().contains(v)
811                    <==> old(self).id_set().remove(id.as_nat()).contains(v) by {
812                    // forward: v new-live ⇒ v old-live (its new witness q<n maps,
813                    // in both branches, back to an old live position) and v != id.
814                    if self.id_set().contains(v) {
815                        let q = choose|q: int| 0 <= q < n && (#[trigger] indices[q]).as_nat() == v;
816                        assert(indices[q].as_nat() != indices[n as int].as_nat());  // v != id
817                        // q's value came from some old live position:
818                        //  - last-element branch: indices==old_indices, q<n<old_n.
819                        //  - swap branch: if q==pos, indices[pos]==last_id==
820                        //    old_indices[old_n-1] (old live); else indices[q]==
821                        //    old_indices[q] (old live, q<n<old_n).
822                        assert(old(self).id_set().contains(v)) by {
823                            if pos.as_nat() == last_pos.as_nat() {
824                                assert(old_indices[q].as_nat() == v);
825                            } else if q == pos.as_nat() {
826                                assert(indices[pos.as_nat() as int].as_nat()
827                                    == old_indices[(old_n - 1) as int].as_nat());
828                            } else {
829                                assert(old_indices[q].as_nat() == v);
830                            }
831                        }
832                    }
833                    // reverse: v old-live and v != id ⇒ v new-live. v's old
834                    // witness q0 < old_n. The only old live position that loses
835                    // its value is `pos` (held id, now last_id) — but v != id,
836                    // so v survives at some new position < n.
837                    if old(self).id_set().remove(id.as_nat()).contains(v) {
838                        let q0 = choose|q0: int| 0 <= q0 < old_n
839                            && (#[trigger] old_indices[q0]).as_nat() == v;
840                        assert(v != id.as_nat());
841                        // old_indices[pos]==id (inverse-on-live), so q0 != pos.
842                        assert(old_indices[pos.as_nat() as int].as_nat() == id.as_nat());
843                        assert(q0 != pos.as_nat());
844                        if pos.as_nat() == last_pos.as_nat() {
845                            // last-element: indices==old_indices, q0 != pos==n,
846                            // so q0 < n and indices[q0]==v.
847                            assert(q0 < n);
848                            assert(indices[q0].as_nat() == v);
849                        } else {
850                            // swap: last value (old_indices[old_n-1]) moved to pos.
851                            if q0 == old_n - 1 {
852                                assert(indices[pos.as_nat() as int].as_nat() == v);
853                                assert(pos.as_nat() < n);
854                            } else {
855                                // q0 < old_n-1 == n and q0 != pos ⇒ unchanged.
856                                assert(q0 < n);
857                                assert(indices[q0].as_nat() == v);
858                            }
859                        }
860                    }
861                }
862            }
863            // pool gains id at the front: new pool is indices[n..cap], and
864            // indices[n] == id, indices[n+1..cap] == old indices[n+1..cap]
865            // == old pool (old pool was indices[old_n..cap] = indices[n+1..cap]).
866            assert(self.free_pool() =~= old(self).free_pool().insert(0, id.as_nat())) by {
867                let np = self.free_pool();
868                let op = old(self).free_pool().insert(0, id.as_nat());
869                assert(np.len() == op.len());
870                assert forall|k: int| 0 <= k < np.len() implies np[k] == op[k] by {
871                    if k == 0 {
872                        assert(np[0] == indices[n as int].as_nat());
873                    } else {
874                        assert(np[k] == indices[n as int + k].as_nat());
875                        assert(op[k] == old(self).free_pool()[k - 1]);
876                        assert(old(self).free_pool()[k - 1]
877                            == old_indices[old_n as int + (k - 1)].as_nat());
878                        // position n+k == old_n+k-1 > n is unchanged: the swap
879                        // touched only pos (< n) and last_pos (== n); the
880                        // last-element branch left indices == old_indices.
881                        assert(n as int + k > n);
882                        assert(indices[n as int + k] == old_indices[n as int + k]);
883                        assert(n as int + k == old_n as int + (k - 1));
884                    }
885                }
886            }
887        }
888    }
889
890    /// Remove the first live entry whose VALUE equals `val` (production
891    /// `remove_value` parity: linear scan of the dense region, then the
892    /// verified `remove` on the id found at that position).
893    pub fn remove_value(&mut self, val: &T) -> (removed: bool)
894        where T: PartialEq
895        requires old(self).wf(),
896        ensures
897            final(self).wf(),
898            final(self).cap_spec() == old(self).cap_spec(),
899            removed ==> final(self).n_spec() == old(self).n_spec() - 1,
900            !removed ==> *final(self) == *old(self),
901    {
902        let n = self.dense.len();
903        proof { n.lemma_as_nat_bounded(); }  // n.as_nat() < Idx::max_nat()
904        let n_u = n.as_usize();
905        let mut pos_u: usize = 0;
906        while pos_u < n_u
907            invariant
908                self.wf(),
909                *self == *old(self),
910                n_u == self.n_spec(),
911                self.n_spec() < Idx::max_nat(),
912                self.n_spec() <= self.cap_spec(),
913                pos_u <= n_u,
914            decreases n_u - pos_u,
915        {
916            let pos = match Idx::try_from_usize(pos_u) {
917                Some(p) => p,
918                None => {
919                    proof { assert(false); }  // pos_u < n_u < max_nat ⇒ Some
920                    return false;
921                }
922            };
923            let cur = self.dense.get_index(pos);
924            if values_equal(&cur, val) {
925                let id = self.indices.get_index(pos);
926                proof {
927                    // indices[pos] for pos < n is live: inverse-on-live gives
928                    // sparse[indices[pos]] == pos < n, and the round-trip
929                    // indices[sparse[id]] == id — exactly contains_spec.
930                    let indices = self.indices.view();
931                    let p = pos.as_nat() as int;
932                    assert(self.sparse.view()[indices[p].as_nat() as int].as_nat() == p);
933                    assert(self.contains_spec(id));
934                }
935                self.remove(id);
936                return true;
937            }
938            pos_u = pos_u + 1;
939        }
940        false
941    }
942
943    /// Read-only access to the dense value vector (production `data()`
944    /// parity: exposes the packed live values for iteration).
945    pub fn data(&self) -> (r: &SpVec<T, Idx, S, TRACK>)
946        ensures r == self.dense_ref(),
947    {
948        &self.dense
949    }
950
951    // ---- semi-persistence: delegate to the three inner vectors ----
952
953    pub(crate) fn mark(&mut self, shrink: ShrinkPolicy) -> (token: SparseSetToken)
954        requires
955            old(self).wf(),
956            TRACK,
957            old(self).can_mark_spec(),
958        ensures
959            final(self).wf(),
960            final(self).dense_view() == old(self).dense_view(),
961            final(self).sparse_view() == old(self).sparse_view(),
962            final(self).indices_view() == old(self).indices_view(),
963            final(self).dense_snapshots_view()
964                == old(self).dense_snapshots_view().push(old(self).dense_view()),
965            final(self).sparse_snapshots_view()
966                == old(self).sparse_snapshots_view().push(old(self).sparse_view()),
967            final(self).indices_snapshots_view()
968                == old(self).indices_snapshots_view().push(old(self).indices_view()),
969            token.dense_frame_idx_spec() == old(self).dense_depth_spec(),
970            token.sparse_frame_idx_spec() == old(self).sparse.depth_spec(),
971            token.indices_frame_idx_spec() == old(self).indices.depth_spec(),
972            final(self).dense_depth_spec() == old(self).dense_depth_spec() + 1,
973    {
974        let dense = self.dense.mark(shrink);
975        let sparse = self.sparse.mark(shrink);
976        let indices = self.indices.mark(shrink);
977        SparseSetToken { dense, sparse, indices }
978    }
979
980    // ------------------------------------------------------------------
981    // Total-operation shell. `try_restore` is deliberately
982    // absent: `restore` carries a snapshot-wellformedness precondition that
983    // `is_valid_token` does not answer (it quantifies over archived snapshot
984    // contents). The structural fix is archiving snapshot-wf in `wf` the way
985    // `ListArena` archives `arena_model_wf`; without that archive a total
986    // restore would need an O(cap) runtime permutation check.
987    // ------------------------------------------------------------------
988
989    /// Exec counterpart of `add`'s three-column capacity precondition.
990    pub fn can_add(&self) -> (b: bool)
991        requires self.wf(),
992        ensures b == self.can_add_spec(),
993    {
994        self.dense.can_push() && self.sparse.can_push() && self.indices.can_push()
995    }
996
997    /// Total add.
998    pub fn try_add(&mut self, value: T) -> (r: Result<Idx, crate::error::ContainerError>)
999        requires old(self).wf(),
1000        ensures
1001            final(self).wf(),
1002            r matches Err(e) ==> e == crate::error::ContainerError::CapacityExhausted
1003                && final(self).id_set() == old(self).id_set(),
1004            r matches Ok(id) ==> {
1005                &&& final(self).n_spec() == old(self).n_spec() + 1
1006                &&& final(self).contains_spec(id)
1007                &&& !old(self).id_set().contains(id.as_nat())
1008                &&& final(self).id_set() =~= old(self).id_set().insert(id.as_nat())
1009                &&& id.as_nat() <= old(self).cap_spec()
1010                &&& final(self).cap_spec() == if old(self).free_pool().len() == 0 {
1011                        old(self).cap_spec() + 1
1012                    } else {
1013                        old(self).cap_spec()
1014                    }
1015                &&& final(self).dense_view()[
1016                        final(self).sparse_view()[id.as_nat() as int].as_nat() as int] == value
1017                &&& (forall|k: Idx| #[trigger] old(self).contains_spec(k)
1018                        ==> final(self).contains_spec(k)
1019                            && final(self).dense_view()[
1020                                    final(self).sparse_view()[k.as_nat() as int].as_nat() as int]
1021                                == old(self).dense_view()[
1022                                    old(self).sparse_view()[k.as_nat() as int].as_nat() as int])
1023            },
1024            // snapshot-stack framing (eclasses: the aggregate's archive is
1025            // keyed on the component stacks).
1026            final(self).dense_snapshots_view() == old(self).dense_snapshots_view(),
1027            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view(),
1028            final(self).indices_snapshots_view() == old(self).indices_snapshots_view(),
1029    {
1030        if self.can_add() {
1031            Ok(self.add(value))
1032        } else {
1033            Err(crate::error::ContainerError::CapacityExhausted)
1034        }
1035    }
1036
1037    /// Total get: `Err(IndexOutOfBounds)` for an id that is not live.
1038    pub fn try_get(&self, id: Idx) -> (r: Result<T, crate::error::ContainerError>)
1039        requires self.wf(),
1040        ensures
1041            r is Ok <==> self.contains_spec(id),
1042            r matches Ok(v) ==> v
1043                == self.dense_view()[self.sparse_view()[id.as_nat() as int].as_nat() as int],
1044    {
1045        if self.contains(id) {
1046            Ok(self.get(id))
1047        } else {
1048            Err(crate::error::ContainerError::IndexOutOfBounds)
1049        }
1050    }
1051
1052    /// Total mark: TRACK first, then the six column headrooms as one answer.
1053    pub fn try_mark(&mut self, shrink: ShrinkPolicy)
1054        -> (r: Result<SparseSetToken, crate::error::ContainerError>)
1055        requires old(self).wf(),
1056        ensures
1057            final(self).wf(),
1058            r is Err ==> final(self).id_set() == old(self).id_set(),
1059            r matches Ok(token) ==> {
1060                &&& final(self).dense_view() == old(self).dense_view()
1061                &&& final(self).sparse_view() == old(self).sparse_view()
1062                &&& final(self).indices_view() == old(self).indices_view()
1063                &&& final(self).dense_snapshots_view()
1064                    == old(self).dense_snapshots_view().push(old(self).dense_view())
1065                &&& final(self).sparse_snapshots_view()
1066                    == old(self).sparse_snapshots_view().push(old(self).sparse_view())
1067                &&& final(self).indices_snapshots_view()
1068                    == old(self).indices_snapshots_view().push(old(self).indices_view())
1069                &&& token.dense_frame_idx_spec()
1070                    == final(self).dense_snapshots_view().len() - 1
1071                &&& token.sparse_frame_idx_spec()
1072                    == final(self).sparse_snapshots_view().len() - 1
1073                &&& token.indices_frame_idx_spec()
1074                    == final(self).indices_snapshots_view().len() - 1
1075            },
1076    {
1077        if !TRACK {
1078            return Err(crate::error::ContainerError::Untracked);
1079        }
1080        if self.dense.can_mark() && self.sparse.can_mark() && self.indices.can_mark() {
1081            Ok(self.mark(shrink))
1082        } else {
1083            Err(crate::error::ContainerError::DepthLimit)
1084        }
1085    }
1086
1087    /// Whether the composite token is restorable now. Every constituent must
1088    /// be restorable, which is the validation half of aggregate atomicity.
1089    pub fn is_valid_token(&self, token: &SparseSetToken) -> (b: bool)
1090        requires self.wf(),
1091        ensures b == self.is_restorable_spec(*token),
1092    {
1093        self.dense.is_valid_token(&token.dense)
1094            && self.sparse.is_valid_token(&token.sparse)
1095            && self.indices.is_valid_token(&token.indices)
1096    }
1097
1098    pub fn restore(&mut self, token: SparseSetToken)
1099        where T: core::default::Default, Idx: core::default::Default
1100        requires
1101            old(self).wf(),
1102            TRACK,
1103            old(self).restore_pre_spec(token),
1104            // the snapshots being restored form a valid sparse-set state
1105            sparse_set_snap_wf(
1106                old(self).snap_at(token).0,
1107                old(self).snap_at(token).1,
1108                old(self).snap_at(token).2),
1109        ensures
1110            final(self).wf(),
1111            final(self).dense_view() == old(self).snap_at(token).0,
1112            final(self).sparse_view() == old(self).snap_at(token).1,
1113            final(self).indices_view() == old(self).snap_at(token).2,
1114            final(self).dense_snapshots_view() == old(self).dense_snapshots_view()
1115                .subrange(0, token.dense_frame_idx_spec() as int),
1116            final(self).sparse_snapshots_view() == old(self).sparse_snapshots_view()
1117                .subrange(0, token.sparse_frame_idx_spec() as int),
1118            final(self).indices_snapshots_view() == old(self).indices_snapshots_view()
1119                .subrange(0, token.indices_frame_idx_spec() as int),
1120    {
1121        // Prevalidate all constituent tokens before restoring any of them:
1122        // a partially restored sparse set
1123        // (dense rolled back, sparse/indices not) violates the permutation
1124        // invariant unrecoverably. Provably-true no-op for verified callers.
1125        crate::guard::check_precondition(
1126            self.is_valid_token(&token),
1127            "SparseSet::restore: invalid, foreign, stale, consumed, or abandoned token component",
1128        );
1129        self.dense.restore(token.dense);
1130        self.sparse.restore(token.sparse);
1131        self.indices.restore(token.indices);
1132    }
1133}
1134
1135/// The sparse-set structural invariant stated over raw snapshot sequences (for
1136/// `restore`: the three snapshots being restored must jointly form a valid
1137/// state, so the restored set is `wf`). Mirrors `wf`'s clauses (2)/(1).
1138pub open(crate) spec fn sparse_set_snap_wf<T, Idx: IndexLike>(
1139    dense: Seq<T>, sparse: Seq<Idx>, indices: Seq<Idx>,
1140) -> bool {
1141    let cap = sparse.len();
1142    let n = dense.len();
1143    &&& indices.len() == cap
1144    &&& n <= cap
1145    &&& (forall|p: int| 0 <= p < cap ==> (#[trigger] indices[p]).as_nat() < cap)
1146    &&& (forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q ==>
1147            (#[trigger] indices[p]).as_nat() != (#[trigger] indices[q]).as_nat())
1148    &&& (forall|p: int| 0 <= p < n ==>
1149            sparse[(#[trigger] indices[p]).as_nat() as int].as_nat() == p)
1150}
1151
1152/// The set of values `{ indices[p].as_nat() : 0 <= p < m }`. (`ISet` for the
1153/// same reason as `id_set`: total comprehension, finiteness proved below.)
1154pub open(crate) spec fn image_prefix<Idx: IndexLike>(indices: Seq<Idx>, m: int) -> ISet<nat> {
1155    ISet::new(|id: nat| exists|p: int| 0 <= p < m && (#[trigger] indices[p]).as_nat() == id)
1156}
1157
1158/// An injective, in-range `indices` (over `[0, cap)`) hits every value in
1159/// `[0, cap)`: there is a `p < cap` with `indices[p].as_nat() == id` for each
1160/// `id < cap`. This is finite surjectivity-from-injectivity (pigeonhole),
1161/// proved via image cardinality: `|image_prefix(cap)| == cap` (each position
1162/// contributes a fresh value, by injectivity), and a `cap`-sized subset of the
1163/// `cap`-sized range `[0, cap)` must be the whole range.
1164pub(crate) proof fn lemma_perm_surjective<Idx: IndexLike>(indices: Seq<Idx>, cap: int, id: nat)
1165    requires
1166        cap <= indices.len(),
1167        id < cap,
1168        forall|p: int| 0 <= p < cap ==> (#[trigger] indices[p]).as_nat() < cap,
1169        forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q ==>
1170            (#[trigger] indices[p]).as_nat() != (#[trigger] indices[q]).as_nat(),
1171    ensures
1172        exists|p: int| 0 <= p < cap && (#[trigger] indices[p]).as_nat() == id,
1173{
1174    lemma_image_prefix_card(indices, cap);
1175    let img = image_prefix(indices, cap);
1176    let rng = ISet::new(|v: nat| v < cap);
1177    // img subset of rng (in-range), both size cap ⇒ equal ⇒ id in img.
1178    assert(img.subset_of(rng)) by {
1179        assert forall|v: nat| img.contains(v) implies rng.contains(v) by {
1180            let p = choose|p: int| 0 <= p < cap && (#[trigger] indices[p]).as_nat() == v;
1181        }
1182    }
1183    lemma_nat_range_card(cap);
1184    vstd::iset_lib::lemma_len_subset(img, rng);
1185    vstd::iset_lib::lemma_subset_equality(img, rng);
1186    assert(rng.contains(id));
1187    assert(img.contains(id));
1188}
1189
1190/// `|image_prefix(indices, m)| == m` for injective in-range `indices`, by
1191/// induction on `m`: the value at position `m-1` is fresh (injectivity), so it
1192/// extends the prefix image by exactly one.
1193pub(crate) proof fn lemma_image_prefix_card<Idx: IndexLike>(indices: Seq<Idx>, m: int)
1194    requires
1195        0 <= m <= indices.len(),
1196        forall|p: int, q: int| 0 <= p < m && 0 <= q < m && p != q ==>
1197            (#[trigger] indices[p]).as_nat() != (#[trigger] indices[q]).as_nat(),
1198    ensures
1199        image_prefix(indices, m).finite(),
1200        image_prefix(indices, m).len() == m,
1201    decreases m,
1202{
1203    if m == 0 {
1204        assert(image_prefix(indices, 0) =~= ISet::<nat>::empty());
1205    } else {
1206        lemma_image_prefix_card(indices, m - 1);
1207        let prev = image_prefix(indices, m - 1);
1208        let cur = image_prefix(indices, m);
1209        let last = indices[m - 1].as_nat();
1210        // last is not in prev (injectivity: no p < m-1 equals position m-1).
1211        assert(!prev.contains(last)) by {
1212            if prev.contains(last) {
1213                let p = choose|p: int| 0 <= p < m - 1 && (#[trigger] indices[p]).as_nat() == last;
1214                assert(indices[p].as_nat() != indices[m - 1].as_nat());
1215            }
1216        }
1217        // cur == prev ∪ {last}.
1218        assert(cur =~= prev.insert(last)) by {
1219            assert forall|v: nat| #![auto] cur.contains(v) <==> prev.insert(last).contains(v) by {
1220                if cur.contains(v) {
1221                    let p = choose|p: int| 0 <= p < m && (#[trigger] indices[p]).as_nat() == v;
1222                    if p < m - 1 { assert(prev.contains(v)); } else { assert(v == last); }
1223                }
1224            }
1225        }
1226        assert(cur.len() == prev.len() + 1);
1227    }
1228}
1229
1230/// `{ v : v < cap }` is finite with size `cap`.
1231pub(crate) proof fn lemma_nat_range_card(cap: int)
1232    requires cap >= 0,
1233    ensures
1234        ISet::new(|v: nat| v < cap).finite(),
1235        ISet::new(|v: nat| v < cap).len() == cap,
1236    decreases cap,
1237{
1238    if cap == 0 {
1239        assert(ISet::new(|v: nat| v < 0) =~= ISet::<nat>::empty());
1240    } else {
1241        lemma_nat_range_card(cap - 1);
1242        assert(ISet::new(|v: nat| v < cap)
1243            =~= ISet::new(|v: nat| v < cap - 1).insert((cap - 1) as nat));
1244    }
1245}
1246
1247/// A transposition of two positions in an injective sequence is injective.
1248/// `b` is `a` with values at `i` and `j` swapped (`a[i]==b[j]`, `a[j]==b[i]`,
1249/// equal elsewhere); both same length `cap`.
1250pub(crate) proof fn lemma_transposition_injective<Idx: IndexLike>(
1251    a: Seq<Idx>, b: Seq<Idx>, i: int, j: int, cap: int,
1252)
1253    requires
1254        0 <= i < cap <= a.len(),
1255        0 <= j < cap,
1256        b.len() == a.len(),
1257        i != j,
1258        b[i].as_nat() == a[j].as_nat(),
1259        b[j].as_nat() == a[i].as_nat(),
1260        forall|k: int| #![auto] 0 <= k < cap && k != i && k != j ==> b[k].as_nat() == a[k].as_nat(),
1261        forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q ==>
1262            (#[trigger] a[p]).as_nat() != (#[trigger] a[q]).as_nat(),
1263    ensures
1264        forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q ==>
1265            (#[trigger] b[p]).as_nat() != (#[trigger] b[q]).as_nat(),
1266{
1267    assert forall|p: int, q: int| 0 <= p < cap && 0 <= q < cap && p != q implies
1268        (#[trigger] b[p]).as_nat() != (#[trigger] b[q]).as_nat() by {
1269        // b's value at any position equals a's value at the transposed position;
1270        // since a is injective and the transposition is a bijection on indices,
1271        // distinct p,q map to distinct source positions, hence distinct values.
1272        let sp = if p == i { j } else if p == j { i } else { p };
1273        let sq = if q == i { j } else if q == j { i } else { q };
1274        assert(b[p].as_nat() == a[sp].as_nat());
1275        assert(b[q].as_nat() == a[sq].as_nat());
1276        assert(sp != sq);
1277        assert(0 <= sp < cap && 0 <= sq < cap);
1278    }
1279}
1280
1281/// Value equality via `PartialEq`, usable from verified code without
1282/// threading vstd's `obeys_eq_spec` plumbing: `external_body` with NO ensures
1283/// — the result is an unconstrained bool as far as proofs are concerned, so
1284/// nothing unsound can be derived from it; `remove_value`'s contract
1285/// consequently promises which STRUCTURAL change happened (an element left),
1286/// not which value matched. The scan behavior is pinned by the ported
1287/// production proptests. Trust ledger: group E.
1288#[verifier::external_body]
1289fn values_equal<T: PartialEq>(a: &T, b: &T) -> bool {
1290    a == b
1291}
1292
1293// ---------------------------------------------------------------------------
1294// Production-compatible constructors. Generic `with_store`
1295// plus the two concrete instantiations production exposes; all establish the
1296// empty `wf` (the permutation invariant is vacuous at cap == n == 0).
1297// ---------------------------------------------------------------------------
1298
1299impl<T, Idx, S, const TRACK: bool> SparseSet<T, Idx, S, TRACK>
1300where
1301    T: Sized + Copy,
1302    Idx: IndexLike + Tagged,
1303    S: DiffStore<T, Idx, TRACK>,
1304{
1305    /// Empty sparse set over a caller-supplied (empty, well-formed) dense
1306    /// store. Production `with_store` parity.
1307    pub(crate) fn with_store(store: S) -> (s: Self)
1308        requires
1309            store.wf(),
1310            store.data().len() == 0,
1311        ensures
1312            s.wf(),
1313            s.n_spec() == 0,
1314            s.cap_spec() == 0,
1315            s.dense_snapshots_view().len() == 0,
1316            s.sparse_snapshots_view().len() == 0,
1317            s.indices_snapshots_view().len() == 0,
1318    {
1319        let s = SparseSet {
1320            dense: SpVec::with_store(store),
1321            sparse: SpVec::<Idx, Idx, InlineStore<Idx, Idx>, TRACK>::new(),
1322            indices: SpVec::<Idx, Idx, InlineStore<Idx, Idx>, TRACK>::new(),
1323        };
1324        proof {
1325            // Empty everything: every wf clause quantifies over [0, 0).
1326            assert(s.cap_spec() == 0);
1327            assert(s.n_spec() == 0);
1328        }
1329        s
1330    }
1331}
1332
1333impl<T, Idx, const TRACK: bool> SparseSet<T, Idx, crate::parallel_store::ParallelStore<T, Idx>, TRACK>
1334where
1335    T: Sized + Copy,
1336    Idx: IndexLike + Tagged,
1337{
1338    /// Empty sparse set over a `ParallelStore` (any `T: Copy`; production
1339    /// `SparseSet::new` parity).
1340    pub fn new() -> (s: Self)
1341        ensures s.wf(), s.n_spec() == 0, s.cap_spec() == 0,
1342    {
1343        Self::with_store(crate::parallel_store::ParallelStore::new())
1344    }
1345}
1346
1347impl<T, Idx, const TRACK: bool> SparseSet<T, Idx, crate::inline_store::InlineStore<T, Idx>, TRACK>
1348where
1349    T: Tagged + Sized + Copy,
1350    Idx: IndexLike + Tagged,
1351{
1352    /// Empty sparse set over an `InlineStore` (`T: Tagged`; production
1353    /// `SparseSet::new_inline` parity).
1354    pub fn new_inline() -> (s: Self)
1355        ensures s.wf(), s.n_spec() == 0, s.cap_spec() == 0,
1356            s.dense_snapshots_view().len() == 0,
1357            s.sparse_snapshots_view().len() == 0,
1358            s.indices_snapshots_view().len() == 0,
1359    {
1360        Self::with_store(crate::inline_store::InlineStore::new())
1361    }
1362}
1363
1364} // verus!
1365
1366// prod-parity: production derives `Debug` on `SparseSetToken`; manual here
1367// (composes three `VecToken`s, now `Debug`).
1368impl core::fmt::Debug for SparseSetToken {
1369    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1370        f.debug_struct("SparseSetToken")
1371            .field("dense", &self.dense)
1372            .field("sparse", &self.sparse)
1373            .field("indices", &self.indices)
1374            .finish()
1375    }
1376}
1377
1378// Production-surface parity (production ships Default on this variant).
1379impl<T, Idx, const TRACK: bool> Default
1380    for SparseSet<T, Idx, crate::parallel_store::ParallelStore<T, Idx>, TRACK>
1381where
1382    T: Sized + Copy,
1383    Idx: IndexLike + Tagged,
1384{
1385    fn default() -> Self {
1386        Self::new()
1387    }
1388}