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
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::{Cell, RefCell};

use zwire_collections::{AcceptAll, ItemFilter, KeyedCollection, TopKViewId};
use zwire_core::internal::{
    alloc_token, batch_depth, create_external_signal, emit_external, is_node_alive,
    propagate_external, remove_flush_hook, schedule_flush_hook, update_external_silent,
};
use zwire_core::{CleanupFn, Computed, NodeId, Scope};

struct WatchedTopK {
    view_id: TopKViewId,
    signal_id: NodeId,
    watched: Rc<Cell<bool>>,
    dirty_notified: Rc<Cell<bool>>,
}

/// High-throughput reactive collection backed directly by [`zwire_collections::KeyedCollection`]
/// (`BTreeSet<(S, K, u32)>` ordered index with cached `(S, K)` Top-K boundary pruning).
///
/// Designed for pure key/sort-key/filter extractors (callbacks that do not re-enter the
/// collection). Eliminates per-row `Rc<T>` boxing, gap-rank `u128` indirection, and repeated
/// `RefCell` bounces while preserving `O(1)` Top-K boundary pruning, single-pass `view_mapped`
/// materialization, batched flush coalescing, and releasing every `RefCell` borrow before
/// calling into [`Scope`].
pub struct PureReactiveCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
    Flt: ItemFilter<T> + 'static,
{
    scope: Scope,
    inner: Rc<RefCell<KeyedCollection<T, K, S, IdFn, SkFn, Flt>>>,
    views: Rc<RefCell<Vec<WatchedTopK>>>,
    cached_top_k: RefCell<BTreeMap<usize, Computed<Vec<T>>>>,
    flush_token: u64,
    flush_scheduled: Rc<Cell<bool>>,
}

impl<T, K, S, IdFn, SkFn, Flt> core::fmt::Debug for PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
    Flt: ItemFilter<T> + 'static,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut s = f.debug_struct("PureReactiveCollection");
        if let Ok(inner) = self.inner.try_borrow() {
            s.field("len", &inner.len())
                .field("indexed_len", &inner.indexed_len())
                .field("version", &inner.version());
        } else {
            s.field("state", &"<borrowed>");
        }
        s.field("flush_scheduled", &self.flush_scheduled.get())
            .finish_non_exhaustive()
    }
}

impl<T, K, S, IdFn, SkFn> PureReactiveCollection<T, K, S, IdFn, SkFn, AcceptAll>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
{
    /// Creates an unfiltered pure sort-key reactive collection bound to `scope`.
    pub fn new(scope: &Scope, get_id: IdFn, sort_key: SkFn) -> Self {
        Self::from_parts(scope, get_id, sort_key, AcceptAll)
    }
}

impl<T, K, S, IdFn, SkFn, Flt> PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
    Flt: Fn(&T) -> bool + 'static,
{
    /// Creates a filtered pure sort-key reactive collection bound to `scope`.
    pub fn with_filter(scope: &Scope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
        Self::from_parts(scope, get_id, sort_key, filter)
    }
}

impl<T, K, S, IdFn, SkFn, Flt> PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
    Flt: ItemFilter<T> + 'static,
{
    /// Creates a pure sort-key reactive collection with any [`ItemFilter<T>`] implementation.
    pub fn from_parts(scope: &Scope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
        let flush_token = alloc_token(scope);
        Self {
            scope: scope.clone(),
            inner: Rc::new(RefCell::new(KeyedCollection::from_parts(
                get_id, sort_key, filter,
            ))),
            views: Rc::new(RefCell::new(Vec::new())),
            cached_top_k: RefCell::new(BTreeMap::new()),
            flush_token,
            flush_scheduled: Rc::new(Cell::new(false)),
        }
    }

    /// Total number of stored items (including items excluded by the filter).
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.borrow().len()
    }

    /// Returns `true` if the collection stores no items.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.borrow().is_empty()
    }

    /// Number of items currently passing the filter and present in the sorted index.
    #[inline]
    pub fn indexed_len(&self) -> usize {
        self.inner.borrow().indexed_len()
    }

    /// Clones the stored item for `id`, if present.
    #[inline]
    pub fn get(&self, id: &K) -> Option<T> {
        self.inner.borrow().get(id).cloned()
    }

    /// Returns `true` if `id` exists in the collection.
    #[inline]
    pub fn contains_key(&self, id: &K) -> bool {
        self.inner.borrow().contains_key(id)
    }

    /// Returns a cloned snapshot of the current top `k` indexed items.
    #[inline]
    pub fn get_top_k(&self, k: usize) -> Vec<T> {
        self.inner.borrow().top_k(k)
    }

    /// Inserts or replaces an item and incrementally updates any affected watched Top-K signals.
    pub fn upsert(&self, item: T) {
        self.inner.borrow_mut().upsert(item);
        self.notify_top_k();
    }

    /// Inserts or replaces a batch of items and updates any affected watched Top-K signals.
    pub fn upsert_many<I>(&self, items: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.inner.borrow_mut().upsert_many(items);
        self.notify_top_k();
    }

    /// Deletes an item by key, returning the owned value if present.
    pub fn delete(&self, id: &K) -> Option<T> {
        let removed = self.inner.borrow_mut().delete(id)?;
        self.notify_top_k();
        Some(removed)
    }

    /// Removes all items from the collection.
    pub fn clear(&self) {
        let changed = {
            let mut col = self.inner.borrow_mut();
            if col.is_empty() {
                false
            } else {
                col.clear();
                true
            }
        };
        if changed {
            self.notify_top_k();
        }
    }

    /// Creates (or returns a cached live) first-class reactive [`Computed<Vec<T>>`] tracking the
    /// exact top `k` items.
    ///
    /// Mutations strictly outside the K-th boundary skip materialization and propagation in `O(1)`.
    pub fn top_k_signal(&self, k: usize) -> Computed<Vec<T>> {
        self.prune_disposed_views();
        if let Some(&sig) = self.cached_top_k.borrow().get(&k)
            && is_node_alive(&self.scope, sig.id())
        {
            return sig;
        }
        let (view_id, initial) = {
            let mut col = self.inner.borrow_mut();
            let view_id = col.watch_top_k(k);
            let initial = col.view_mapped(view_id, T::clone);
            (view_id, initial)
        };
        let sig = self.build_top_k_signal(view_id, initial);
        self.cached_top_k.borrow_mut().insert(k, sig);
        sig
    }

    /// Unregisters a previously created Top-K signal view and disposes its reactive node in the
    /// owning [`Scope`].
    pub fn dispose_top_k_signal(&self, sig: Computed<Vec<T>>) -> bool {
        let target = sig.id();
        self.cached_top_k
            .borrow_mut()
            .retain(|_, cached| cached.id() != target);
        let removed_view = {
            let mut views = self.views.borrow_mut();
            views
                .iter()
                .position(|v| v.signal_id == target)
                .map(|idx| views.swap_remove(idx).view_id)
        };
        if let Some(view_id) = removed_view {
            self.inner.borrow_mut().unwatch_top_k(view_id);
        }
        let disposed = self.scope.dispose(sig);
        removed_view.is_some() || disposed
    }

    fn prune_disposed_views(&self) {
        let dead: Vec<TopKViewId> = {
            let mut views = self.views.borrow_mut();
            views
                .extract_if(.., |v| !is_node_alive(&self.scope, v.signal_id))
                .map(|v| v.view_id)
                .collect()
        };
        if !dead.is_empty() {
            let mut col = self.inner.borrow_mut();
            for vid in dead {
                col.unwatch_top_k(vid);
            }
            self.cached_top_k
                .borrow_mut()
                .retain(|_, sig| is_node_alive(&self.scope, sig.id()));
        }
    }

    fn build_top_k_signal(&self, view_id: TopKViewId, initial: Vec<T>) -> Computed<Vec<T>> {
        let watched = Rc::new(Cell::new(false));
        let dirty_notified = Rc::new(Cell::new(false));
        let signal_id_cell: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));

        let poll_inner = Rc::clone(&self.inner);
        let poll_id = Rc::clone(&signal_id_cell);
        let poll_dirty = Rc::clone(&dirty_notified);
        let poll = Rc::new(move |sc: &Scope| {
            let Some(sid) = poll_id.get() else {
                return;
            };
            let maybe_next = {
                let mut col = poll_inner.borrow_mut();
                col.sync_view(view_id)
                    .then(|| col.view_mapped(view_id, T::clone))
            };
            poll_dirty.set(false);
            if let Some(next) = maybe_next {
                update_external_silent(sc, sid, next);
            }
        });

        let watch_inner = Rc::clone(&self.inner);
        let watch_flag = Rc::clone(&watched);
        let watch_dirty = Rc::clone(&dirty_notified);
        let watch_id = Rc::clone(&signal_id_cell);
        let weak_sc = self.scope.downgrade();
        let on_watched = Rc::new(move || -> Option<CleanupFn> {
            watch_flag.set(true);
            if let (Some(sid), Some(sc_watch)) = (watch_id.get(), weak_sc.upgrade()) {
                let maybe_next = {
                    let mut col = watch_inner.borrow_mut();
                    col.sync_view(view_id)
                        .then(|| col.view_mapped(view_id, T::clone))
                };
                watch_dirty.set(false);
                if let Some(next) = maybe_next {
                    update_external_silent(&sc_watch, sid, next);
                }
            }
            let unw = Rc::clone(&watch_flag);
            let unw_dirty = Rc::clone(&watch_dirty);
            Some(Box::new(move || {
                unw.set(false);
                unw_dirty.set(false);
            }))
        });

        let eq: Rc<dyn Fn(&Vec<T>, &Vec<T>) -> bool> = Rc::new(|a, b| a == b);
        let sig =
            create_external_signal(&self.scope, initial, Some(eq), poll, Some(on_watched), None);
        signal_id_cell.set(Some(sig.id()));

        self.views.borrow_mut().push(WatchedTopK {
            view_id,
            signal_id: sig.id(),
            watched,
            dirty_notified,
        });

        sig
    }

    fn notify_top_k(&self) {
        let mut first: Option<(TopKViewId, NodeId)> = None;
        let mut rest: Vec<(TopKViewId, NodeId)> = Vec::new();
        {
            let views = self.views.borrow();
            if views.is_empty() {
                return;
            }
            let col = self.inner.borrow();
            for v in views.iter() {
                if v.watched.get() && col.is_view_dirty(v.view_id) {
                    let pair = (v.view_id, v.signal_id);
                    if first.is_none() {
                        first = Some(pair);
                    } else {
                        rest.push(pair);
                    }
                }
            }
        }

        let Some((first_vid, first_sid)) = first else {
            return;
        };

        if batch_depth(&self.scope) == 0 {
            if rest.is_empty() {
                let maybe_next = {
                    let mut col = self.inner.borrow_mut();
                    col.sync_view(first_vid)
                        .then(|| col.view_mapped(first_vid, T::clone))
                };
                if let Some(next) = maybe_next {
                    emit_external(&self.scope, first_sid, next);
                }
                return;
            }

            let mut updates = Vec::with_capacity(1 + rest.len());
            {
                let mut col = self.inner.borrow_mut();
                if col.sync_view(first_vid) {
                    updates.push((first_sid, col.view_mapped(first_vid, T::clone)));
                }
                for (vid, sid) in rest {
                    if col.sync_view(vid) {
                        updates.push((sid, col.view_mapped(vid, T::clone)));
                    }
                }
            }
            if updates.len() == 1 {
                let (sid, next) = updates.into_iter().next().expect("len == 1");
                emit_external(&self.scope, sid, next);
            } else if !updates.is_empty() {
                self.scope.batch(|| {
                    for (sid, next) in updates {
                        emit_external(&self.scope, sid, next);
                    }
                });
            }
            return;
        }

        // Inside an active batch: mark downstream pending once and coalesce materialization to
        // a single flush hook at batch end.
        let mut to_propagate: Vec<NodeId> = Vec::new();
        {
            let col = self.inner.borrow();
            let views = self.views.borrow();
            for v in views.iter() {
                if v.watched.get() && !v.dirty_notified.get() && col.is_view_dirty(v.view_id) {
                    v.dirty_notified.set(true);
                    to_propagate.push(v.signal_id);
                }
            }
        }
        for sid in to_propagate {
            propagate_external(&self.scope, sid);
        }

        if !self.flush_scheduled.get() {
            self.flush_scheduled.set(true);
            let inner = Rc::clone(&self.inner);
            let views = Rc::clone(&self.views);
            let scheduled = Rc::clone(&self.flush_scheduled);
            let weak_sc = self.scope.downgrade();
            schedule_flush_hook(
                &self.scope,
                self.flush_token,
                Rc::new(move || {
                    scheduled.set(false);
                    let Some(sc) = weak_sc.upgrade() else {
                        return;
                    };
                    let watched: Vec<_> = {
                        let views = views.borrow();
                        views
                            .iter()
                            .filter_map(|v| {
                                v.dirty_notified.set(false);
                                v.watched.get().then_some((v.signal_id, v.view_id))
                            })
                            .collect()
                    };
                    let mut updates = Vec::new();
                    {
                        let mut col = inner.borrow_mut();
                        for (sid, vid) in watched {
                            if col.sync_view(vid) {
                                updates.push((sid, col.view_mapped(vid, T::clone)));
                            }
                        }
                    }
                    for (sid, next) in updates {
                        emit_external(&sc, sid, next);
                    }
                }),
            );
        }
    }
}

impl<T, K, S, IdFn, SkFn, Flt> Drop for PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
    T: Clone + PartialEq + 'static,
    K: Ord + Clone + 'static,
    S: Ord + Copy + 'static,
    IdFn: Fn(&T) -> K + 'static,
    SkFn: Fn(&T) -> S + 'static,
    Flt: ItemFilter<T> + 'static,
{
    fn drop(&mut self) {
        remove_flush_hook(&self.scope, self.flush_token);
    }
}

#[cfg(test)]
mod tests {
    use super::PureReactiveCollection;
    use crate::ReactiveCollection;
    use alloc::rc::Rc;
    use alloc::vec::Vec;
    use core::cell::Cell;
    use core::cmp::Reverse;
    use zwire_core::Scope;

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Row {
        id: u32,
        score: i32,
        active: bool,
    }

    #[test]
    fn pure_reactive_collection_matches_reactive_collection_top_50_over_1000_random_ops() {
        let scope = Scope::new();
        let rc = ReactiveCollection::with_filter(
            &scope,
            |r: &Row| r.id,
            |a, b| b.score.cmp(&a.score),
            |r| r.active && r.score >= 700,
        );
        let pure = PureReactiveCollection::with_filter(
            &scope,
            |r: &Row| r.id,
            |r: &Row| Reverse(r.score),
            |r| r.active && r.score >= 700,
        );

        let mut seed = 0xDEAD_BEEFu32;
        let mut next_u32 = || {
            seed ^= seed << 13;
            seed ^= seed >> 17;
            seed ^= seed << 5;
            seed
        };

        let initial_rows: Vec<Row> = (0..300u32)
            .map(|id| {
                let r = next_u32();
                Row {
                    id,
                    score: i32::try_from(r % 1_000).unwrap_or(0),
                    active: (r & 1) == 0,
                }
            })
            .collect();
        rc.upsert_many(initial_rows.clone());
        pure.upsert_many(initial_rows);

        let rc_top50 = rc.top_k_signal(50);
        let pure_top50 = pure.top_k_signal(50);

        let rc_notifs = Rc::new(Cell::new(0usize));
        let pure_notifs = Rc::new(Cell::new(0usize));
        let rc_n = Rc::clone(&rc_notifs);
        let pure_n = Rc::clone(&pure_notifs);
        let _sub_rc = scope.subscribe(rc_top50, move |_| rc_n.set(rc_n.get() + 1));
        let _sub_pure = scope.subscribe(pure_top50, move |_| pure_n.set(pure_n.get() + 1));

        assert_eq!(scope.get(rc_top50), scope.get(pure_top50));
        assert_eq!(rc.len(), pure.len());

        for step in 0..1_000u32 {
            let op = next_u32() % 5;
            let id = next_u32() % 400;
            if op == 0 {
                let removed_rc = rc.delete(&id);
                let removed_pure = pure.delete(&id);
                assert_eq!(removed_rc, removed_pure, "delete mismatch at step {step}");
            } else {
                let score = i32::try_from(next_u32() % 1_000).unwrap_or(0);
                let active = (next_u32() & 1) == 0;
                let row = Row { id, score, active };
                rc.upsert(row.clone());
                pure.upsert(row);
            }

            assert_eq!(rc.len(), pure.len(), "len mismatch at step {step}");
            assert_eq!(
                rc.get(&id),
                pure.get(&id),
                "get mismatch for id {id} at step {step}"
            );
            assert_eq!(
                scope.get(rc_top50),
                scope.get(pure_top50),
                "top_k(50) signal mismatch at step {step}"
            );
        }

        // Both must fire the exact same number of subscriber notifications (O(1) boundary pruning
        // parity).
        assert_eq!(rc_notifs.get(), pure_notifs.get());
        assert!(pure_notifs.get() > 0);
        assert!(pure_notifs.get() < 1_000);
    }

    #[test]
    fn pure_reactive_collection_batching_and_dispose() {
        let scope = Scope::new();
        let pure = PureReactiveCollection::new(&scope, |r: &Row| r.id, |r: &Row| Reverse(r.score));
        let top2 = pure.top_k_signal(2);
        let hits = Rc::new(Cell::new(0usize));
        let h = Rc::clone(&hits);
        let _sub = scope.subscribe(top2, move |_| h.set(h.get() + 1));

        scope.batch(|| {
            pure.upsert(Row {
                id: 1,
                score: 10,
                active: true,
            });
            pure.upsert(Row {
                id: 2,
                score: 50,
                active: true,
            });
            pure.upsert(Row {
                id: 3,
                score: 30,
                active: true,
            });
        });

        assert_eq!(hits.get(), 1);
        assert_eq!(
            scope
                .get(top2)
                .into_iter()
                .map(|r| r.id)
                .collect::<Vec<_>>(),
            alloc::vec![2, 3]
        );
        assert!(pure.dispose_top_k_signal(top2));
    }
}