lazily 0.34.0

Lazy reactive signals with dependency tracking and cache invalidation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! Keyed reactive collections: the generic [`ReactiveMap`] and its
//! [`CellMap`] / [`SlotMap`] specializations (`#reactivemap`).
//!
//! `Context` addresses nodes by opaque [`SlotId`](crate::context). These types
//! add a *keyed* layer on top: a hash collection whose **membership is itself
//! reactive**, with one independently-tracked reactive node per entry.
//!
//! # One primitive, two specializations
//!
//! There is a single keyed primitive, generic over the entry's **handle kind**
//! `H` (the [`MapHandle`] trait, implemented by [`CellHandle`] for input cells
//! and [`SlotHandle`] for derived slots):
//!
//! - **[`CellMap<K, V>`] = `ReactiveMap<K, V, CellHandle<V>>`** — **input-cell**
//!   entries. Adds cell-only [`set`](ReactiveMap::set) and eager value-minting
//!   ([`entry`](ReactiveMap::entry) / [`entry_with`](ReactiveMap::entry_with)).
//! - **[`SlotMap<K, V>`] = `ReactiveMap<K, V, SlotHandle<V>>`** — **derived-slot**
//!   entries. [`get_or_insert_with`](ReactiveMap::get_or_insert_with) mints a
//!   slot on first access (**lazy materialization**); a slot's value is derived,
//!   so `SlotMap` has **no `set`**. Eager materialization is a pre-mint loop over
//!   the keyset ([`materialize_all`](ReactiveMap::materialize_all)); lazy is
//!   mint-on-access. There is **no eager/lazy mode flag**.
//!
//! The shared surface — `get_or_insert_with` / `remove` / `move_*` / membership /
//! order / `keys` / `len` / `contains_key` — lives on the generic `ReactiveMap`.
//! `set` and eager value-minting are the `CellMap`-only specialization; the
//! pre-mint eager helper is the `SlotMap`-only specialization.
//!
//! # Fine-grained vs. coarse
//!
//! Modelling a collection as a single `ctx.cell(HashMap<K, V>)` is *coarse*:
//! every single-entry mutation replaces the whole map, so any reader of any
//! entry is invalidated and (over a wire) the entire map is re-sent.
//!
//! [`ReactiveMap`] is *fine-grained*. Each entry is its own reactive node, so:
//!
//! - A reader that depends on entry `a` is **not** invalidated when entry `b`
//!   changes — only that entry's dependents recompute.
//! - Membership (the set of keys) is tracked by a dedicated version cell, so
//!   [`keys`](ReactiveMap::keys) / [`len`](ReactiveMap::len) readers recompute
//!   only when keys are **added or removed**, not when an existing value changes.
//!
//! ```
//! use lazily::{CellMap, Context};
//!
//! let ctx = Context::new();
//! let scores: CellMap<&'static str, i32> = CellMap::new(&ctx);
//! let alice = scores.entry(&ctx, "alice", 10);
//! let bob = scores.entry(&ctx, "bob", 20);
//!
//! // A computed over the whole collection recomputes only on membership change.
//! let n = ctx.computed({
//!     let scores = scores.clone();
//!     move |ctx| scores.len(ctx)
//! });
//! assert_eq!(ctx.get(&n), 2);
//!
//! // Mutating an existing entry does not change membership.
//! alice.set(&ctx, 11);
//! assert_eq!(ctx.get(&n), 2);
//! assert_eq!(bob.get(&ctx), 20);
//! ```

use std::cell::{Cell as StdCell, RefCell};
use std::collections::HashMap;
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;

use crate::Context;
use crate::cell::CellHandle;
use crate::slot::SlotHandle;

/// Which kind of reactive node a [`ReactiveMap`] entry is — the handle-kind axis
/// the map abstracts over.
///
/// Mirrors `EntryKind` in `lazily-formal`'s `Materialization` module.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
    /// An **input** cell ([`CellHandle`]) — always materialized on `get`.
    Cell,
    /// A **derived** slot ([`SlotHandle`]) — materialized eagerly (pre-mint) or
    /// lazily on first read.
    Slot,
}

mod sealed {
    pub trait Sealed {}
}

/// The entry-handle axis a [`ReactiveMap`] abstracts over. Implemented by
/// [`CellHandle`] (input cells) and [`SlotHandle`] (derived slots) only — the
/// two node kinds of the cell model. Sealed: bindings do not add new kinds.
pub trait MapHandle<V>: sealed::Sealed + Copy + 'static {
    /// This handle's entry kind. `CellHandle` is [`EntryKind::Cell`]; `SlotHandle`
    /// is [`EntryKind::Slot`].
    const KIND: EntryKind;

    /// Allocate the node for one entry in `ctx`, with `compute` producing its
    /// canonical value. An input cell sets the value directly; a derived slot
    /// wraps `compute` as its recomputation.
    fn materialize(ctx: &Context, compute: impl Fn(&Context) -> V + 'static) -> Self
    where
        V: PartialEq + Clone + 'static;

    /// Read this entry's value through its owning context (subscribes the caller
    /// as any cell/slot read does).
    fn observe(self, ctx: &Context) -> V
    where
        V: Clone + 'static;

    /// Detach this entry's node from the graph on removal — clear its cached
    /// value and its dependents.
    fn clear_dependents(self, ctx: &Context);
}

impl<V> sealed::Sealed for CellHandle<V> {}
impl<V: 'static> MapHandle<V> for CellHandle<V> {
    const KIND: EntryKind = EntryKind::Cell;

    fn materialize(ctx: &Context, compute: impl Fn(&Context) -> V + 'static) -> Self
    where
        V: PartialEq + Clone + 'static,
    {
        // An input has no derivation: materialize by setting its value directly.
        ctx.cell(compute(ctx))
    }

    fn observe(self, ctx: &Context) -> V
    where
        V: Clone + 'static,
    {
        ctx.get_cell(&self)
    }

    fn clear_dependents(self, ctx: &Context) {
        CellHandle::clear_dependents(&self, ctx);
    }
}

impl<V> sealed::Sealed for SlotHandle<V> {}
impl<V: 'static> MapHandle<V> for SlotHandle<V> {
    const KIND: EntryKind = EntryKind::Slot;

    fn materialize(ctx: &Context, compute: impl Fn(&Context) -> V + 'static) -> Self
    where
        V: PartialEq + Clone + 'static,
    {
        // A derived node: the same node an eager pre-mint would allocate.
        ctx.computed(compute)
    }

    fn observe(self, ctx: &Context) -> V
    where
        V: Clone + 'static,
    {
        ctx.get(&self)
    }

    fn clear_dependents(self, ctx: &Context) {
        self.clear(ctx);
    }
}

/// A keyed reactive collection generic over the entry handle kind `H`: a hash map
/// of `K -> H` with reactive membership and independently-tracked per-entry nodes.
///
/// Cheap to [`Clone`] (an `Rc` to the shared inner state) so it can be captured
/// by compute/effect closures. All operations are taken against the owning
/// [`Context`]; like the rest of `lazily`, the graph data lives in the context.
///
/// The two specializations a binding exposes are [`CellMap`] (input cells) and
/// [`SlotMap`] (derived slots). See the module docs.
pub struct ReactiveMap<K, V, H> {
    inner: Rc<ReactiveMapInner<K, H>>,
    _marker: PhantomData<V>,
}

struct ReactiveMapInner<K, H> {
    /// Per-key reactive nodes. Each entry is its own reactive node.
    entries: RefCell<HashMap<K, H>>,
    /// Insertion-ordered authoritative key list (snapshot returned by `keys`).
    order: RefCell<Vec<K>>,
    /// Reactive *set-membership* signal. Holds a monotonic version bumped only
    /// when the **set** of keys changes (add/remove). Reading it (in
    /// `len`/`contains_key`/`is_empty`) subscribes the caller to membership
    /// changes without coupling to entry values *or to pure reordering*.
    membership: CellHandle<u64>,
    /// Plain (untracked) mirror of the membership version so mutators can bump
    /// the reactive cell without registering a spurious dependency.
    version: StdCell<u64>,
    /// Reactive *order* signal. Bumped on add/remove **and on move/reorder**.
    /// `keys` subscribes here so an atomic ordered move (`#lzcellmove`)
    /// invalidates key-order readers without disturbing `len`/`contains_key`
    /// readers that only care about set identity.
    order_signal: CellHandle<u64>,
    /// Untracked mirror of the order version.
    order_version: StdCell<u64>,
}

impl<K, V, H> Clone for ReactiveMap<K, V, H> {
    fn clone(&self) -> Self {
        Self {
            inner: Rc::clone(&self.inner),
            _marker: PhantomData,
        }
    }
}

impl<K, V, H> ReactiveMap<K, V, H>
where
    K: Eq + Hash + Clone + 'static,
    V: PartialEq + Clone + 'static,
    H: MapHandle<V>,
{
    /// Create an empty collection bound to `ctx`.
    pub fn new(ctx: &Context) -> Self {
        Self {
            inner: Rc::new(ReactiveMapInner {
                entries: RefCell::new(HashMap::new()),
                order: RefCell::new(Vec::new()),
                membership: ctx.cell(0u64),
                version: StdCell::new(0),
                order_signal: ctx.cell(0u64),
                order_version: StdCell::new(0),
            }),
            _marker: PhantomData,
        }
    }

    /// Bump the *order* signal (invalidates `keys` readers). Add/remove also
    /// bump this; a pure move bumps **only** this.
    fn bump_order(&self, ctx: &Context) {
        let next = self.inner.order_version.get().wrapping_add(1);
        self.inner.order_version.set(next);
        ctx.set_cell(&self.inner.order_signal, next);
    }

    /// Bump set-membership (invalidates `len`/`contains_key` readers). Always
    /// paired with an order bump because add/remove change order too.
    fn bump_membership(&self, ctx: &Context) {
        let next = self.inner.version.get().wrapping_add(1);
        self.inner.version.set(next);
        // A write, not a tracked read: membership readers are invalidated, but
        // no dependency is registered on whatever frame called the mutator.
        ctx.set_cell(&self.inner.membership, next);
        // The key set changed, so the ordered key list changed too.
        self.bump_order(ctx);
    }

    /// Mint the entry node for `key` (via `H::materialize` with `compute` as its
    /// canonical value producer) on first access, caching the handle and bumping
    /// reactive membership. Re-minting an existing key returns the cached handle.
    fn mint_with(&self, ctx: &Context, key: K, compute: impl Fn(&Context) -> V + 'static) -> H {
        if let Some(handle) = self.inner.entries.borrow().get(&key).copied() {
            return handle; // warm: already allocated.
        }
        let handle = H::materialize(ctx, compute);
        self.inner.entries.borrow_mut().insert(key.clone(), handle);
        self.inner.order.borrow_mut().push(key);
        self.bump_membership(ctx);
        handle
    }

    /// Get the value at `key`, minting the entry via `factory(&key)` first if the
    /// key is absent — the mint-on-access recipe. For a [`SlotMap`] this is the
    /// **lazy materialization** pull; for a [`CellMap`] it seeds an input cell.
    ///
    /// Bumps reactive membership only on insert; an existing key returns its
    /// current value without re-running the factory.
    pub fn get_or_insert_with(
        &self,
        ctx: &Context,
        key: K,
        factory: impl Fn(&K) -> V + 'static,
    ) -> V {
        if let Some(handle) = self.inner.entries.borrow().get(&key).copied() {
            return handle.observe(ctx);
        }
        let k = key.clone();
        let handle = self.mint_with(ctx, key, move |_ctx| factory(&k));
        handle.observe(ctx)
    }

    /// Return the existing entry handle for `key`, or `None`. Non-reactive: this
    /// does not subscribe the caller to membership.
    pub fn handle(&self, key: &K) -> Option<H> {
        self.inner.entries.borrow().get(key).copied()
    }

    /// Read the value at `key` if present. Reactive on that entry only (a reader
    /// is invalidated when this entry changes, not when siblings change).
    pub fn get(&self, ctx: &Context, key: &K) -> Option<V> {
        let handle = self.inner.entries.borrow().get(key).copied();
        handle.map(|h| h.observe(ctx))
    }

    /// Remove `key`'s entry. Bumps reactive membership and clears the removed
    /// entry's dependents. Returns whether the key was present.
    ///
    /// Note: the underlying node id is not recycled (the runtime exposes no
    /// node-free API yet); the orphaned node stops driving any dependents.
    pub fn remove(&self, ctx: &Context, key: &K) -> bool {
        let removed = self.inner.entries.borrow_mut().remove(key);
        let Some(handle) = removed else {
            return false;
        };
        self.inner.order.borrow_mut().retain(|k| k != key);
        handle.clear_dependents(ctx);
        self.bump_membership(ctx);
        true
    }

    /// Reactive snapshot of the keys in their current order. Subscribes the
    /// caller to **order** changes (add/remove **and move/reorder**), not to
    /// per-entry value changes.
    pub fn keys(&self, ctx: &Context) -> Vec<K> {
        let _ = ctx.get_cell(&self.inner.order_signal);
        self.inner.order.borrow().clone()
    }

    /// The currently-materialized (present) keys, in first-materialization order.
    /// Non-reactive; the present set only grows (deferral, not de-allocation).
    pub fn present_keys(&self) -> Vec<K> {
        self.inner.order.borrow().clone()
    }

    /// Number of currently-materialized (present) entries. Non-reactive.
    pub fn present_count(&self) -> usize {
        self.inner.order.borrow().len()
    }

    /// Whether `key` is currently materialized (present in the allocated set).
    /// Non-reactive.
    pub fn is_present(&self, key: &K) -> bool {
        self.inner.entries.borrow().contains_key(key)
    }

    /// Current 0-based position of `key` in the order, or `None` if absent.
    /// Non-reactive.
    pub fn position(&self, key: &K) -> Option<usize> {
        self.inner.order.borrow().iter().position(|k| k == key)
    }

    /// Atomically move `key` to `index` in the order (`#lzcellmove`).
    ///
    /// This is the *atomic, optimized* reorder: the entry keeps the **same**
    /// node, the same dependents, and its CRDT lineage — unlike the naive
    /// `remove` + re-mint which re-allocates the node and bumps membership twice.
    /// Only the order signal is bumped (once), so `keys` readers recompute but
    /// `len`/`contains_key` readers — which track set identity, not order —
    /// stay cached.
    ///
    /// `index` is clamped to `[0, len)`. Returns whether `key` was present.
    pub fn move_to(&self, ctx: &Context, key: &K, index: usize) -> bool {
        let mut order = self.inner.order.borrow_mut();
        let Some(from) = order.iter().position(|k| k == key) else {
            return false;
        };
        let to = index.min(order.len().saturating_sub(1));
        if from == to {
            return true; // no-op: do not invalidate readers needlessly.
        }
        let k = order.remove(from);
        order.insert(to, k);
        drop(order);
        self.bump_order(ctx);
        true
    }

    /// Atomically move `key` to just before `anchor` in the order
    /// (`#lzcellmove`). No-op if either key is absent or already adjacent in the
    /// requested position. Returns whether the move could be expressed.
    pub fn move_before(&self, ctx: &Context, key: &K, anchor: &K) -> bool {
        let Some(anchor_idx) = self.position(anchor) else {
            return false;
        };
        let from = match self.position(key) {
            Some(i) => i,
            None => return false,
        };
        // Removing `key` first shifts `anchor` left by one when key precedes it.
        let target = if from < anchor_idx {
            anchor_idx - 1
        } else {
            anchor_idx
        };
        self.move_to(ctx, key, target)
    }

    /// Atomically move `key` to just after `anchor` in the order (`#lzcellmove`).
    pub fn move_after(&self, ctx: &Context, key: &K, anchor: &K) -> bool {
        let Some(anchor_idx) = self.position(anchor) else {
            return false;
        };
        let from = match self.position(key) {
            Some(i) => i,
            None => return false,
        };
        let target = if from <= anchor_idx {
            anchor_idx
        } else {
            anchor_idx + 1
        };
        self.move_to(ctx, key, target)
    }

    /// Reactive entry count. Subscribes the caller to membership changes only.
    pub fn len(&self, ctx: &Context) -> usize {
        let _ = ctx.get_cell(&self.inner.membership);
        self.inner.order.borrow().len()
    }

    /// Reactive emptiness check. Subscribes the caller to membership changes.
    pub fn is_empty(&self, ctx: &Context) -> bool {
        self.len(ctx) == 0
    }

    /// Reactive membership test for `key`. Subscribes the caller to membership
    /// changes (add/remove of any key), not to value changes.
    pub fn contains_key(&self, ctx: &Context, key: &K) -> bool {
        let _ = ctx.get_cell(&self.inner.membership);
        self.inner.entries.borrow().contains_key(key)
    }

    /// Non-reactive count. Does not subscribe the caller to anything.
    pub fn len_untracked(&self) -> usize {
        self.inner.order.borrow().len()
    }

    /// This map's entry kind ([`EntryKind::Cell`] for a [`CellMap`],
    /// [`EntryKind::Slot`] for a [`SlotMap`]).
    pub fn entry_kind(&self) -> EntryKind {
        H::KIND
    }
}

/// A keyed **input-cell** collection: every entry is a settable [`CellHandle<V>`].
///
/// The `CellMap` specialization of [`ReactiveMap`] adds cell-only `set` and eager
/// value-minting (`entry` / `entry_with`) on top of the shared reactive keyed
/// surface.
pub type CellMap<K, V> = ReactiveMap<K, V, CellHandle<V>>;

/// A keyed **derived-slot** collection: every entry is a [`SlotHandle<V>`] whose
/// value is derived. `get_or_insert_with` mints a slot on first access (lazy
/// materialization); [`materialize_all`](ReactiveMap::materialize_all) pre-mints
/// the keyset (eager). A slot's value is derived, so `SlotMap` has **no `set`**.
pub type SlotMap<K, V> = ReactiveMap<K, V, SlotHandle<V>>;

/// `CellMap`-only surface: eager value-minting and `set` (an input is settable).
impl<K, V> ReactiveMap<K, V, CellHandle<V>>
where
    K: Eq + Hash + Clone + 'static,
    V: PartialEq + Clone + 'static,
{
    /// Return the value cell for `key`, minting it with `default` (computed via
    /// the closure) on first access. Subsequent calls return the cached handle.
    ///
    /// Adding a new key bumps reactive membership; re-fetching an existing key
    /// does not. Cell-only: eager value-minting has no derived-slot analog.
    pub fn entry_with(&self, ctx: &Context, key: K, default: impl FnOnce() -> V) -> CellHandle<V> {
        if let Some(handle) = self.inner.entries.borrow().get(&key).copied() {
            return handle;
        }
        let value = default();
        self.mint_with(ctx, key, move |_ctx| value.clone())
    }

    /// Return the value cell for `key`, minting it with `default` on first
    /// access. Convenience wrapper over [`entry_with`](Self::entry_with).
    pub fn entry(&self, ctx: &Context, key: K, default: V) -> CellHandle<V> {
        self.entry_with(ctx, key, || default)
    }

    /// Set the value at `key`, inserting a new entry (and bumping membership) if
    /// it does not exist yet. Updating an existing entry leaves membership
    /// untouched and invalidates only that entry's dependents.
    ///
    /// Cell-only: an input is settable; a derived [`SlotMap`] slot is not.
    pub fn set(&self, ctx: &Context, key: K, value: V) {
        if let Some(handle) = self.inner.entries.borrow().get(&key).copied() {
            handle.set(ctx, value);
            return;
        }
        self.entry_with(ctx, key, || value);
    }
}

/// `SlotMap`-only surface: the eager pre-mint helper. Lazy materialization is
/// [`get_or_insert_with`](ReactiveMap::get_or_insert_with) on the shared surface.
impl<K, V> ReactiveMap<K, V, SlotHandle<V>>
where
    K: Eq + Hash + Clone + 'static,
    V: PartialEq + Clone + 'static,
{
    /// **Eager materialization**: pre-mint a derived slot for every key in
    /// `keys` via `factory`, up front. Observationally identical to minting each
    /// key lazily on first read — it only changes *when* the nodes are allocated.
    pub fn materialize_all(
        &self,
        ctx: &Context,
        keys: impl IntoIterator<Item = K>,
        factory: impl Fn(&K) -> V + 'static,
    ) {
        let factory = Rc::new(factory);
        for key in keys {
            let f = Rc::clone(&factory);
            self.get_or_insert_with(ctx, key, move |k| f(k));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn entry_caches_one_cell_per_key() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        let a1 = map.entry(&ctx, "a", 1);
        let a2 = map.entry(&ctx, "a", 999);
        // Same key -> same cell; the second default is ignored.
        assert_eq!(a1.id, a2.id);
        assert_eq!(a1.get(&ctx), 1);
        assert_eq!(map.len_untracked(), 1);
    }

    #[test]
    fn get_or_insert_with_mints_once_then_returns_existing() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        let calls = Rc::new(StdCell::new(0));
        // First access mints via the factory.
        assert_eq!(
            map.get_or_insert_with(&ctx, "a", {
                let calls = Rc::clone(&calls);
                move |_| {
                    calls.set(calls.get() + 1);
                    7
                }
            }),
            7
        );
        assert_eq!(map.len_untracked(), 1);
        // Second access returns the existing value; factory is NOT called again.
        assert_eq!(
            map.get_or_insert_with(&ctx, "a", {
                let calls = Rc::clone(&calls);
                move |_| {
                    calls.set(calls.get() + 1);
                    999
                }
            }),
            7
        );
        assert_eq!(calls.get(), 1);
        // An explicit set is observed by a subsequent get_or_insert_with.
        map.set(&ctx, "a", 42);
        assert_eq!(map.get_or_insert_with(&ctx, "a", |_| 0), 42);
    }

    #[test]
    fn membership_is_reactive_but_value_changes_are_not() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        let a = map.entry(&ctx, "a", 1);
        map.entry(&ctx, "b", 2);

        let count = ctx.computed({
            let map = map.clone();
            move |ctx| map.len(ctx)
        });
        assert_eq!(ctx.get(&count), 2);

        // Mutating an existing entry must NOT invalidate the membership reader.
        a.set(&ctx, 100);
        assert!(ctx.is_set(&count), "membership reader stayed cached");
        assert_eq!(ctx.get(&count), 2);

        // Adding a key DOES invalidate it.
        map.entry(&ctx, "c", 3);
        assert_eq!(ctx.get(&count), 3);

        // Removing a key invalidates it too.
        assert!(map.remove(&ctx, &"b"));
        assert_eq!(ctx.get(&count), 2);
        assert_eq!(map.keys(&ctx), vec!["a", "c"]);
    }

    #[test]
    fn per_entry_reads_are_independent() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        let a = map.entry(&ctx, "a", 1);
        let b = map.entry(&ctx, "b", 2);

        let view_a = ctx.computed({
            let map = map.clone();
            move |ctx| map.get(ctx, &"a").unwrap_or(0) * 10
        });
        assert_eq!(ctx.get(&view_a), 10);

        // Changing b must not invalidate a's reader.
        b.set(&ctx, 222);
        assert!(ctx.is_set(&view_a), "sibling change must not invalidate");
        assert_eq!(ctx.get(&view_a), 10);

        // Changing a does.
        a.set(&ctx, 5);
        assert_eq!(ctx.get(&view_a), 50);
    }

    #[test]
    fn slot_map_mints_lazily_and_caches() {
        let ctx = Context::new();
        let fam: SlotMap<u32, u32> = SlotMap::new(&ctx);
        // Nothing present until first access.
        assert_eq!(fam.present_count(), 0);
        assert_eq!(fam.get_or_insert_with(&ctx, 7, |&k| k * 2), 14);
        assert_eq!(fam.present_count(), 1);
        assert!(fam.is_present(&7));
        // Same key -> same derived slot (value preserved, factory not re-run).
        let h = fam.handle(&7).unwrap();
        assert_eq!(h.get(&ctx), 14);
        assert_eq!(fam.get_or_insert_with(&ctx, 7, |&k| k * 999), 14);
    }

    #[test]
    fn slot_map_materialize_all_is_eager() {
        let ctx = Context::new();
        let fam: SlotMap<u32, u32> = SlotMap::new(&ctx);
        fam.materialize_all(&ctx, [0u32, 1, 2, 5, 9], |&k| k * 3);
        assert_eq!(fam.present_count(), 5);
        for k in [0u32, 1, 2, 5, 9] {
            assert!(fam.is_present(&k));
        }
        assert_eq!(fam.get(&ctx, &5), Some(15));
        assert_eq!(fam.entry_kind(), EntryKind::Slot);
    }

    #[test]
    fn move_to_reorders_keys_and_keeps_cell_identity() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        let a = map.entry(&ctx, "a", 1);
        map.entry(&ctx, "b", 2);
        map.entry(&ctx, "c", 3);
        assert_eq!(map.keys(&ctx), vec!["a", "b", "c"]);

        // Move "c" to the front.
        assert!(map.move_to(&ctx, &"c", 0));
        assert_eq!(map.keys(&ctx), vec!["c", "a", "b"]);

        // The moved entry keeps the SAME value cell (identity + value intact).
        assert_eq!(map.handle(&"a").unwrap().id, a.id);
        assert_eq!(map.get(&ctx, &"a"), Some(1));
        assert_eq!(map.get(&ctx, &"c"), Some(3));

        // Absent key -> false, no reorder.
        assert!(!map.move_to(&ctx, &"z", 0));
        assert_eq!(map.keys(&ctx), vec!["c", "a", "b"]);
    }

    #[test]
    fn pure_move_invalidates_order_but_not_membership_readers() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        map.entry(&ctx, "a", 1);
        map.entry(&ctx, "b", 2);
        map.entry(&ctx, "c", 3);

        let order_reader = ctx.computed({
            let map = map.clone();
            move |ctx| map.keys(ctx).join(",")
        });
        let count = ctx.computed({
            let map = map.clone();
            move |ctx| map.len(ctx)
        });
        let has_b = ctx.computed({
            let map = map.clone();
            move |ctx| map.contains_key(ctx, &"b")
        });
        assert_eq!(ctx.get(&order_reader), "a,b,c");
        assert_eq!(ctx.get(&count), 3);
        assert!(ctx.get(&has_b));

        // A pure reorder must invalidate the order reader...
        assert!(map.move_to(&ctx, &"a", 2));
        assert_eq!(ctx.get(&order_reader), "b,c,a");
        // ...but NOT the set-identity readers (len / contains_key stay cached).
        assert!(
            ctx.is_set(&count),
            "len reader must stay cached on pure move"
        );
        assert!(
            ctx.is_set(&has_b),
            "contains_key reader must stay cached on pure move"
        );
        assert_eq!(ctx.get(&count), 3);
    }

    #[test]
    fn move_to_is_noop_when_position_unchanged() {
        let ctx = Context::new();
        let map: CellMap<&str, i32> = CellMap::new(&ctx);
        map.entry(&ctx, "a", 1);
        map.entry(&ctx, "b", 2);

        let order_reader = ctx.computed({
            let map = map.clone();
            move |ctx| map.keys(ctx).join(",")
        });
        assert_eq!(ctx.get(&order_reader), "a,b");

        // Moving to its current index is a no-op and must not invalidate.
        assert!(map.move_to(&ctx, &"a", 0));
        assert!(
            ctx.is_set(&order_reader),
            "no-op move must not invalidate keys readers"
        );
        // Index past the end clamps to last position.
        assert!(map.move_to(&ctx, &"a", 99));
        assert_eq!(ctx.get(&order_reader), "b,a");
    }

    #[test]
    fn move_before_and_after_place_relative_to_anchor() {
        let ctx = Context::new();
        let map: CellMap<i32, i32> = CellMap::new(&ctx);
        for k in 0..4 {
            map.entry(&ctx, k, k * 10);
        }
        assert_eq!(map.keys(&ctx), vec![0, 1, 2, 3]);

        // Move 3 before 1.
        assert!(map.move_before(&ctx, &3, &1));
        assert_eq!(map.keys(&ctx), vec![0, 3, 1, 2]);

        // Move 0 after 2.
        assert!(map.move_after(&ctx, &0, &2));
        assert_eq!(map.keys(&ctx), vec![3, 1, 2, 0]);

        // Unknown anchor / key -> false.
        assert!(!map.move_before(&ctx, &3, &99));
        assert!(!map.move_after(&ctx, &99, &2));
    }

    #[test]
    fn contains_key_tracks_membership() {
        let ctx = Context::new();
        let map: CellMap<i32, i32> = CellMap::new(&ctx);
        let has_5 = ctx.computed({
            let map = map.clone();
            move |ctx| map.contains_key(ctx, &5)
        });
        assert!(!ctx.get(&has_5));
        map.entry(&ctx, 5, 50);
        assert!(ctx.get(&has_5));
    }
}