zwire 0.1.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
//! Cross-crate integration tests verifying composition of `zwire-core`, `zwire-tx`,
//! `zwire-collections`, and `zwire-protocol` through the 5 zero-cost extension slots.

use core::cell::{Cell, RefCell};
use std::rc::Rc;

use zwire::prelude::*;

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

#[test]
fn reactive_collection_batch_coalesces_materialization_and_works_with_stm_draft() {
    let scope = Scope::new();
    let col = ReactiveCollection::new(&scope, |e: &Entry| e.id, |a, b| b.score.cmp(&a.score));
    let top3 = col.top_k_signal(3);
    let leader_id = scope.computed(move |cx| cx.with(top3, |rows| rows.first().map(|e| e.id)));

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

    // Batch 100 inserts -> flush hook coalesces into exactly 1 subscriber notification!
    scope.batch(|| {
        for i in 1..=100u32 {
            col.upsert(Entry {
                id: i,
                score: i32::try_from(i).unwrap() * 10,
            });
        }
    });
    assert_eq!(scope.get(leader_id), Some(100));
    assert_eq!(notifications.get(), 1);

    // Off-top update is O(1) pruned -> 0 notifications
    col.upsert(Entry { id: 1, score: 15 });
    assert_eq!(notifications.get(), 1);

    // STM Draft reads reactive top3 and detects conflict if top3 changes before commit
    let target = scope.atom(0u32);
    let mut draft = Draft::new(&scope);
    let best = draft.get(top3).unwrap()[0].id;
    assert_eq!(best, 100);
    draft.set(target, best).unwrap();

    // New leader arrives -> invalidates top3 -> STM commit_verified rejects!
    col.upsert(Entry {
        id: 999,
        score: 99_999,
    });
    assert_eq!(
        draft.commit_verified(),
        Err(DraftError::StmConflict { node: top3.id() })
    );
    assert_eq!(scope.get(target), 0);
}

#[test]
fn end_to_end_hydrate_optimistic_settle_and_inspector() {
    let scope = Scope::new();
    let writes = Rc::new(RefCell::new(Vec::<String>::new()));
    let w_c = Rc::clone(&writes);
    let _insp = attach_inspector(
        &scope,
        InspectorHook {
            on_write: Some(Rc::new(move |ev| {
                if let Some(k) = &ev.key {
                    w_c.borrow_mut().push(k.clone());
                }
            })),
            ..InspectorHook::default()
        },
    );

    hydrate_json(&scope, r#"{"credits":500}"#).unwrap();
    let credits = hydratable(&scope, "credits", 0i64);
    assert_eq!(scope.get(credits), 500);

    let mut guard = OptimisticGuard::new(&scope);
    guard.update(credits, |c| c - 100);
    assert_eq!(scope.get(credits), 400);

    // Settling atomically forwards committed base write to inspector
    guard.settle_with(|| scope.set(credits, 400));
    assert_eq!(scope.get(credits), 400);
    assert_eq!(dehydrate_json(&scope), r#"{"credits":400}"#);
    assert_eq!(*writes.borrow(), vec![String::from("credits")]);
}

#[test]
fn scope_drops_without_rc_reference_cycles_across_all_layers() {
    struct DropCounter(Rc<Cell<usize>>);
    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.0.set(self.0.get() + 1);
        }
    }

    struct DummySource(Rc<Cell<usize>>);
    impl ExternalSource<i32> for DummySource {
        fn get_snapshot(&self) -> i32 {
            7
        }
        fn subscribe(&self, _on_update: Box<dyn Fn(i32)>) -> zwire::core::CleanupFn {
            Box::new(|| {})
        }
    }
    impl Drop for DummySource {
        fn drop(&mut self) {
            self.0.set(self.0.get() + 1);
        }
    }

    let drops = Rc::new(Cell::new(0usize));
    let weak = {
        let scope = Scope::new();
        let w = scope.downgrade();

        let _atom = scope.atom_with(DropCounter(Rc::clone(&drops)), AtomOptions::new());
        let a = hydratable(&scope, "n", 1i64);
        let d_comp = DropCounter(Rc::clone(&drops));
        let comp = scope.computed(move |cx| {
            let _keep = &d_comp;
            cx.get(a) * 2
        });
        scope.subscribe(comp, |_| {}).detach();
        scope
            .effect(move |cx| {
                let _ = cx.get(comp);
                None
            })
            .detach();

        attach_inspector(
            &scope,
            InspectorHook {
                on_write: Some(Rc::new(|_| {})),
                ..InspectorHook::default()
            },
        )
        .detach();

        let ext = from_external_source(&scope, DummySource(Rc::clone(&drops)));
        scope.subscribe(ext, |_| {}).detach();

        let col = ReactiveCollection::new(&scope, |e: &Entry| e.id, |x, y| y.score.cmp(&x.score));
        let top2 = col.top_k_signal(2);
        scope.subscribe(top2, |_| {}).detach();
        col.upsert(Entry { id: 1, score: 10 });

        assert!(w.upgrade().is_some());
        w
    };

    assert!(
        weak.upgrade().is_none(),
        "Scope leaked via an internal Rc reference cycle"
    );
    assert_eq!(
        drops.get(),
        3,
        "atom value, computed closure, and ExternalSource must all drop with Scope"
    );
}

#[test]
fn collection_edits_can_read_reenter_and_migrate_keys() {
    let scope = Scope::new();
    let col = ReactiveCollection::new(&scope, |item: &(i32, i32)| item.0, Ord::cmp);
    col.upsert((1, 1));
    assert!(col.update(&1, |current| {
        assert_eq!(col.get(&1), Some(*current));
        col.upsert((3, 3));
        (2, 2)
    }));
    assert!(!col.contains_key(&1));
    assert!(!col.mutate(&2, |item| {
        assert!(col.contains_key(&2));
        col.delete(&2);
        col.upsert((2, 4));
        item.1 = 9;
    }));
    assert_eq!(col.get_top_k(2), [(2, 4), (3, 3)]);
}

#[test]
fn reactive_collection_disposes_and_prunes_top_k_signals() {
    let scope = Scope::new();
    let col = ReactiveCollection::new(&scope, |e: &Entry| e.id, |a, b| b.score.cmp(&a.score));
    col.upsert(Entry { id: 1, score: 10 });

    let top1 = col.top_k_signal(1);
    let top2 = col.top_k_signal(2);
    assert_eq!(scope.get(top1).len(), 1);

    assert!(col.dispose_top_k_signal(top1));
    assert!(!col.dispose_top_k_signal(top1));
    assert!(scope.try_get(top1).is_err());

    // Disposing top2 directly via Scope::dispose must also prune cleanly on next collection write
    assert!(scope.dispose(top2));
    col.upsert(Entry { id: 2, score: 20 });
    assert!(scope.try_get(top2).is_err());
}

#[test]
fn reactive_collection_mid_batch_read_sees_subsequent_same_batch_writes() {
    let scope = Scope::new();
    let col = ReactiveCollection::new(&scope, |e: &Entry| e.id, |a, b| b.score.cmp(&a.score));
    let top2 = col.top_k_signal(2);

    let seen = Rc::new(RefCell::new(Vec::<Vec<u32>>::new()));
    let seen_c = Rc::clone(&seen);
    let _sub = scope.subscribe(top2, move |rows| {
        seen_c
            .borrow_mut()
            .push(rows.iter().map(|e| e.id).collect());
    });

    scope.batch(|| {
        col.upsert(Entry { id: 1, score: 10 });
        assert_eq!(
            scope
                .get(top2)
                .into_iter()
                .map(|e| e.id)
                .collect::<Vec<_>>(),
            vec![1]
        );
        col.upsert(Entry { id: 2, score: 20 });
        assert_eq!(
            scope
                .get(top2)
                .into_iter()
                .map(|e| e.id)
                .collect::<Vec<_>>(),
            vec![2, 1]
        );
    });

    assert_eq!(*seen.borrow(), vec![vec![2, 1]]);
}

#[test]
fn reactive_collection_caches_top_k_signal_and_prunes_disposed_views() {
    let scope = Scope::new();
    let col = ReactiveCollection::new(&scope, |e: &Entry| e.id, |a, b| b.score.cmp(&a.score));
    col.upsert(Entry { id: 1, score: 10 });

    let s1 = col.top_k_signal(3);
    let s2 = col.top_k_signal(3);
    assert_eq!(s1.id(), s2.id(), "top_k_signal(k) should cache live signal");
    assert_eq!(scope.get(s1).len(), 1);

    assert!(scope.dispose(s1));
    col.upsert(Entry { id: 2, score: 20 });

    let s3 = col.top_k_signal(3);
    assert_ne!(
        s3.id(),
        s1.id(),
        "disposed cached top_k_signal must be replaced with a fresh signal"
    );
    assert_eq!(
        scope.get(s3).into_iter().map(|e| e.id).collect::<Vec<_>>(),
        vec![2, 1]
    );
}