zwire 0.3.0

Zero-dependency, no_std-compatible transactional reactive state engine: scoped push-pull arena, rebaseable optimistic layers + STM drafts, exact incremental Top-K collections, and open @zwire/core wire protocols
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Comprehensive integration tests for Wave 3 Rust features (F-B, F-C, F-D, F-E).
#![cfg(feature = "core")]

use core::cell::{Cell, RefCell};
use core::future::{Future, poll_fn};
use core::pin::Pin;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::task::{Context, Poll, Waker};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::task::Wake;

use zwire::prelude::*;

#[derive(Default)]
struct WakeCounter(AtomicUsize);
impl Wake for WakeCounter {
    fn wake(self: Arc<Self>) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }
}

/// Manual controllable future for deterministic async / cancellation / out-of-order tests.
struct ManualFuture<T> {
    result: Rc<RefCell<Option<T>>>,
    waker: Rc<RefCell<Option<Waker>>>,
    dropped: Rc<Cell<bool>>,
}

struct ManualHandle<T> {
    result: Rc<RefCell<Option<T>>>,
    waker: Rc<RefCell<Option<Waker>>>,
    dropped: Rc<Cell<bool>>,
}

impl<T> ManualHandle<T> {
    fn resolve(&self, val: T) {
        *self.result.borrow_mut() = Some(val);
        if let Some(w) = self.waker.borrow_mut().take() {
            w.wake();
        }
    }

    fn is_dropped(&self) -> bool {
        self.dropped.get()
    }
}

fn manual_future<T>() -> (ManualFuture<T>, ManualHandle<T>) {
    let result = Rc::new(RefCell::new(None));
    let waker = Rc::new(RefCell::new(None));
    let dropped = Rc::new(Cell::new(false));
    (
        ManualFuture {
            result: Rc::clone(&result),
            waker: Rc::clone(&waker),
            dropped: Rc::clone(&dropped),
        },
        ManualHandle {
            result,
            waker,
            dropped,
        },
    )
}

impl<T> Future for ManualFuture<T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(val) = self.result.borrow_mut().take() {
            return Poll::Ready(val);
        }
        *self.waker.borrow_mut() = Some(cx.waker().clone());
        Poll::Pending
    }
}

impl<T> Drop for ManualFuture<T> {
    fn drop(&mut self) {
        self.dropped.set(true);
    }
}

// ============================================================================
// F-B: split_effect, watch, peek, subscribe_selected, dispose_id, BatchGuard
// ============================================================================

#[test]
fn scope_split_effect_cutoff_untracked_run_cleanup_and_auto_dispose() {
    let scope = Scope::new();
    let count = scope.atom(1i32);
    let side = scope.atom(100i32);
    let baseline_nodes = scope.live_node_count();

    let log: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
    let log_run = Rc::clone(&log);
    let scope_run = scope.clone();

    let sub = scope.split_effect(
        move |cx| cx.get(count) % 2, // parity: equality cutoff!
        move |val, prev| {
            // Reading `side` inside `run` must be untracked.
            let s = scope_run.get(side);
            log_run
                .borrow_mut()
                .push(format!("run:{val}:{prev:?}:side={s}"));
            let log_cl = Rc::clone(&log_run);
            let v = *val;
            Some(Box::new(move || {
                log_cl.borrow_mut().push(format!("cleanup:{v}"));
            }))
        },
    );

    assert_eq!(*log.borrow(), vec!["run:1:None:side=100"]);

    // Changing `side` must NOT re-trigger split_effect (run is untracked).
    scope.set(side, 200);
    assert_eq!(log.borrow().len(), 1);

    // Changing `count` from 1 -> 3 keeps parity == 1 -> equality cutoff!
    scope.set(count, 3);
    assert_eq!(log.borrow().len(), 1);

    // Changing `count` from 3 -> 4 flips parity 1 -> 0 -> cleanup(1), then run(0, Some(1)).
    scope.set(count, 4);
    assert_eq!(
        *log.borrow(),
        vec!["run:1:None:side=100", "cleanup:1", "run:0:Some(1):side=200"]
    );

    drop(sub);
    assert_eq!(
        *log.borrow(),
        vec![
            "run:1:None:side=100",
            "cleanup:1",
            "run:0:Some(1):side=200",
            "cleanup:0"
        ]
    );
    // Internal Computed and Effect must be fully disposed.
    assert_eq!(scope.live_node_count(), baseline_nodes);

    // SSR mode is a silent no-op.
    let ssr = Scope::ssr();
    let ssr_a = ssr.atom(1);
    let ran = Rc::new(Cell::new(false));
    let ran_cb = Rc::clone(&ran);
    let _ssr_sub = ssr.split_effect(
        move |cx| cx.get(ssr_a),
        move |_, _| {
            ran_cb.set(true);
            None
        },
    );
    assert!(!ran.get());
}

#[test]
fn scope_watch_immediate_and_lazy_with_cleanup() {
    let scope = Scope::new();
    let val = scope.atom(10i32);

    // Lazy (immediate: false)
    let lazy_log: Rc<RefCell<Vec<(Option<i32>, i32)>>> = Rc::new(RefCell::new(Vec::new()));
    let lazy_cb = Rc::clone(&lazy_log);
    let sub_lazy = scope.watch(
        val,
        move |prev, next| {
            lazy_cb.borrow_mut().push((prev.copied(), *next));
            None
        },
        WatchOptions::default(),
    );
    assert!(lazy_log.borrow().is_empty());

    // Immediate (immediate: true) with cleanup
    let imm_log: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
    let imm_cb = Rc::clone(&imm_log);
    let sub_imm = scope.watch(
        val,
        move |prev, next| {
            imm_cb.borrow_mut().push(format!("cb:{prev:?}->{next}"));
            let cl = Rc::clone(&imm_cb);
            let n = *next;
            Some(Box::new(move || {
                cl.borrow_mut().push(format!("cl:{n}"));
            }))
        },
        WatchOptions { immediate: true },
    );
    assert_eq!(*imm_log.borrow(), vec!["cb:None->10"]);

    scope.set(val, 20);
    assert_eq!(*lazy_log.borrow(), vec![(Some(10), 20)]);
    assert_eq!(
        *imm_log.borrow(),
        vec!["cb:None->10", "cl:10", "cb:Some(10)->20"]
    );

    drop(sub_lazy);
    drop(sub_imm);
    assert_eq!(
        *imm_log.borrow(),
        vec!["cb:None->10", "cl:10", "cb:Some(10)->20", "cl:20"]
    );
}

#[test]
fn scope_peek_does_not_track_dependencies() {
    let scope = Scope::new();
    let tracked = scope.atom(1i32);
    let peeked = scope.atom(10i32);
    let evals = Rc::new(Cell::new(0usize));
    let evals_c = Rc::clone(&evals);
    let scope_c = scope.clone();

    let comp = scope.computed(move |cx| {
        evals_c.set(evals_c.get() + 1);
        cx.get(tracked) + cx.peek(peeked) + scope_c.peek(peeked)
    });

    assert_eq!(scope.get(comp), 21);
    assert_eq!(evals.get(), 1);

    // Updating `peeked` must NOT dirty `comp`.
    scope.set(peeked, 100);
    assert_eq!(scope.get(comp), 21);
    assert_eq!(evals.get(), 1);

    // Updating `tracked` re-evaluates and observes the new `peeked` value.
    scope.set(tracked, 2);
    assert_eq!(scope.get(comp), 202);
    assert_eq!(evals.get(), 2);
}

#[test]
fn scope_subscribe_selected_and_dispose_id_and_batch_guard() {
    let scope = Scope::new();
    let user = scope.atom((String::from("Alice"), 30u32));
    let baseline = scope.live_node_count();

    let seen_ages: Rc<RefCell<Vec<u32>>> = Rc::new(RefCell::new(Vec::new()));
    let ages_cb = Rc::clone(&seen_ages);
    let sub = scope.subscribe_selected(user, |u| u.1, move |age| ages_cb.borrow_mut().push(*age));

    // Changing name only -> selector returns same age -> no notification!
    scope.set(user, (String::from("Bob"), 30));
    assert!(seen_ages.borrow().is_empty());

    // Changing age -> notifies!
    scope.set(user, (String::from("Bob"), 31));
    assert_eq!(*seen_ages.borrow(), vec![31]);

    // BatchGuard coalesces writes until dropped.
    {
        let _guard = scope.batch_guard();
        scope.set(user, (String::from("Bob"), 32));
        scope.set(user, (String::from("Bob"), 33));
        assert_eq!(*seen_ages.borrow(), vec![31]);
    }
    assert_eq!(*seen_ages.borrow(), vec![31, 33]);

    // Dropping subscription auto-disposes internal computed.
    drop(sub);
    assert_eq!(scope.live_node_count(), baseline);

    // Type-erased dispose_id
    let id = user.id();
    assert!(scope.dispose_id(id));
    assert!(!scope.dispose_id(id));
    assert_eq!(scope.live_node_count(), 0);
}

#[cfg(feature = "sync")]
#[test]
fn sync_scope_wave3_fb_primitives() {
    let scope = SyncScope::new();
    let a = scope.atom(1i32);
    let b = scope.atom(10i32);
    let baseline = scope.live_node_count();

    // SyncEvalContext::peek + SyncScope::peek
    let evals = Arc::new(AtomicUsize::new(0));
    let evals_c = Arc::clone(&evals);
    let sc_c = scope.clone();
    let comp = scope.computed(move |cx| {
        evals_c.fetch_add(1, Ordering::Relaxed);
        cx.get(a) + cx.peek(b) + sc_c.peek(b)
    });
    assert_eq!(scope.get(comp), 21);
    scope.set(b, 50);
    assert_eq!(scope.get(comp), 21);
    assert_eq!(evals.load(Ordering::Relaxed), 1);
    scope.set(a, 2);
    assert_eq!(scope.get(comp), 102);
    assert_eq!(evals.load(Ordering::Relaxed), 2);
    assert!(scope.dispose_id(comp.id()));
    assert!(!scope.dispose_id(comp.id()));
    assert_eq!(scope.live_node_count(), baseline);

    // SyncScope::split_effect
    let split_log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let sl = Arc::clone(&split_log);
    let sub = scope.split_effect(
        move |cx| cx.get(a) % 2,
        move |val, prev| {
            sl.lock().unwrap().push(format!("run:{val}:{prev:?}"));
            let sl2 = Arc::clone(&sl);
            let v = *val;
            Some(Box::new(move || {
                sl2.lock().unwrap().push(format!("cl:{v}"));
            }))
        },
    );
    assert_eq!(*split_log.lock().unwrap(), vec!["run:0:None"]);
    scope.set(a, 4); // still even -> cutoff
    assert_eq!(split_log.lock().unwrap().len(), 1);
    scope.set(a, 5); // odd -> runs cleanup + run
    assert_eq!(
        *split_log.lock().unwrap(),
        vec!["run:0:None", "cl:0", "run:1:Some(0)"]
    );
    drop(sub);
    assert_eq!(
        *split_log.lock().unwrap(),
        vec!["run:0:None", "cl:0", "run:1:Some(0)", "cl:1"]
    );
    assert_eq!(scope.live_node_count(), baseline);

    // SyncScope::watch + SyncBatchGuard
    let watch_log: Arc<Mutex<Vec<(Option<i32>, i32)>>> = Arc::new(Mutex::new(Vec::new()));
    let wl = Arc::clone(&watch_log);
    let wsub = scope.watch(
        a,
        move |prev, next| {
            wl.lock().unwrap().push((prev.copied(), *next));
            None
        },
        WatchOptions { immediate: true },
    );
    assert_eq!(*watch_log.lock().unwrap(), vec![(None, 5)]);
    {
        let _guard = scope.batch_guard();
        scope.set(a, 6);
        scope.set(a, 7);
        assert_eq!(watch_log.lock().unwrap().len(), 1);
    }
    assert_eq!(*watch_log.lock().unwrap(), vec![(None, 5), (Some(5), 7)]);
    drop(wsub);

    // SyncScope::subscribe_selected
    let pair = scope.atom((1i32, 2i32));
    let pair_base = scope.live_node_count();
    let sel_log: Arc<Mutex<Vec<i32>>> = Arc::new(Mutex::new(Vec::new()));
    let sl2 = Arc::clone(&sel_log);
    let ssub = scope.subscribe_selected(pair, |p| p.1, move |v| sl2.lock().unwrap().push(*v));
    scope.set(pair, (99, 2));
    assert!(sel_log.lock().unwrap().is_empty());
    scope.set(pair, (99, 3));
    assert_eq!(*sel_log.lock().unwrap(), vec![3]);
    drop(ssub);
    assert_eq!(scope.live_node_count(), pair_base);
}

// ============================================================================
// F-C: Arena-backed Owner tree, on_cleanup, effect, subscribe, Scope::dispose_scope
// ============================================================================

#[test]
fn owner_tree_cascades_bottom_up_lifo_and_disposes_subs_cleanups_nodes() {
    let scope = Scope::new();
    let src = scope.atom(1i32);
    let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));

    let mut root = scope.create_root();
    let root_atom = root.atom(10);
    {
        let o = Rc::clone(&order);
        root.on_cleanup(move || o.borrow_mut().push("root_cl_1"));
    }
    {
        let o = Rc::clone(&order);
        root.on_cleanup(move || o.borrow_mut().push("root_cl_2"));
    }
    let effect_hits = Rc::new(Cell::new(0usize));
    let eh = Rc::clone(&effect_hits);
    let o_eff = Rc::clone(&order);
    root.effect(move |cx| {
        let _ = cx.get(src);
        eh.set(eh.get() + 1);
        let o = Rc::clone(&o_eff);
        Some(Box::new(move || o.borrow_mut().push("root_eff_cl")))
    });

    let mut child1 = root.child_root();
    let c1_atom = child1.atom(20);
    {
        let o = Rc::clone(&order);
        child1.on_cleanup(move || o.borrow_mut().push("child1_cl"));
    }

    let mut child2 = root.child_root();
    let c2_atom = child2.atom(30);
    {
        let o = Rc::clone(&order);
        child2.on_cleanup(move || o.borrow_mut().push("child2_cl"));
    }

    let mut grandchild = child2.child_root();
    let gc_atom = grandchild.atom(40);
    {
        let o = Rc::clone(&order);
        grandchild.on_cleanup(move || o.borrow_mut().push("grandchild_cl"));
    }

    let sub_hits = Rc::new(Cell::new(0usize));
    let sh = Rc::clone(&sub_hits);
    grandchild.subscribe(src, move |_| sh.set(sh.get() + 1));

    scope.set(src, 2);
    assert_eq!(effect_hits.get(), 2);
    assert_eq!(sub_hits.get(), 1);
    // Clear the cleanup recorded from the effect re-run before testing disposal order.
    assert_eq!(*order.borrow(), vec!["root_eff_cl"]);
    order.borrow_mut().clear();

    // Disposing root cascades bottom-up LIFO:
    // child2 (grandchild -> child2) -> child1 -> root (root_eff_cl -> root_cl_2 -> root_cl_1)
    root.dispose();
    assert!(root.is_disposed());
    assert!(child1.is_disposed());
    assert!(child2.is_disposed());
    assert!(grandchild.is_disposed());

    assert_eq!(
        *order.borrow(),
        vec![
            "grandchild_cl",
            "child2_cl",
            "child1_cl",
            "root_eff_cl",
            "root_cl_2",
            "root_cl_1",
        ]
    );

    assert_eq!(scope.try_get(root_atom), Err(CoreError::Disposed));
    assert_eq!(scope.try_get(c1_atom), Err(CoreError::Disposed));
    assert_eq!(scope.try_get(c2_atom), Err(CoreError::Disposed));
    assert_eq!(scope.try_get(gc_atom), Err(CoreError::Disposed));

    // Subscriptions/effects are gone.
    scope.set(src, 3);
    assert_eq!(effect_hits.get(), 2);
    assert_eq!(sub_hits.get(), 1);
}

#[test]
fn scope_dispose_scope_cleans_up_everything() {
    let scope = Scope::new();
    let a = scope.atom(1i32);
    let cleaned = Rc::new(Cell::new(0usize));
    let c1 = Rc::clone(&cleaned);
    let mut root = scope.create_root();
    root.on_cleanup(move || c1.set(c1.get() + 1));

    let c2 = Rc::clone(&cleaned);
    let _hook = scope.on_watched(a, move || {
        let c = Rc::clone(&c2);
        Some(Box::new(move || c.set(c.get() + 10)))
    });
    let _sub = scope.subscribe(a, |_| {});

    assert!(!scope.is_disposed());
    scope.dispose_scope();
    assert!(scope.is_disposed());
    assert_eq!(cleaned.get(), 11);
    assert_eq!(scope.live_node_count(), 0);
    // Idempotent
    scope.dispose_scope();
    assert_eq!(cleaned.get(), 11);
}

#[cfg(feature = "sync")]
#[test]
fn sync_scope_owner_cascade_dispose_scope_and_drop_cleanup() {
    let cleaned = Arc::new(AtomicUsize::new(0));
    {
        let scope = SyncScope::new();
        let a = scope.atom(1i32);
        let c = Arc::clone(&cleaned);
        let _hook = scope.on_watched(a, move || {
            let c2 = Arc::clone(&c);
            Some(Box::new(move || {
                c2.fetch_add(1, Ordering::Relaxed);
            }))
        });
        // Detach subscription so `Drop for SyncScopeInner` must fire the watched cleanup!
        scope.subscribe(a, |_| {}).detach();
    }
    assert_eq!(cleaned.load(Ordering::Relaxed), 1);

    // SyncOwner cascade + SyncScope::dispose_scope
    let scope = SyncScope::new();
    let order = Arc::new(Mutex::new(Vec::new()));
    let mut root = scope.create_root();
    let mut child = root.child_root();
    {
        let o = Arc::clone(&order);
        root.on_cleanup(move || o.lock().unwrap().push("root"));
    }
    {
        let o = Arc::clone(&order);
        child.on_cleanup(move || o.lock().unwrap().push("child"));
    }
    assert!(!scope.is_disposed());
    scope.dispose_scope();
    assert!(scope.is_disposed());
    assert_eq!(*order.lock().unwrap(), vec!["child", "root"]);
    assert!(root.is_disposed());
    assert!(child.is_disposed());
}

// ============================================================================
// F-D: #[derive(ReactiveStore)], MapStore<K, V>, and projection
// ============================================================================

#[cfg(feature = "derive")]
#[derive(Debug, Clone, PartialEq, ReactiveStore)]
#[store(crate = zwire::core)]
struct Profile {
    name: String,
    age: u32,
    active: bool,
}

#[cfg(feature = "derive")]
#[test]
fn derive_reactive_store_per_field_granularity_snapshot_and_batched_patch() {
    let scope = Scope::new();
    let store = ProfileStore::new(
        &scope,
        Profile {
            name: String::from("Ada"),
            age: 36,
            active: true,
        },
    );

    assert_eq!(
        store.snapshot(&scope),
        Profile {
            name: String::from("Ada"),
            age: 36,
            active: true,
        }
    );

    let name_hits = Rc::new(Cell::new(0usize));
    let age_hits = Rc::new(Cell::new(0usize));
    let nh = Rc::clone(&name_hits);
    let ah = Rc::clone(&age_hits);
    let _s1 = scope.subscribe(store.name, move |_| nh.set(nh.get() + 1));
    let _s2 = scope.subscribe(store.age, move |_| ah.set(ah.get() + 1));

    // Mutating only `age` does not notify `name` subscribers.
    scope.set(store.age, 37);
    assert_eq!(name_hits.get(), 0);
    assert_eq!(age_hits.get(), 1);

    // Batched `patch` notifies combined computed only once.
    let summary_hits = Rc::new(Cell::new(0usize));
    let sh = Rc::clone(&summary_hits);
    let summary = scope.computed(move |cx| format!("{}:{}", cx.get(store.name), cx.get(store.age)));
    let _s3 = scope.subscribe(summary, move |_| sh.set(sh.get() + 1));

    store.patch(
        &scope,
        Profile {
            name: String::from("Grace"),
            age: 85,
            active: false,
        },
    );
    assert_eq!(summary_hits.get(), 1);
    assert_eq!(scope.get(summary), "Grace:85");
    assert_eq!(
        store.snapshot(&scope),
        Profile {
            name: String::from("Grace"),
            age: 85,
            active: false,
        }
    );
}

#[test]
fn map_store_lazy_fields_unwatched_pruning_and_crud() {
    let scope = Scope::new();
    let store = MapStore::from_entries(&scope, [("a", 1i32), ("b", 2i32)]);
    let baseline_nodes = scope.live_node_count();

    assert_eq!(store.len(), 2);
    assert!(!store.is_empty());
    assert_eq!(store.get(&"a"), Some(1));
    assert_eq!(store.get(&"z"), None);
    assert_eq!(store.live_field_count(), 0);

    // Subscribing to field("a") allocates 1 atom; updating "b" does not trigger "a".
    let a_field = store.field("a");
    assert_eq!(store.live_field_count(), 1);

    let seen: Rc<RefCell<Vec<Option<i32>>>> = Rc::new(RefCell::new(Vec::new()));
    let s = Rc::clone(&seen);
    let sub = scope.subscribe(a_field, move |v| s.borrow_mut().push(*v));

    store.set_key("b", 20);
    assert!(seen.borrow().is_empty());

    store.set_key("a", 10);
    assert_eq!(*seen.borrow(), vec![Some(10)]);

    assert_eq!(store.delete_key(&"a"), Some(10));
    assert_eq!(*seen.borrow(), vec![Some(10), None]);
    assert_eq!(store.len(), 1);
    assert_eq!(scope.get(store.len_signal()), 1);

    // Dropping the last subscriber triggers on_unwatched pruning and disposes the field atom!
    drop(sub);
    assert_eq!(store.live_field_count(), 0);
    assert_eq!(scope.live_node_count(), baseline_nodes);

    let snap = store.snapshot();
    assert_eq!(snap.len(), 1);
    assert_eq!(snap.get(&"b"), Some(&20));
}

#[test]
fn projection_mutable_draft_notifies_only_when_returning_true() {
    #[derive(Clone, Debug)]
    struct NonEqBucket {
        sum: i32,
        updates: usize,
    }

    let scope = Scope::new();
    let input = scope.atom(5i32);

    let bucket = projection(
        &scope,
        NonEqBucket { sum: 0, updates: 0 },
        move |cx, draft| {
            let v = cx.get(input);
            if v > 0 {
                draft.sum += v;
                draft.updates += 1;
                true
            } else {
                // Ignore non-positive writes -> return false -> suppress downstream!
                false
            }
        },
    );

    let hits = Rc::new(Cell::new(0usize));
    let h = Rc::clone(&hits);
    let _sub = scope.subscribe(bucket, move |_| h.set(h.get() + 1));

    assert_eq!(scope.get(bucket).sum, 5);
    assert_eq!(hits.get(), 0);

    // Positive update -> returns true -> downstream notified
    scope.set(input, 3);
    assert_eq!(scope.get(bucket).sum, 8);
    assert_eq!(hits.get(), 1);

    // Negative update -> returns false -> early cutoff, downstream NOT notified!
    scope.set(input, -10);
    assert_eq!(scope.get(bucket).sum, 8);
    assert_eq!(hits.get(), 1);

    // Another positive update -> notified again
    scope.set(input, 2);
    assert_eq!(scope.get(bucket).sum, 10);
    assert_eq!(hits.get(), 2);
}

// ============================================================================
// F-E: Executor-agnostic #![no_std] Resource<T, E, K>
// ============================================================================

#[test]
fn resource_drive_lifecycle_cancellation_and_refetch() {
    let scope = Scope::new();
    let user_id = scope.atom(1u32);
    let res: Resource<String, &'static str, u32> = Resource::new(&scope, user_id);

    assert!(res.is_pending());
    assert_eq!(res.latest(), None);

    let handles: Rc<RefCell<Vec<(u32, ManualHandle<Result<String, &'static str>>)>>> =
        Rc::new(RefCell::new(Vec::new()));
    let h_loader = Rc::clone(&handles);

    let mut driver = Box::pin(res.drive(move |id| {
        let (fut, handle) = manual_future();
        h_loader.borrow_mut().push((id, handle));
        fut
    }));

    let woke = Arc::new(WakeCounter::default());
    let waker = Waker::from(Arc::clone(&woke));
    let mut cx = Context::from_waker(&waker);

    // Initial poll starts request for user_id = 1
    assert!(driver.as_mut().poll(&mut cx).is_pending());
    assert_eq!(handles.borrow().len(), 1);
    assert_eq!(handles.borrow()[0].0, 1);
    assert_eq!(scope.get(res.state()), ResourceState::Pending);

    // Changing source while request 1 is in-flight cancels (drops) request 1 and starts request 2!
    scope.set(user_id, 2);
    assert!(driver.as_mut().poll(&mut cx).is_pending());
    assert!(handles.borrow()[0].1.is_dropped());
    assert_eq!(handles.borrow().len(), 2);
    assert_eq!(handles.borrow()[1].0, 2);

    // Resolve request 2 -> Ready("user-2")
    handles.borrow()[1].1.resolve(Ok(String::from("user-2")));
    assert!(driver.as_mut().poll(&mut cx).is_pending());
    assert_eq!(
        scope.get(res.state()),
        ResourceState::Ready(String::from("user-2"))
    );
    assert_eq!(res.latest(), Some(String::from("user-2")));
    assert!(!res.is_pending());

    // Refetch transitions Ready -> Refreshing(previous)
    res.refetch();
    assert!(driver.as_mut().poll(&mut cx).is_pending());
    assert_eq!(handles.borrow().len(), 3);
    assert_eq!(
        scope.get(res.state()),
        ResourceState::Refreshing(String::from("user-2"))
    );
    assert!(res.is_pending());

    // Error preserves previous value
    handles.borrow()[2].1.resolve(Err("timeout"));
    assert!(driver.as_mut().poll(&mut cx).is_pending());
    assert_eq!(
        scope.get(res.state()),
        ResourceState::Error {
            error: "timeout",
            previous: Some(String::from("user-2")),
        }
    );
    assert_eq!(res.latest(), Some(String::from("user-2")));

    // Dispose ends the drive loop cleanly
    res.dispose();
    assert_eq!(scope.get(res.state()), ResourceState::Disposed);
    assert!(driver.as_mut().poll(&mut cx).is_ready());
}

#[test]
fn resource_ignores_stale_out_of_order_completions_and_mutate_supersedes() {
    let scope = Scope::new();
    let res: Resource<i32, &'static str> = Resource::stateless(&scope);

    let (fut1, h1) = manual_future::<Result<i32, &'static str>>();
    let (fut2, h2) = manual_future::<Result<i32, &'static str>>();

    let mut load1 = Box::pin(res.load(move |()| fut1));
    let mut load2 = Box::pin(res.load(move |()| fut2));
    let mut cx = Context::from_waker(Waker::noop());

    // Start load1 (gen 1), then load2 (gen 2)
    assert!(load1.as_mut().poll(&mut cx).is_pending());
    assert!(load2.as_mut().poll(&mut cx).is_pending());
    assert_eq!(res.generation(), 2);

    // load2 completes FIRST -> Ready(200)
    h2.resolve(Ok(200));
    assert!(load2.as_mut().poll(&mut cx).is_ready());
    assert_eq!(scope.get(res.state()), ResourceState::Ready(200));

    // Stale load1 completes LATER -> MUST be ignored!
    h1.resolve(Ok(100));
    assert!(load1.as_mut().poll(&mut cx).is_ready());
    assert_eq!(scope.get(res.state()), ResourceState::Ready(200));

    // mutate() supersedes an in-flight load
    let (fut3, h3) = manual_future::<Result<i32, &'static str>>();
    let mut load3 = Box::pin(res.load(move |()| fut3));
    assert!(load3.as_mut().poll(&mut cx).is_pending());
    res.mutate(999);
    assert_eq!(scope.get(res.state()), ResourceState::Ready(999));

    h3.resolve(Ok(300));
    assert!(load3.as_mut().poll(&mut cx).is_ready());
    // Still 999 because mutate() incremented generation!
    assert_eq!(scope.get(res.state()), ResourceState::Ready(999));
}

#[test]
fn resource_poll_fn_sanity() {
    // Ensure our test harness runs smoothly with core::future::poll_fn as well
    let mut done = false;
    let mut f = Box::pin(poll_fn(|_| {
        if done {
            Poll::Ready(42)
        } else {
            done = true;
            Poll::Pending
        }
    }));
    let mut cx = Context::from_waker(Waker::noop());
    assert!(f.as_mut().poll(&mut cx).is_pending());
    assert_eq!(f.as_mut().poll(&mut cx), Poll::Ready(42));
}