Skip to main content

day_reactive/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-reactive: the reactive core (DESIGN.md §3.3, §4).
5//!
6//! Build-once / bind-forever: signals, memos, effects, `bind`, and `watch` over a thread-local
7//! generational arena. All handles are `Copy` and `!Send`; the only cross-thread door is
8//! [`Setter`]. Writes batch; the drain runs to fixpoint in (priority, scope-depth, creation-seq)
9//! order; layout/turn-end callbacks run once after the fixpoint (§3.3's turn state machine).
10//!
11//! `Signal` is `!Send`:
12//! ```compile_fail
13//! fn assert_send<T: Send>(_: T) {}
14//! let s = day_reactive::Signal::new(1);
15//! assert_send(s); // must not compile
16//! ```
17
18// ---------------------------------------------------------------------------------------------
19// `tls_group!`: one pthread key for a module's whole set of thread-locals.
20//
21// On Android, Rust's `thread_local!` has no native-TLS path (`rustc --print cfg
22// --target aarch64-linux-android` emits no `target_thread_local`), so every `thread_local!`
23// static takes one of bionic's 128 `pthread_key_create` slots, allocated on first touch and
24// never released. day plus its dependencies declares far more than that, so a long-running app
25// exhausts the table as more of its code runs first, and the next library to ask for a key
26// fails. Android's WebView is the usual casualty: its browser startup takes several keys, gets
27// none, and traps with no message at all.
28//
29// This macro takes `thread_local!`'s syntax and gives back the same names with the same `.with`,
30// but backs all of them with one key: the slots become fields of a single per-module struct and
31// each name becomes a zero-sized handle that borrows its field. Call sites do not change.
32// Cell/RefCell conveniences (`set`/`get`/`replace`) are absent: go through `.with`, which is
33// what the field itself offers.
34#[macro_export]
35macro_rules! tls_group {
36    ($( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
37        #[allow(non_snake_case)]
38        struct TlsGroupSlots { $( $name: $ty, )+ }
39        ::std::thread_local! {
40            static TLS_GROUP: TlsGroupSlots = TlsGroupSlots { $( $name: $init, )+ };
41        }
42        $(
43            $(#[$attr])*
44            #[allow(non_camel_case_types, dead_code)]
45            #[derive(Clone, Copy)]
46            $vis struct $name;
47            impl $name {
48                #[inline]
49                #[allow(dead_code)]
50                $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
51                    TLS_GROUP.with(|g| f(&g.$name))
52                }
53                #[inline]
54                #[allow(dead_code)]
55                $vis fn try_with<R>(
56                    self,
57                    f: impl ::core::ops::FnOnce(&$ty) -> R,
58                ) -> ::core::result::Result<R, ::std::thread::AccessError> {
59                    TLS_GROUP.try_with(|g| f(&g.$name))
60                }
61            }
62        )+
63    };
64}
65
66// ---------------------------------------------------------------------------------------------
67// `tls_root!` / `tls_slots!`: one pthread key for a whole crate.
68//
69// `tls_group!` above already collapses a module's statics to one key. These two go the last step:
70// each module declares its slots as a plain struct (`tls_slots!`) and the crate root gathers them
71// into a single thread-local (`tls_root!`). A crate then costs one key no matter how many modules
72// keep state, and the root is also the natural place to hang teardown.
73//
74// Call sites are unchanged: the names still answer `.with`. The cost is one line per module
75// naming its field in the root, and `tls_root!` listing the modules. `crate::tls_root` resolves
76// in the expanding crate, so each crate keeps its own root.
77#[macro_export]
78macro_rules! tls_root {
79    ($( $(#[$attr:meta])* $field:ident : $ty:ty ),+ $(,)?) => {
80        #[allow(non_snake_case)]
81        pub(crate) struct TlsRoot { $( $(#[$attr])* pub(crate) $field: $ty, )+ }
82        ::std::thread_local! {
83            static TLS_ROOT: TlsRoot =
84                TlsRoot { $( $(#[$attr])* $field: ::core::default::Default::default(), )+ };
85        }
86        /// Borrow the crate's single thread-local root. Reentrant: the root itself holds no
87        /// lock, so a slot's closure may reach another slot.
88        #[inline]
89        pub(crate) fn tls_root<R>(f: impl ::core::ops::FnOnce(&TlsRoot) -> R) -> R {
90            TLS_ROOT.with(f)
91        }
92        /// Best-effort access for destructor paths after the crate's TLS has gone away.
93        #[inline]
94        #[allow(dead_code)]
95        pub(crate) fn try_tls_root<R>(
96            f: impl ::core::ops::FnOnce(&TlsRoot) -> R,
97        ) -> ::core::result::Result<R, ::std::thread::AccessError> {
98            TLS_ROOT.try_with(f)
99        }
100    };
101}
102
103/// One module's slots, stored as `$field` of the crate's [`tls_root!`].
104// `crate::tls_root` is correct here, and `$crate` would be wrong: the root belongs to the crate
105// expanding this macro, not to day-reactive. That resolution is what gives each crate a root of
106// its own, so the lint is describing the intent rather than a mistake.
107#[allow(clippy::crate_in_macro_def)]
108#[macro_export]
109macro_rules! tls_slots {
110    ($field:ident; $( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
111        #[allow(non_snake_case)]
112        pub(crate) struct TlsGroupSlots { $( $name: $ty, )+ }
113        impl ::core::default::Default for TlsGroupSlots {
114            fn default() -> Self { Self { $( $name: $init, )+ } }
115        }
116        $(
117            $(#[$attr])*
118            #[allow(non_camel_case_types, dead_code)]
119            #[derive(Clone, Copy)]
120            $vis struct $name;
121            impl $name {
122                #[inline]
123                #[allow(dead_code)]
124                $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
125                    crate::tls_root(|r| f(&r.$field.$name))
126                }
127                #[inline]
128                #[allow(dead_code)]
129                $vis fn try_with<R>(
130                    self,
131                    f: impl ::core::ops::FnOnce(&$ty) -> R,
132                ) -> ::core::result::Result<R, ::std::thread::AccessError> {
133                    crate::try_tls_root(|r| f(&r.$field.$name))
134                }
135            }
136        )+
137    };
138}
139
140use std::any::{Any, TypeId};
141use std::cell::{Cell, RefCell};
142use std::collections::{HashMap, HashSet};
143use std::future::Future;
144use std::marker::PhantomData;
145use std::panic::Location;
146use std::pin::Pin;
147use std::rc::Rc;
148use std::sync::Arc;
149
150use slotmap::{Key, SlotMap, new_key_type};
151
152new_key_type! {
153    pub struct NodeKey;
154    pub struct ScopeKey;
155}
156
157// ---------------------------------------------------------------------------
158// Runtime
159// ---------------------------------------------------------------------------
160
161#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
162enum NodeState {
163    Clean,
164    Check,
165    Dirty,
166}
167
168#[derive(Clone, Copy, PartialEq, Eq)]
169enum NodeKind {
170    Signal,
171    Memo,
172    /// Effects, binds, watches: anything with a re-runnable reaction closure.
173    Reaction,
174}
175
176/// Type-erased memo comparator (a monomorphized `PartialEq::eq`).
177type MemoEq = fn(&dyn Any, &dyn Any) -> bool;
178
179/// A node's stored value, shared so a reader can hold it while the runtime borrow is released.
180///
181/// `with`/`try_with` must run the caller's closure without holding the thread-local runtime
182/// borrow (the closure routinely reads other signals, which re-enters `with_rt`). This used to be
183/// done by taking the value out of the node and putting it back afterwards, which had two costs: a
184/// re-entrant read of the same signal found the hole and reported "disposed", and a panic inside
185/// the closure lost the value permanently. Sharing the cell instead lets a reader clone it out
186/// cheaply, so concurrent reads work and the value is never in limbo.
187type NodeValue = Rc<RefCell<Box<dyn Any>>>;
188
189struct Node {
190    kind: NodeKind,
191    state: NodeState,
192    value: Option<NodeValue>,
193    /// Memo recompute (returns boxed new value), compared with `eq`.
194    memo_compute: Option<Rc<dyn Fn() -> Box<dyn Any>>>,
195    memo_eq: Option<MemoEq>,
196    /// Reaction closure (effect/bind/watch body).
197    reaction: Option<Rc<dyn Fn()>>,
198    sources: Vec<NodeKey>,
199    /// Callbacks an external dependency registry (day-model's trigger claims) hangs on this
200    /// computation's current run, drained when the run's sources clear (re-track or disposal),
201    /// mirroring the per-run lifetime of `sources` itself. Run outside the runtime borrow.
202    run_cleanups: Vec<Box<dyn FnOnce()>>,
203    observers: Vec<NodeKey>,
204    // Computations restore this owner when they run, including lazy memo reads.
205    scope: ScopeKey,
206    /// Ordering: (priority, scope depth, creation seq). Priority 0 = structural binding.
207    priority: u8,
208    depth: u32,
209    seq: u64,
210    last_changed: u64,
211    last_run: u64,
212    queued: bool,
213    created_at: &'static Location<'static>,
214}
215
216struct ScopeData {
217    parent: ScopeKey,
218    children: Vec<ScopeKey>,
219    nodes: Vec<NodeKey>,
220    cleanups: Vec<Box<dyn FnOnce()>>,
221    context: HashMap<TypeId, Box<dyn Any>>,
222    depth: u32,
223}
224
225struct Runtime {
226    nodes: SlotMap<NodeKey, Node>,
227    scopes: SlotMap<ScopeKey, ScopeData>,
228    root_scope: ScopeKey,
229    current_scope: ScopeKey,
230    /// Observer stack; `None` = untracked frame.
231    observers: Vec<Option<NodeKey>>,
232    pending: Vec<NodeKey>,
233    batch_depth: u32,
234    draining: bool,
235    tick: u64,
236    next_seq: u64,
237    scheduler: Option<Rc<dyn Fn()>>,
238    schedule_posted: bool,
239    /// The async-spawn door ([`install_spawner`]): runs a boxed future on the app's main-loop
240    /// executor, returning an abort closure.
241    spawner: Option<Spawner>,
242    turn_end: Vec<Rc<dyn Fn()>>,
243    /// One-shot callbacks for the end of the current turn ([`at_turn_end`]).
244    turn_end_once: Vec<Box<dyn FnOnce()>>,
245    warned_writes: HashSet<*const Location<'static>>,
246}
247
248impl Runtime {
249    fn new() -> Self {
250        let mut scopes = SlotMap::with_key();
251        let root_scope = scopes.insert(ScopeData {
252            parent: ScopeKey::null(),
253            children: Vec::new(),
254            nodes: Vec::new(),
255            cleanups: Vec::new(),
256            context: HashMap::new(),
257            depth: 0,
258        });
259        Runtime {
260            nodes: SlotMap::with_key(),
261            scopes,
262            root_scope,
263            current_scope: root_scope,
264            observers: Vec::new(),
265            pending: Vec::new(),
266            batch_depth: 0,
267            draining: false,
268            tick: 1,
269            next_seq: 0,
270            scheduler: None,
271            schedule_posted: false,
272            turn_end_once: Vec::new(),
273            spawner: None,
274            turn_end: Vec::new(),
275            warned_writes: HashSet::new(),
276        }
277    }
278}
279
280crate::tls_group! {
281    static RT: RefCell<Runtime> = RefCell::new(Runtime::new());
282
283}
284
285/// Per-drain re-run cap (§4.2): panic in debug, warn-and-defer in release.
286const RERUN_CAP: u32 = 100;
287
288/// Per-turn cap on drain→turn-end rounds ([`flush_sync`]): same panic/warn split as
289/// [`RERUN_CAP`]. Two rounds settle the normal case (a turn-end hook scheduling reactive
290/// work, such as day-persistence's deferred requeries); reaching the cap means hooks are feeding
291/// each other every round.
292const TURN_ROUND_CAP: u32 = 8;
293
294fn with_rt<R>(f: impl FnOnce(&mut Runtime) -> R) -> R {
295    RT.with(|rt| f(&mut rt.borrow_mut()))
296}
297
298// ---------------------------------------------------------------------------
299// Graph internals
300// ---------------------------------------------------------------------------
301
302#[track_caller]
303fn create_node(rt: &mut Runtime, kind: NodeKind, scope: ScopeKey) -> NodeKey {
304    let depth = rt.scopes.get(scope).map_or(0, |s| s.depth);
305    let seq = rt.next_seq;
306    rt.next_seq += 1;
307    let key = rt.nodes.insert(Node {
308        kind,
309        state: NodeState::Clean,
310        value: None,
311        memo_compute: None,
312        memo_eq: None,
313        reaction: None,
314        sources: Vec::new(),
315        run_cleanups: Vec::new(),
316        observers: Vec::new(),
317        scope,
318        priority: 1,
319        depth,
320        seq,
321        last_changed: 0,
322        last_run: 0,
323        queued: false,
324        created_at: Location::caller(),
325    });
326    if let Some(s) = rt.scopes.get_mut(scope) {
327        s.nodes.push(key);
328    }
329    key
330}
331
332/// Register a tracked read: current observer gains `source` as a dependency.
333fn track_read(rt: &mut Runtime, source: NodeKey) {
334    if let Some(Some(obs)) = rt.observers.last().copied() {
335        if obs == source {
336            return;
337        }
338        let already = rt.nodes[obs].sources.contains(&source);
339        if !already {
340            rt.nodes[obs].sources.push(source);
341            rt.nodes[source].observers.push(obs);
342        }
343    }
344}
345
346/// Unsubscribe `key` from its sources and hand back its run cleanups. The caller must run the
347/// returned closures after releasing the runtime borrow: they call into consumers (day-model
348/// claim release disposes trigger scopes) that re-enter the runtime.
349#[must_use]
350fn clear_sources(rt: &mut Runtime, key: NodeKey) -> Vec<Box<dyn FnOnce()>> {
351    let sources = std::mem::take(&mut rt.nodes[key].sources);
352    for s in sources {
353        if let Some(n) = rt.nodes.get_mut(s)
354            && let Some(pos) = n.observers.iter().position(|&o| o == key)
355        {
356            n.observers.swap_remove(pos);
357        }
358    }
359    std::mem::take(&mut rt.nodes[key].run_cleanups)
360}
361
362/// Mark downstream after a source changed. Direct observers get `Dirty`; transitive
363/// (through memos) get `Check`. Reactions are enqueued.
364fn mark_observers(rt: &mut Runtime, source: NodeKey, level: NodeState) {
365    // Small explicit stack to avoid recursion borrow issues.
366    let mut stack: Vec<(NodeKey, NodeState)> = rt.nodes[source]
367        .observers
368        .iter()
369        .map(|&o| (o, level))
370        .collect();
371    while let Some((key, level)) = stack.pop() {
372        let Some(node) = rt.nodes.get_mut(key) else {
373            continue;
374        };
375        if node.state >= level {
376            continue; // already at least this dirty
377        }
378        node.state = level;
379        match node.kind {
380            NodeKind::Reaction => {
381                if !node.queued {
382                    node.queued = true;
383                    rt.pending.push(key);
384                }
385            }
386            NodeKind::Memo => {
387                for &o in &rt.nodes[key].observers {
388                    stack.push((o, NodeState::Check));
389                }
390            }
391            NodeKind::Signal => {}
392        }
393    }
394}
395
396/// Enter a computation's owner and tracking frame together. A memo can be pulled by a
397/// different window's reaction, and a queued effect can run after its caller has left scope.
398/// Neither should inherit that caller's context or allocate state into its scope.
399fn compute_in_owner<T>(key: NodeKey, f: impl FnOnce() -> T) -> Option<T> {
400    let owner = with_rt(|rt| {
401        let owner = rt.nodes.get(key)?.scope;
402        rt.scopes.contains_key(owner).then_some(owner)
403    })?;
404    let scope = Scope {
405        key: owner,
406        _not_send: PhantomData,
407    };
408    Some(scope.enter(|| {
409        with_rt(|rt| rt.observers.push(Some(key)));
410        let _guard = rt_guard(|rt: &mut Runtime| {
411            rt.observers.pop();
412        });
413        f()
414    }))
415}
416
417/// Pull-refresh a memo: recompute if (transitively) dirty; bump `last_changed` only on real change.
418fn refresh_memo(key: NodeKey) {
419    let Some((state, kind)) = with_rt(|rt| rt.nodes.get(key).map(|n| (n.state, n.kind))) else {
420        return;
421    };
422    if kind != NodeKind::Memo || state == NodeState::Clean {
423        return;
424    }
425    if state == NodeState::Check {
426        // Refresh sources; only recompute if one actually changed since our last run.
427        let (sources, last_run) =
428            with_rt(|rt| (rt.nodes[key].sources.clone(), rt.nodes[key].last_run));
429        let mut any_changed = false;
430        for s in sources {
431            refresh_memo(s);
432            if with_rt(|rt| rt.nodes.get(s).is_some_and(|n| n.last_changed > last_run)) {
433                any_changed = true;
434            }
435        }
436        if !any_changed {
437            with_rt(|rt| {
438                if let Some(n) = rt.nodes.get_mut(key) {
439                    n.state = NodeState::Clean;
440                }
441            });
442            return;
443        }
444    }
445    // Recompute.
446    let compute = with_rt(|rt| rt.nodes[key].memo_compute.clone());
447    let Some(compute) = compute else { return };
448    let cleanups = with_rt(|rt| clear_sources(rt, key));
449    for f in cleanups {
450        f();
451    }
452    let Some(new_value) = compute_in_owner(key, || compute()) else {
453        return;
454    };
455    with_rt(|rt| {
456        let tick = rt.tick;
457        let Some(node) = rt.nodes.get_mut(key) else {
458            return;
459        };
460        let changed = match (node.value.as_ref(), node.memo_eq) {
461            (Some(old), Some(eq)) => {
462                // A reader may be holding this cell; compare against it without disturbing them.
463                let old = old.borrow();
464                !eq(old.as_ref(), new_value.as_ref())
465            }
466            _ => true,
467        };
468        node.last_run = tick;
469        node.state = NodeState::Clean;
470        if changed {
471            // Install a new cell rather than writing through the old one: a read in flight keeps
472            // reading the value it borrowed, for the duration of its closure, instead of panicking.
473            node.value = Some(Rc::new(RefCell::new(new_value)));
474            node.last_changed = tick;
475            rt.tick += 1;
476        }
477        // Downstream was already marked Check when we were invalidated; observers that pull us
478        // will see last_changed. Nothing further to do here.
479    });
480}
481
482/// Run one reaction if it is actually stale.
483fn run_reaction(key: NodeKey) {
484    let info = with_rt(|rt| {
485        rt.nodes.get_mut(key).map(|n| {
486            n.queued = false;
487            (n.state, n.sources.clone(), n.last_run)
488        })
489    });
490    let Some((state, sources, last_run)) = info else {
491        return;
492    };
493    if state == NodeState::Clean {
494        return;
495    }
496    if state == NodeState::Check {
497        let mut any_changed = false;
498        for s in &sources {
499            refresh_memo(*s);
500            if with_rt(|rt| rt.nodes.get(*s).is_some_and(|n| n.last_changed > last_run)) {
501                any_changed = true;
502                break;
503            }
504        }
505        if !any_changed {
506            with_rt(|rt| {
507                if let Some(n) = rt.nodes.get_mut(key) {
508                    n.state = NodeState::Clean;
509                }
510            });
511            return;
512        }
513    }
514    let reaction = with_rt(|rt| rt.nodes.get(key).and_then(|n| n.reaction.clone()));
515    let Some(reaction) = reaction else { return };
516    let cleanups = with_rt(|rt| {
517        let cleanups = clear_sources(rt, key);
518        if let Some(n) = rt.nodes.get_mut(key) {
519            n.state = NodeState::Clean;
520        }
521        cleanups
522    });
523    // Released claims must drop before the fresh run tracks, and outside the borrow.
524    for f in cleanups {
525        f();
526    }
527    compute_in_owner(key, || reaction());
528    with_rt(|rt| {
529        let tick = rt.tick;
530        rt.tick += 1;
531        if let Some(n) = rt.nodes.get_mut(key) {
532            n.last_run = tick;
533        }
534    });
535}
536
537/// Drain the pending queue to fixpoint, then run turn-end callbacks (§3.3 steps 2–3),
538/// repeating both until the turn is quiescent. A turn-end callback may schedule new
539/// reactive work (day-persistence's autosave flush re-derives live queries and diffs the
540/// answers into signals); that work belongs to this turn: §3.3 step 2's "writes made
541/// during the drain extend the current drain", extended across the turn-end boundary.
542/// Left pending instead, every cross-row readout (a query-fed list, a derived bound)
543/// would render one turn stale. Round two drains the deltas and re-runs the hooks, and
544/// autosave then finds nothing dirty, so a settled app exits after two rounds;
545/// The turn-round cap stops turn-end hooks that feed each other forever.
546///
547/// # Panics
548///
549/// In debug builds, panics when one effect re-runs past the per-drain cap (a reactive cycle)
550/// or when turn-end callbacks keep scheduling work past the round cap. Release builds log a
551/// warning and recover.
552pub fn flush_sync() {
553    let already = with_rt(|rt| {
554        if rt.draining {
555            return true;
556        }
557        rt.draining = true;
558        false
559    });
560    if already {
561        return; // re-entrant flush folds into the current drain
562    }
563    let mut round = 0u32;
564    loop {
565        round += 1;
566        // Fresh per round: the re-run cap is per drain (§4.2), and each round is one drain.
567        let mut run_counts: HashMap<NodeKey, u32> = HashMap::new();
568        loop {
569            let mut batch = with_rt(|rt| std::mem::take(&mut rt.pending));
570            if batch.is_empty() {
571                break;
572            }
573            // (priority, scope-depth, creation-seq): owners before descendants.
574            with_rt(|rt| {
575                batch.sort_by_key(|&k| {
576                    rt.nodes.get(k).map_or((u8::MAX, u32::MAX, u64::MAX), |n| {
577                        (n.priority, n.depth, n.seq)
578                    })
579                });
580            });
581            for key in batch {
582                let count = run_counts.entry(key).or_insert(0);
583                *count += 1;
584                if *count > RERUN_CAP {
585                    if *count == RERUN_CAP + 1 {
586                        let loc = with_rt(|rt| rt.nodes.get(key).map(|n| n.created_at));
587                        if let Some(loc) = loc {
588                            debug_assert!(
589                                false,
590                                "day-reactive: effect created at {loc} re-ran more than {RERUN_CAP} times in one drain (reactive cycle?)"
591                            );
592                            log::warn!(
593                                "day-reactive: effect created at {loc} exceeded the re-run cap; skipping it for the rest of this drain (the next source write re-arms it)"
594                            );
595                        }
596                    }
597                    // Break the cycle but leave the node runnable. This key was drained out of
598                    // `pending` above with `queued` still true; without the reset here,
599                    // `mark_observers` would never enqueue it again and the binding would be
600                    // silently dead for the rest of the process. Clean + unqueued means the next
601                    // source write re-marks and re-enqueues it with a fresh per-drain budget.
602                    with_rt(|rt| {
603                        if let Some(n) = rt.nodes.get_mut(key) {
604                            n.queued = false;
605                            n.state = NodeState::Clean;
606                        }
607                    });
608                    continue;
609                }
610                run_reaction(key);
611            }
612        }
613        let (once, turn_end) = with_rt(|rt| {
614            rt.draining = false;
615            rt.schedule_posted = false;
616            (std::mem::take(&mut rt.turn_end_once), rt.turn_end.clone())
617        });
618        // One-shot work first: it settles what this turn changed (a toolbar composed once from
619        // everything the turn contributed), which the standing hooks (layout) then see.
620        for cb in once {
621            cb();
622        }
623        for cb in turn_end {
624            cb();
625        }
626        // Quiescent, or a nested flush inside a callback already settled everything.
627        let more = with_rt(|rt| {
628            if rt.pending.is_empty() {
629                return false;
630            }
631            rt.draining = true;
632            true
633        });
634        if !more {
635            return;
636        }
637        if round >= TURN_ROUND_CAP {
638            // The callbacks' first write posted a scheduled drain (draining was false
639            // then), so the deferred work still runs next turn, the same recovery shape as
640            // the re-run cap.
641            with_rt(|rt| rt.draining = false);
642            debug_assert!(
643                false,
644                "day-reactive: turn-end callbacks scheduled new reactive work for {TURN_ROUND_CAP} straight rounds in one turn (hooks feeding each other?)"
645            );
646            log::warn!(
647                "day-reactive: turn-end callbacks still scheduling work after {TURN_ROUND_CAP} rounds; deferring the rest to the next turn"
648            );
649            return;
650        }
651    }
652}
653
654/// Reset the runtime to a clean idle state after a panic unwound through a drain or batch,
655/// e.g. a reactive-cycle assertion (the rerun cap) that tripped inside a native event callback
656/// which the backend *contained* (rather than letting it abort the process across the C ABI; a
657/// GTK/Qt signal trampoline can't unwind). The in-flight `pending` work and the observer stack
658/// are dropped (the next interaction re-derives them); persistent registrations (effects, memos,
659/// turn-end hooks) are kept.
660pub fn recover_from_panic() {
661    with_rt(|rt| {
662        rt.draining = false;
663        rt.schedule_posted = false;
664        rt.batch_depth = 0;
665        rt.turn_end_once.clear();
666        rt.pending.clear();
667        rt.observers.clear();
668        // The scope stack is unwound by `Scope::enter`'s guard, but a panic raised between
669        // scopes (or from a callsite that set `current_scope` directly) can still leave it on a
670        // disposed scope, where every later `Signal::new` would be born dead. Re-root it.
671        rt.current_scope = rt.root_scope;
672    });
673}
674
675/// After a write: schedule work. Inside a batch or drain, the fixpoint picks it up; outside,
676/// post a coalesced drain through the installed scheduler (§3.3 step 3).
677fn schedule_after_write(rt: &mut Runtime) -> Option<Rc<dyn Fn()>> {
678    if rt.batch_depth > 0 || rt.draining {
679        return None;
680    }
681    if rt.schedule_posted {
682        return None;
683    }
684    rt.schedule_posted = true;
685    rt.scheduler.clone()
686}
687
688fn signal_write_boxed(key: NodeKey, apply: impl FnOnce(&mut Box<dyn Any>) -> bool) {
689    let poster = with_rt(|rt| {
690        let node = rt.nodes.get_mut(key)?;
691        let cell = node.value.as_ref()?.clone();
692        // A write to a signal from inside its own `with`/`try_with` closure. Before the value
693        // was shared this silently did nothing (the read's restore clobbered the write), so
694        // say it plainly instead of losing the update.
695        let Ok(mut value) = cell.try_borrow_mut() else {
696            panic!(
697                "day-reactive: wrote to a Signal while a with()/try_with() read of it is still \
698                 in flight — the write would be lost. Finish the read closure first (copy the \
699                 value out with get()) and write after it returns."
700            )
701        };
702        let changed = apply(&mut value);
703        drop(value);
704        let node = rt.nodes.get_mut(key)?;
705        if !changed {
706            return None;
707        }
708        node.last_changed = rt.tick;
709        rt.tick += 1;
710        mark_observers(rt, key, NodeState::Dirty);
711        schedule_after_write(rt)
712    });
713    if let Some(post) = poster {
714        post();
715    }
716}
717
718// ---------------------------------------------------------------------------
719// Public: batching / scheduling / turn end
720// ---------------------------------------------------------------------------
721
722/// Run `f` in a batch: writes coalesce; the synchronous fixpoint drain runs at batch close.
723/// Restores a piece of runtime state when it goes out of scope, on the normal path and on an
724/// unwind. day-core contains panics at its trampoline boundaries (`pump_events`, posted tasks,
725/// lifecycle) so a panicking app callback degrades the UI instead of aborting the process; that
726/// guarantee is only worth anything if the reactive runtime is still coherent afterwards.
727/// Restoring after `f()` returns is not enough, because that line is skipped on unwind.
728fn rt_guard(f: impl FnOnce(&mut Runtime)) -> impl Drop {
729    std::mem::DropGuard::new((), |()| with_rt(f))
730}
731
732pub fn batch<R>(f: impl FnOnce() -> R) -> R {
733    with_rt(|rt| rt.batch_depth += 1);
734    let r = {
735        // Runs on unwind too, so a contained panic can't strand `batch_depth` above zero, which
736        // would stop every later write from scheduling a drain (a silently frozen UI). Saturating:
737        // if `recover_from_panic` already zeroed the depth mid-unwind, a plain `-= 1` here would
738        // underflow: a panic inside this Drop, which is a process abort.
739        let _g = rt_guard(|rt: &mut Runtime| rt.batch_depth = rt.batch_depth.saturating_sub(1));
740        f()
741    };
742    let should_drain = with_rt(|rt| {
743        rt.batch_depth == 0
744            && !rt.draining
745            && (!rt.pending.is_empty() || !rt.turn_end_once.is_empty())
746    });
747    if should_drain {
748        flush_sync();
749    }
750    r
751}
752
753/// Force a synchronous fixpoint drain **now**, even inside an open [`batch`]. Event dispatch wraps
754/// handlers in a batch (day-core), so a handler that needs its writes to drain immediately
755/// (namely `with_animation`, whose ambient animation must be live *while* the resulting patches
756/// apply) cannot rely on the batch's close (that runs later, after the scope ends). This
757/// temporarily drops the batch depth so [`flush_sync`] runs, then restores it. No-op if a drain
758/// is already in progress (the writes fold into it); harmless if nothing is pending.
759pub fn flush_now() {
760    let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
761    // Restored on unwind too: the debug rerun-cap panic can cross here under an event-dispatch
762    // batch, and skipping the restore would hand the enclosing batch guard a zero depth.
763    let _g = rt_guard(move |rt: &mut Runtime| rt.batch_depth = saved);
764    flush_sync();
765}
766
767/// Run `f` without tracking reads.
768pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
769    with_rt(|rt| rt.observers.push(None));
770    // Popped on unwind too: a stranded `None` observer would silently disable dependency
771    // tracking for every read that followed, so nothing would ever update again.
772    let _g = rt_guard(|rt: &mut Runtime| {
773        rt.observers.pop();
774    });
775    f()
776}
777
778/// The identity of one reactive computation (a reaction or a memo) across its lifetime.
779/// Opaque; `Copy + Eq + Hash`, so an external dependency registry can key per-computation
780/// bookkeeping on it. Slotmap-generational underneath: a recycled slot is a new `RunId`.
781#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
782pub struct RunId(NodeKey);
783
784/// The computation currently tracking reads: `None` at top level and under [`untrack`].
785pub fn active_run() -> Option<RunId> {
786    with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
787}
788
789/// Hang `f` on the active computation's current run: it fires when that computation next
790/// re-tracks (a re-run clears its sources first) or is disposed. This is the hook that lets an
791/// external dependency registry (day-model's trigger claims) mirror this graph's per-run
792/// source bookkeeping. Returns `false`, registering nothing, when no computation is tracking.
793pub fn on_run_retrack(f: impl FnOnce() + 'static) -> bool {
794    with_rt(|rt| {
795        let Some(Some(key)) = rt.observers.last().copied() else {
796            return false;
797        };
798        match rt.nodes.get_mut(key) {
799            Some(n) => {
800                n.run_cleanups.push(Box::new(f));
801                true
802            }
803            None => false,
804        }
805    })
806}
807
808/// Install "post a drain on the main loop". Backends call this once at startup.
809pub fn install_scheduler(post: impl Fn() + 'static) {
810    with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
811}
812
813/// A boxed, `!Send` future for the [`install_spawner`] executor door.
814pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
815
816/// The installed spawner: runs a future on the main-loop executor, returns its abort closure.
817type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
818
819/// Install the async-spawn door: `spawn` runs a future on the app's main-loop executor and
820/// returns an abort closure (remove + drop the future). The abort must be a no-op once the
821/// task has completed: [`Resource`] stores it after an eager first poll, so a synchronously
822/// ready future has already finished by then. day-core's `launch_with` wires this to
823/// `day::task` / `TaskHandle::abort`; call it once at startup (docs/async.md).
824pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
825    with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
826}
827
828/// Spawn through the installed door ([`install_spawner`]); the [`on_main`] panic model.
829fn spawn_local(fut: LocalBoxFuture) -> Box<dyn FnOnce()> {
830    let spawner = with_rt(|rt| rt.spawner.clone());
831    match spawner {
832        Some(s) => s(fut),
833        None => panic!("day-reactive: no spawner installed (backend not started)"),
834    }
835}
836
837/// Register a callback run once after every fixpoint drain (day-core's layout turn).
838pub fn on_turn_end(cb: impl Fn() + 'static) {
839    with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
840}
841
842/// Run `cb` once, when the current turn settles: after the drain inside a drain or a batch
843/// (even a batch that leaves no reactive work behind), or right away when no turn is open.
844///
845/// This is how a consumer coalesces a burst of changes into one pass. Swapping a page
846/// withdraws the old page's toolbar items and contributes the new page's within one turn, and
847/// only the settled result is worth handing to the toolkit.
848pub fn at_turn_end(cb: impl FnOnce() + 'static) {
849    let now = with_rt(|rt| {
850        if rt.draining || rt.batch_depth > 0 {
851            rt.turn_end_once.push(Box::new(cb));
852            None
853        } else {
854            Some(cb)
855        }
856    });
857    if let Some(cb) = now {
858        cb();
859    }
860}
861
862// ---------------------------------------------------------------------------
863// Cross-thread: the main poster + Setter
864// ---------------------------------------------------------------------------
865
866type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
867static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
868
869/// Install the cross-thread → main-thread door. Backends call this once at startup.
870pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
871    let _ = MAIN_POSTER.set(Box::new(post));
872}
873
874/// Whether a backend has installed the main poster yet, i.e. whether [`on_main`] would work
875/// rather than panic. Platform glue that can be called before launch (a notification tap that
876/// cold-starts the process) probes this and buffers instead of posting. The poster is set once
877/// and never cleared, so a `false` can only become `true`: a caller that buffers on a false
878/// negative is still correct, provided something drains the buffer at launch.
879pub fn has_main_poster() -> bool {
880    MAIN_POSTER.get().is_some()
881}
882
883/// Schedule `f` on the UI thread (usable from any thread once a backend installed the poster).
884///
885/// # Panics
886///
887/// Panics when no backend has installed the main poster yet (see [`has_main_poster`]).
888pub fn on_main(f: impl FnOnce() + Send + 'static) {
889    match MAIN_POSTER.get() {
890        Some(post) => post(Box::new(f)),
891        None => panic!("day-reactive: no main poster installed (backend not started)"),
892    }
893}
894
895type DelayedPoster = Box<dyn Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync>;
896static DELAYED_POSTER: std::sync::OnceLock<DelayedPoster> = std::sync::OnceLock::new();
897
898/// Install the timer door (`Platform::post_delayed`). Backends call this once at startup.
899pub fn install_delayed_poster(
900    post: impl Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync + 'static,
901) {
902    let _ = DELAYED_POSTER.set(Box::new(post));
903}
904
905/// Schedule `f` on the UI thread after (at least) `ms` milliseconds, the rail behind
906/// `day::sleep` (docs/async.md).
907///
908/// # Panics
909///
910/// Panics when no backend has installed the delayed poster yet.
911pub fn on_main_delayed(ms: u32, f: impl FnOnce() + Send + 'static) {
912    match DELAYED_POSTER.get() {
913        Some(post) => post(ms, Box::new(f)),
914        None => panic!("day-reactive: no delayed poster installed (backend not started)"),
915    }
916}
917
918// ---------------------------------------------------------------------------
919// Scope
920// ---------------------------------------------------------------------------
921
922/// Ownership scope for signals/effects (§4.3). `Copy` handle; not `Send`.
923#[derive(Clone, Copy, PartialEq, Eq)]
924pub struct Scope {
925    key: ScopeKey,
926    _not_send: PhantomData<*const ()>,
927}
928
929impl Scope {
930    pub fn current() -> Scope {
931        Scope {
932            key: with_rt(|rt| rt.current_scope),
933            _not_send: PhantomData,
934        }
935    }
936
937    pub fn root() -> Scope {
938        Scope {
939            key: with_rt(|rt| rt.root_scope),
940            _not_send: PhantomData,
941        }
942    }
943
944    /// Create a child of the current scope.
945    pub fn child() -> Scope {
946        Scope::current().create_child()
947    }
948
949    #[must_use]
950    pub fn create_child(self) -> Scope {
951        let key = with_rt(|rt| {
952            let depth = rt.scopes.get(self.key).map_or(1, |s| s.depth + 1);
953            let child = rt.scopes.insert(ScopeData {
954                parent: self.key,
955                children: Vec::new(),
956                nodes: Vec::new(),
957                cleanups: Vec::new(),
958                context: HashMap::new(),
959                depth,
960            });
961            if let Some(p) = rt.scopes.get_mut(self.key) {
962                p.children.push(child);
963            }
964            child
965        });
966        Scope {
967            key,
968            _not_send: PhantomData,
969        }
970    }
971
972    /// A scope owned by nobody; dispose it manually.
973    pub fn detached() -> Scope {
974        let key = with_rt(|rt| {
975            rt.scopes.insert(ScopeData {
976                parent: ScopeKey::null(),
977                children: Vec::new(),
978                nodes: Vec::new(),
979                cleanups: Vec::new(),
980                context: HashMap::new(),
981                depth: 0,
982            })
983        });
984        Scope {
985            key,
986            _not_send: PhantomData,
987        }
988    }
989
990    /// Run `f` with `self` as the current scope.
991    pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
992        let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
993        // Restored on unwind too. Otherwise a contained panic leaves the runtime parented to
994        // this (usually transient, soon-disposed) scope, so every later `Signal::new` is created
995        // dead and its first read panics with a misleading "read of disposed Signal".
996        let _g = rt_guard(move |rt: &mut Runtime| rt.current_scope = prev);
997        f()
998    }
999
1000    pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1001        with_rt(|rt| {
1002            if let Some(s) = rt.scopes.get_mut(self.key) {
1003                s.cleanups.push(Box::new(f));
1004            }
1005        });
1006    }
1007
1008    #[must_use]
1009    pub fn is_alive(self) -> bool {
1010        with_rt(|rt| rt.scopes.contains_key(self.key))
1011    }
1012
1013    /// Dispose this scope: children first, then own nodes (unsubscribed + dropped) and cleanups.
1014    pub fn dispose(self) {
1015        let Some(children) = with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone()))
1016        else {
1017            return;
1018        };
1019        for c in children {
1020            (Scope {
1021                key: c,
1022                _not_send: PhantomData,
1023            })
1024            .dispose();
1025        }
1026        let Some((nodes, cleanups, parent)) = with_rt(|rt| {
1027            rt.scopes
1028                .remove(self.key)
1029                .map(|s| (s.nodes, s.cleanups, s.parent))
1030        }) else {
1031            return;
1032        };
1033        let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1034        with_rt(|rt| {
1035            if let Some(p) = rt.scopes.get_mut(parent)
1036                && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1037            {
1038                p.children.swap_remove(pos);
1039            }
1040            for key in nodes {
1041                run_cleanups.extend(clear_sources(rt, key));
1042                // Detach us from downstream observers too.
1043                if let Some(node) = rt.nodes.get_mut(key) {
1044                    let observers = std::mem::take(&mut node.observers);
1045                    for o in observers {
1046                        if let Some(on) = rt.nodes.get_mut(o)
1047                            && let Some(pos) = on.sources.iter().position(|&s| s == key)
1048                        {
1049                            on.sources.swap_remove(pos);
1050                        }
1051                    }
1052                }
1053                rt.nodes.remove(key);
1054                // Pending entries for removed nodes are skipped at pop (generational key check).
1055            }
1056        });
1057        // A dying computation's per-run claims drop like a re-track would drop them: outside
1058        // the borrow, before the scope's own cleanups (which may release scope-level claims).
1059        for f in run_cleanups {
1060            f();
1061        }
1062        for c in cleanups {
1063            c();
1064        }
1065    }
1066
1067    /// Provide a context value visible to this scope and its descendants.
1068    pub fn provide<T: 'static>(self, value: T) {
1069        with_rt(|rt| {
1070            if let Some(s) = rt.scopes.get_mut(self.key) {
1071                s.context.insert(TypeId::of::<T>(), Box::new(value));
1072            }
1073        });
1074    }
1075
1076    /// Look up a context value here or in any ancestor (requires `T: Clone`).
1077    #[must_use]
1078    pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1079        with_rt(|rt| {
1080            let mut cur = self.key;
1081            while let Some(s) = rt.scopes.get(cur) {
1082                if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1083                    return v.downcast_ref::<T>().cloned();
1084                }
1085                cur = s.parent;
1086            }
1087            None
1088        })
1089    }
1090}
1091
1092// ---------------------------------------------------------------------------
1093// Signal
1094// ---------------------------------------------------------------------------
1095
1096/// A `Copy`, `!Send` reactive value handle (§4.2).
1097pub struct Signal<T: 'static> {
1098    key: NodeKey,
1099    created_at: &'static Location<'static>,
1100    _m: PhantomData<*const T>,
1101}
1102
1103impl<T: 'static> Clone for Signal<T> {
1104    fn clone(&self) -> Self {
1105        *self
1106    }
1107}
1108impl<T: 'static> Copy for Signal<T> {}
1109
1110impl<T: 'static> std::fmt::Debug for Signal<T> {
1111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112        write!(f, "Signal({:?})", self.key)
1113    }
1114}
1115
1116impl<T: 'static> Signal<T> {
1117    #[track_caller]
1118    pub fn new(value: T) -> Self {
1119        Self::new_in(Scope::current(), value)
1120    }
1121
1122    /// A process-global signal: allocated in the root scope regardless of where the call
1123    /// runs, so it never dies with a transient caller. **Every lazily-initialized global
1124    /// registry must use this, not [`Signal::new`]**, because a lazy global first touched inside a
1125    /// presented cover / pushed page / `when` arm otherwise inherits that scope and is
1126    /// disposed with it, and every later read panics (the day-localization locale signal was the
1127    /// observed case).
1128    #[track_caller]
1129    pub fn global(value: T) -> Self {
1130        Self::new_in(Scope::root(), value)
1131    }
1132
1133    #[track_caller]
1134    pub fn new_in(scope: Scope, value: T) -> Self {
1135        let created_at = Location::caller();
1136        let key = with_rt(|rt| {
1137            let k = create_node(rt, NodeKind::Signal, scope.key);
1138            rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1139            rt.nodes[k].created_at = created_at;
1140            k
1141        });
1142        Signal {
1143            key,
1144            created_at,
1145            _m: PhantomData,
1146        }
1147    }
1148
1149    /// Tracked read by reference.
1150    ///
1151    /// # Panics
1152    ///
1153    /// Panics when the signal's scope was disposed. Use [`Signal::try_with`] in closures that
1154    /// can outlive their scope.
1155    #[track_caller]
1156    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1157        match self.try_with(f) {
1158            Some(r) => r,
1159            None => panic!(
1160                "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1161                self.created_at
1162            ),
1163        }
1164    }
1165
1166    pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1167        // Clone the shared cell out so `f` runs with the runtime borrow released (it routinely
1168        // reads other signals). The value stays in the node throughout, so a re-entrant read of
1169        // This signal inside `f` succeeds instead of reporting a disposed node, and a panic in
1170        // `f` cannot strand it.
1171        let cell = with_rt(|rt| {
1172            track_read(rt, self.key);
1173            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1174        })?;
1175        let value = cell.borrow();
1176        value.downcast_ref::<T>().map(f)
1177    }
1178
1179    pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1180        untrack(|| self.with(f))
1181    }
1182
1183    #[track_caller]
1184    #[must_use]
1185    pub fn get(self) -> T
1186    where
1187        T: Clone,
1188    {
1189        self.with(std::clone::Clone::clone)
1190    }
1191
1192    #[must_use]
1193    pub fn try_get(self) -> Option<T>
1194    where
1195        T: Clone,
1196    {
1197        self.try_with(std::clone::Clone::clone)
1198    }
1199
1200    #[must_use]
1201    pub fn get_untracked(self) -> T
1202    where
1203        T: Clone,
1204    {
1205        untrack(|| self.get())
1206    }
1207
1208    /// Mark-only tracked read (subscribe without reading).
1209    pub fn track(self) {
1210        with_rt(|rt| track_read(rt, self.key));
1211    }
1212
1213    #[track_caller]
1214    pub fn set(self, value: T) {
1215        self.write_check(move |slot| {
1216            *slot = value;
1217            true
1218        });
1219    }
1220
1221    #[track_caller]
1222    pub fn set_if_changed(self, value: T)
1223    where
1224        T: PartialEq,
1225    {
1226        self.write_check(move |slot| {
1227            if *slot == value {
1228                false
1229            } else {
1230                *slot = value;
1231                true
1232            }
1233        });
1234    }
1235
1236    #[track_caller]
1237    pub fn update(self, f: impl FnOnce(&mut T)) {
1238        self.write_check(move |slot| {
1239            f(slot);
1240            true
1241        });
1242    }
1243
1244    #[track_caller]
1245    fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1246        let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1247        if !alive {
1248            // Writes to disposed handles are defined no-ops (§4.3), warned once per callsite.
1249            let loc = Location::caller();
1250            let first = with_rt(|rt| rt.warned_writes.insert(std::ptr::from_ref(loc)));
1251            if first && cfg!(debug_assertions) {
1252                log::warn!(
1253                    "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1254                    self.created_at
1255                );
1256            }
1257            return;
1258        }
1259        signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1260            Some(slot) => apply(slot),
1261            None => false,
1262        });
1263    }
1264
1265    /// A `Send` write-only handle (§3.3).
1266    #[must_use]
1267    pub fn setter(self) -> Setter<T>
1268    where
1269        T: Send,
1270    {
1271        Setter {
1272            key: self.key,
1273            _m: PhantomData,
1274        }
1275    }
1276}
1277
1278/// `Send` write-only handle to a signal; delivery hops to the UI thread via the main poster.
1279/// Writes after disposal are silent no-ops (§4.3).
1280pub struct Setter<T: Send + 'static> {
1281    key: NodeKey,
1282    _m: PhantomData<fn(T)>,
1283}
1284
1285impl<T: Send + 'static> Clone for Setter<T> {
1286    fn clone(&self) -> Self {
1287        *self
1288    }
1289}
1290impl<T: Send + 'static> Copy for Setter<T> {}
1291
1292impl<T: Send + 'static> Setter<T> {
1293    pub fn set(self, value: T) {
1294        let key = self.key;
1295        on_main(move || {
1296            let poster = with_rt(|rt| {
1297                let cell = rt.nodes.get(key)?.value.clone()?;
1298                {
1299                    let mut boxed = cell.try_borrow_mut().ok()?;
1300                    let slot = boxed.downcast_mut::<T>()?;
1301                    *slot = value;
1302                }
1303                let node = rt.nodes.get_mut(key)?;
1304                node.last_changed = rt.tick;
1305                rt.tick += 1;
1306                mark_observers(rt, key, NodeState::Dirty);
1307                schedule_after_write(rt)
1308            });
1309            if let Some(post) = poster {
1310                post();
1311            }
1312        });
1313    }
1314}
1315
1316// ---------------------------------------------------------------------------
1317// Memo
1318// ---------------------------------------------------------------------------
1319
1320/// Cached, equality-diffed derived value (§4.2).
1321pub struct Memo<T: 'static> {
1322    key: NodeKey,
1323    created_at: &'static Location<'static>,
1324    _m: PhantomData<*const T>,
1325}
1326
1327impl<T: 'static> Clone for Memo<T> {
1328    fn clone(&self) -> Self {
1329        *self
1330    }
1331}
1332impl<T: 'static> Copy for Memo<T> {}
1333
1334impl<T: 'static> Memo<T> {
1335    #[track_caller]
1336    pub fn new(f: impl Fn() -> T + 'static) -> Self
1337    where
1338        T: PartialEq,
1339    {
1340        Self::new_with_eq(f, |a, b| a == b)
1341    }
1342
1343    #[track_caller]
1344    pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1345        let created_at = Location::caller();
1346        // The value is stored as EqBox<T> (value + comparator together), so diffing needs no
1347        // specialization and the arena-level eq is a plain fn pointer (eqbox_eq::<T>).
1348        let key = with_rt(|rt| {
1349            let scope = rt.current_scope;
1350            create_node(rt, NodeKind::Memo, scope)
1351        });
1352        let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1353            Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1354        with_rt(|rt| {
1355            let node = &mut rt.nodes[key];
1356            node.memo_compute = Some(compute);
1357            node.memo_eq = Some(eqbox_eq::<T>);
1358            node.state = NodeState::Dirty; // lazy: computed on first read
1359            node.created_at = created_at;
1360        });
1361        Memo {
1362            key,
1363            created_at,
1364            _m: PhantomData,
1365        }
1366    }
1367
1368    /// Tracked read by reference, recomputing first when a source changed.
1369    ///
1370    /// # Panics
1371    ///
1372    /// Panics when the memo's scope was disposed.
1373    #[track_caller]
1374    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1375        refresh_memo(self.key);
1376        let value = with_rt(|rt| {
1377            track_read(rt, self.key);
1378            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1379        });
1380        match value {
1381            // Shared, like `Signal::try_with`: the memo stays readable while `f` runs.
1382            Some(cell) => {
1383                let boxed = cell.borrow();
1384                boxed.downcast_ref::<EqBox<T>>().map_or_else(
1385                    || panic!("day-reactive: memo type mismatch"),
1386                    |e| f(&e.value),
1387                )
1388            }
1389            None => panic!(
1390                "day-reactive: read of disposed Memo created at {}",
1391                self.created_at
1392            ),
1393        }
1394    }
1395
1396    #[track_caller]
1397    #[must_use]
1398    pub fn get(self) -> T
1399    where
1400        T: Clone,
1401    {
1402        self.with(std::clone::Clone::clone)
1403    }
1404}
1405
1406/// Value + comparator stored together so memo diffing needs no specialization.
1407struct EqBox<T> {
1408    value: T,
1409    eq: fn(&T, &T) -> bool,
1410}
1411
1412fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1413    match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1414        (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1415        _ => false,
1416    }
1417}
1418
1419// ---------------------------------------------------------------------------
1420// Effect / bind / watch / Trigger
1421// ---------------------------------------------------------------------------
1422
1423/// A reaction that re-runs when its tracked reads change. Runs once at creation.
1424/// Every run enters the scope that created it. Ambient context and any new state or
1425/// cleanup registrations belong to that owner, including when another scope triggers it.
1426pub struct Effect;
1427
1428impl Effect {
1429    // Constructor-style registration: the reaction is owned by the current Scope (disposed
1430    // with it), so there is no handle value to return.
1431    #[allow(clippy::new_ret_no_self)]
1432    #[track_caller]
1433    pub fn new(f: impl Fn() + 'static) {
1434        create_reaction(Rc::new(f), 1);
1435    }
1436}
1437
1438#[track_caller]
1439fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1440    let created_at = Location::caller();
1441    let key = with_rt(|rt| {
1442        let scope = rt.current_scope;
1443        let k = create_node(rt, NodeKind::Reaction, scope);
1444        rt.nodes[k].reaction = Some(f);
1445        rt.nodes[k].priority = priority;
1446        rt.nodes[k].created_at = created_at;
1447        k
1448    });
1449    let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1450    if let Some(reaction) = reaction {
1451        compute_in_owner(key, || reaction());
1452    }
1453    with_rt(|rt| {
1454        let tick = rt.tick;
1455        rt.tick += 1;
1456        if let Some(n) = rt.nodes.get_mut(key) {
1457            n.last_run = tick;
1458        }
1459    });
1460    key
1461}
1462
1463/// The binding primitive (§4.2): compute (tracked) + apply (untracked), equality-gated.
1464/// Structural priority: bindings drain before plain effects. `apply` receives the new value
1465/// by reference so `V` needs only `PartialEq` (no `Clone`).
1466#[track_caller]
1467pub fn bind<V: PartialEq + 'static>(
1468    compute: impl Fn() -> V + 'static,
1469    apply: impl Fn(&V) + 'static,
1470) {
1471    let last: RefCell<Option<V>> = RefCell::new(None);
1472    create_reaction(
1473        Rc::new(move || {
1474            let v = compute();
1475            if last.borrow().as_ref() != Some(&v) {
1476                untrack(|| apply(&v));
1477                *last.borrow_mut() = Some(v);
1478            }
1479        }),
1480        0,
1481    );
1482}
1483
1484/// `bind` pre-seeded with the value already applied at build time: the initial run does not
1485/// re-apply (pieces pass initial values through realize props; §5.2's no-duplicate-op rule).
1486#[track_caller]
1487pub fn bind_seeded<V: PartialEq + 'static>(
1488    seed: V,
1489    compute: impl Fn() -> V + 'static,
1490    apply: impl Fn(&V) + 'static,
1491) {
1492    let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1493    create_reaction(
1494        Rc::new(move || {
1495            let v = compute();
1496            if last.borrow().as_ref() != Some(&v) {
1497                untrack(|| apply(&v));
1498                *last.borrow_mut() = Some(v);
1499            }
1500        }),
1501        0,
1502    );
1503}
1504
1505/// `bind` for payloads without `PartialEq`, applying on every recompute.
1506#[track_caller]
1507pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1508    create_reaction(
1509        Rc::new(move || {
1510            let v = compute();
1511            untrack(|| apply(v));
1512        }),
1513        0,
1514    );
1515}
1516
1517/// Derive-state without effect-write loops (§4.2): `source` is tracked; `cb` runs untracked
1518/// with (new, old). Does not fire for the initial value: a "load whatever is selected"
1519/// reaction has to run once by hand first, or use [`bind`], which applies the initial value
1520/// and then every change.
1521#[track_caller]
1522pub fn watch<S: Clone + 'static>(
1523    source: impl Fn() -> S + 'static,
1524    cb: impl Fn(&S, Option<&S>) + 'static,
1525) {
1526    let prev: RefCell<Option<S>> = RefCell::new(None);
1527    create_reaction(
1528        Rc::new(move || {
1529            let new = source();
1530            let old = prev.borrow_mut().replace(new.clone());
1531            if old.is_some() {
1532                untrack(|| cb(&new, old.as_ref()));
1533            }
1534        }),
1535        1,
1536    );
1537}
1538
1539/// Data-less invalidation source.
1540#[derive(Clone, Copy)]
1541pub struct Trigger {
1542    signal: Signal<u64>,
1543}
1544
1545impl Trigger {
1546    #[track_caller]
1547    #[must_use]
1548    pub fn new() -> Self {
1549        Trigger {
1550            signal: Signal::new(0),
1551        }
1552    }
1553    pub fn track(self) {
1554        self.signal.track();
1555    }
1556    pub fn notify(self) {
1557        self.signal.update(|v| *v = v.wrapping_add(1));
1558    }
1559}
1560
1561impl Default for Trigger {
1562    fn default() -> Self {
1563        Self::new()
1564    }
1565}
1566
1567// ---------------------------------------------------------------------------
1568// Two-way binding surface (§5.3)
1569// ---------------------------------------------------------------------------
1570
1571/// A readable-writable value a control can bind to two-way: a `Signal`, or any projection that
1572/// knows how to read and write its own slot (day-model's `Field` is the other implementor).
1573///
1574/// The trait lives here rather than in day-pieces so a store crate can implement it without
1575/// depending on the piece vocabulary; day-pieces re-exports it, so piece code sees no move.
1576pub trait Binding<T: 'static>: Clone + 'static {
1577    /// Tracked read: the current value, subscribing the running computation to changes.
1578    fn read(&self) -> T;
1579    /// Untracked read: the current value, subscribing nothing (the reactive world's "peek").
1580    fn peek(&self) -> T;
1581    /// Write the value, waking whatever tracks it.
1582    fn write(&self, v: T);
1583    /// A live write mid-gesture (`Event::ValueChanged`): readers must follow, but nothing
1584    /// durable should key off it. Defaults to [`Binding::write`]: a plain signal has no
1585    /// notion of "durable", and a degraded backend that never commits stays correct.
1586    fn write_preview(&self, v: T) {
1587        self.write(v);
1588    }
1589    /// The settled value that ends a gesture (`Event::ValueCommitted`). Defaults to
1590    /// [`Binding::write`]; a day-model field seals its preview session here: one change
1591    /// record, one undo unit, one UPDATE for the whole drag.
1592    fn write_commit(&self, v: T) {
1593        self.write(v);
1594    }
1595    /// Seal the last preview when its control is disposed. Persistent bindings default to
1596    /// committing; scope-owned signals have already received the preview and may be gone.
1597    fn write_teardown(&self, v: T) {
1598        self.write_commit(v);
1599    }
1600    /// Close an open preview session without recording it: the app wrote a value of its own over
1601    /// what the gesture previewed (a text field's text replaced while being typed in), and that
1602    /// write recorded its own change. The next preview starts a fresh session whose prior is
1603    /// the app's value. Defaults to nothing: a plain signal keeps no session.
1604    fn end_preview(&self) {}
1605}
1606
1607impl<T: Clone + 'static> Binding<T> for Signal<T> {
1608    fn read(&self) -> T {
1609        self.get()
1610    }
1611    fn peek(&self) -> T {
1612        self.get_untracked()
1613    }
1614    fn write(&self, v: T) {
1615        self.set(v);
1616    }
1617    fn write_teardown(&self, _v: T) {}
1618}
1619
1620/// The object-safe half of [`Binding`], behind [`AnyBinding`]. Its methods carry an `erased_`
1621/// prefix so a call on a `Signal` inside this crate never sees two candidates named `read`.
1622trait ErasedBinding<T: 'static> {
1623    fn erased_read(&self) -> T;
1624    fn erased_peek(&self) -> T;
1625    fn erased_write(&self, v: T);
1626    fn erased_write_preview(&self, v: T);
1627    fn erased_write_commit(&self, v: T);
1628    fn erased_write_teardown(&self, v: T);
1629    fn erased_end_preview(&self);
1630}
1631
1632impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1633    fn erased_read(&self) -> T {
1634        Binding::read(self)
1635    }
1636    fn erased_peek(&self) -> T {
1637        Binding::peek(self)
1638    }
1639    fn erased_write(&self, v: T) {
1640        Binding::write(self, v);
1641    }
1642    fn erased_write_preview(&self, v: T) {
1643        Binding::write_preview(self, v);
1644    }
1645    fn erased_write_commit(&self, v: T) {
1646        Binding::write_commit(self, v);
1647    }
1648    fn erased_write_teardown(&self, v: T) {
1649        Binding::write_teardown(self, v);
1650    }
1651    fn erased_end_preview(&self) {
1652        Binding::end_preview(self);
1653    }
1654}
1655
1656/// A type-erased [`Binding`]: what a piece stores when its builder takes `impl Binding<T>`
1657/// (docs/api-style.md "Three input spellings"), so the piece itself needs no type parameter
1658/// per bound value.
1659///
1660/// `Copy`, like [`Signal`], so it captures into closures the same way: the erased binding lives
1661/// in a slot owned by the reactive scope that created it, which is the scope building the
1662/// piece. Reads and writes forward to the binding it wraps, preview and commit included.
1663pub struct AnyBinding<T: 'static> {
1664    slot: Signal<Rc<dyn ErasedBinding<T>>>,
1665}
1666
1667impl<T: 'static> Clone for AnyBinding<T> {
1668    fn clone(&self) -> Self {
1669        *self
1670    }
1671}
1672impl<T: 'static> Copy for AnyBinding<T> {}
1673
1674impl<T: 'static> AnyBinding<T> {
1675    /// Erase `binding`. Call it where the piece is built: the slot belongs to the current scope.
1676    pub fn new(binding: impl Binding<T>) -> Self {
1677        let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1678        AnyBinding {
1679            slot: Signal::new(erased),
1680        }
1681    }
1682    fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1683        self.slot.get_untracked()
1684    }
1685    /// Tracked read.
1686    #[must_use]
1687    pub fn get(self) -> T {
1688        self.inner().erased_read()
1689    }
1690    /// Tracked read, or `None` once the scope that created the binding is disposed.
1691    #[must_use]
1692    pub fn try_get(self) -> Option<T> {
1693        self.slot.try_get().map(|b| b.erased_read())
1694    }
1695    /// Untracked read.
1696    #[must_use]
1697    pub fn get_untracked(self) -> T {
1698        self.inner().erased_peek()
1699    }
1700    /// Tracked read through a projection.
1701    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1702        let v = self.inner().erased_read();
1703        f(&v)
1704    }
1705    /// Write, waking whatever tracks the binding.
1706    pub fn set(self, v: T) {
1707        self.inner().erased_write(v);
1708    }
1709    /// Write only when the value differs from the current one.
1710    pub fn set_if_changed(self, v: T)
1711    where
1712        T: PartialEq,
1713    {
1714        let b = self.inner();
1715        if b.erased_peek() != v {
1716            b.erased_write(v);
1717        }
1718    }
1719    /// Read the current value, let `f` change it, write it back.
1720    pub fn update(self, f: impl FnOnce(&mut T)) {
1721        let b = self.inner();
1722        let mut v = b.erased_peek();
1723        f(&mut v);
1724        b.erased_write(v);
1725    }
1726}
1727
1728impl<T: 'static> Binding<T> for AnyBinding<T> {
1729    fn read(&self) -> T {
1730        self.inner().erased_read()
1731    }
1732    fn peek(&self) -> T {
1733        self.inner().erased_peek()
1734    }
1735    fn write(&self, v: T) {
1736        self.inner().erased_write(v);
1737    }
1738    fn write_preview(&self, v: T) {
1739        self.inner().erased_write_preview(v);
1740    }
1741    fn write_commit(&self, v: T) {
1742        self.inner().erased_write_commit(v);
1743    }
1744    fn write_teardown(&self, v: T) {
1745        self.inner().erased_write_teardown(v);
1746    }
1747    fn end_preview(&self) {
1748        self.inner().erased_end_preview();
1749    }
1750}
1751
1752// ---------------------------------------------------------------------------
1753// Async data loading: Load + Resource (§4.5, docs/async.md)
1754// ---------------------------------------------------------------------------
1755
1756/// The lifecycle of an async-loaded value. `Failed` carries the fetcher's error as a shared
1757/// trait object so `Load` stays `Clone` for signal reads.
1758#[derive(Clone)]
1759pub enum Load<T> {
1760    Loading,
1761    Ready(T),
1762    Failed(Arc<dyn std::error::Error + Send + Sync>),
1763}
1764
1765impl<T> Load<T> {
1766    /// The loaded value, if ready.
1767    pub fn ready(&self) -> Option<&T> {
1768        match self {
1769            Load::Ready(v) => Some(v),
1770            _ => None,
1771        }
1772    }
1773    pub fn is_loading(&self) -> bool {
1774        matches!(self, Load::Loading)
1775    }
1776    pub fn is_ready(&self) -> bool {
1777        matches!(self, Load::Ready(_))
1778    }
1779    /// The failure, if the last fetch failed.
1780    pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1781        match self {
1782            Load::Failed(e) => Some(e.as_ref()),
1783            _ => None,
1784        }
1785    }
1786}
1787
1788impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1789    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1790        match self {
1791            Load::Loading => write!(f, "Loading"),
1792            Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1793            Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1794        }
1795    }
1796}
1797
1798/// Latest-wins bookkeeping shared by a Resource's reaction, its spawned futures, and disposal.
1799struct FetchState {
1800    generation: Cell<u64>,
1801    abort: RefCell<Option<Box<dyn FnOnce()>>>,
1802}
1803
1804impl FetchState {
1805    /// Invalidate the in-flight fetch: bump the generation first (so a completion that cannot
1806    /// be aborted still fails its check), then take-and-call the abort outside the borrow
1807    /// (dropping a future can re-enter reactive state).
1808    fn supersede(&self) -> u64 {
1809        let next = self.generation.get() + 1;
1810        self.generation.set(next);
1811        let old = self.abort.borrow_mut().take();
1812        if let Some(abort) = old {
1813            abort();
1814        }
1815        next
1816    }
1817}
1818
1819/// Declarative async data loading (§4.5): a tracked `source` whose value feeds an async
1820/// `fetcher`; the result lands in a `Signal<Load<T>>`. The source re-runs when its tracked
1821/// reads change; an unchanged source value refetches nothing, [`Resource::refetch`] always
1822/// does. Latest wins: a source change supersedes the in-flight fetch (aborting its task;
1823/// dropping any `FetchFuture` inside cancels the platform request) and a stale completion
1824/// writes nothing. Scope disposal aborts the in-flight fetch the same way.
1825///
1826/// ```ignore
1827/// let stations = Resource::new(
1828///     move || region.get(),                              // tracked: refetch on change
1829///     |region| async move { fetch_stations(region).await },
1830/// );
1831/// when(move || stations.ready(), move || station_list(stations));
1832/// ```
1833pub struct Resource<T: 'static> {
1834    state: Signal<Load<T>>,
1835    refetch_count: Signal<u64>,
1836    _not_send: PhantomData<*const T>,
1837}
1838
1839impl<T> Clone for Resource<T> {
1840    fn clone(&self) -> Self {
1841        *self
1842    }
1843}
1844impl<T> Copy for Resource<T> {}
1845
1846impl<T: 'static> Resource<T> {
1847    /// Start loading: `source` runs tracked (its signal reads become dependencies) and its
1848    /// value moves into `fetcher`'s future, which runs on the main-loop executor via the
1849    /// installed spawner, so no `Send` bound anywhere, and the future may read/write signals
1850    /// after its awaits. Infallible fetchers use `E = std::convert::Infallible`.
1851    #[track_caller]
1852    pub fn new<S, Fut, E>(
1853        source: impl Fn() -> S + 'static,
1854        fetcher: impl Fn(S) -> Fut + 'static,
1855    ) -> Resource<T>
1856    where
1857        S: Clone + PartialEq + 'static,
1858        Fut: Future<Output = Result<T, E>> + 'static,
1859        E: std::error::Error + Send + Sync + 'static,
1860    {
1861        let state: Signal<Load<T>> = Signal::new(Load::Loading);
1862        let refetch_count: Signal<u64> = Signal::new(0);
1863        let fs = Rc::new(FetchState {
1864            generation: Cell::new(0),
1865            abort: RefCell::new(None),
1866        });
1867        let reaction_fs = fs.clone();
1868        let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
1869        create_reaction(
1870            Rc::new(move || {
1871                // Tracked reads first: the refetch counter and the source. Everything else runs
1872                // untracked: the fetcher may read signals without making them dependencies.
1873                let count = refetch_count.get();
1874                let s = source();
1875                let fs = reaction_fs.clone();
1876                untrack(|| {
1877                    // Equality gate on (source value, refetch count): a rerun caused by an
1878                    // unrelated tracked read refetches nothing; refetch() always changes the
1879                    // pair, so it always fetches.
1880                    let same = prev
1881                        .borrow()
1882                        .as_ref()
1883                        .is_some_and(|(ps, pc)| ps == &s && *pc == count);
1884                    if same {
1885                        return;
1886                    }
1887                    *prev.borrow_mut() = Some((s.clone(), count));
1888                    let my_generation = fs.supersede();
1889                    state.set(Load::Loading);
1890                    let fut = fetcher(s);
1891                    let done = fs.clone();
1892                    let abort = spawn_local(Box::pin(async move {
1893                        let result = fut.await;
1894                        if done.generation.get() != my_generation {
1895                            return; // superseded while in flight; latest wins
1896                        }
1897                        done.abort.borrow_mut().take(); // completed: the stored abort is dead
1898                        match result {
1899                            Ok(v) => state.set(Load::Ready(v)),
1900                            Err(e) => state.set(Load::Failed(Arc::new(e))),
1901                        }
1902                    }));
1903                    // Eager-poll ordering: the spawner polls once before returning, so a
1904                    // synchronously-ready fetcher has already completed here; storing its
1905                    // abort is harmless only because the spawner contract makes aborting a
1906                    // finished task a no-op (this line is why that contract exists).
1907                    *fs.abort.borrow_mut() = Some(abort);
1908                });
1909            }),
1910            1,
1911        );
1912        // Disposal: supersede + abort the in-flight task. (A completion that slipped through
1913        // would write to disposed signals, the defined no-op, but aborting frees the platform
1914        // request immediately.)
1915        let cleanup_fs = fs;
1916        Scope::current().on_cleanup(move || {
1917            cleanup_fs.supersede();
1918        });
1919        Resource {
1920            state,
1921            refetch_count,
1922            _not_send: PhantomData,
1923        }
1924    }
1925
1926    /// The underlying state signal (tracked reads, `when(move || …)` guards, `each` sources).
1927    #[must_use]
1928    pub fn signal(self) -> Signal<Load<T>> {
1929        self.state
1930    }
1931
1932    /// The current load state (tracked).
1933    #[must_use]
1934    pub fn get(self) -> Load<T>
1935    where
1936        T: Clone,
1937    {
1938        self.state.get()
1939    }
1940
1941    /// Read the current load state by reference (tracked).
1942    pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
1943        self.state.with(f)
1944    }
1945
1946    /// Whether a fetch is in flight (tracked).
1947    pub fn loading(self) -> bool {
1948        self.with(Load::is_loading)
1949    }
1950
1951    /// Whether a value is ready (tracked): `when(move || r.ready(), …)`.
1952    pub fn ready(self) -> bool {
1953        self.with(Load::is_ready)
1954    }
1955
1956    /// Force a refetch with the current source value (even if unchanged).
1957    pub fn refetch(self) {
1958        self.refetch_count.update(|c| *c = c.wrapping_add(1));
1959    }
1960}
1961
1962// ---------------------------------------------------------------------------
1963// Tests
1964// ---------------------------------------------------------------------------
1965
1966#[cfg(test)]
1967mod tests {
1968    use super::*;
1969    use std::cell::Cell as StdCell;
1970    use std::rc::Rc;
1971
1972    fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
1973        let c = Rc::new(StdCell::new(0));
1974        let c2 = c.clone();
1975        (c, move || c2.set(c2.get() + 1))
1976    }
1977
1978    #[test]
1979    fn signal_get_set() {
1980        let s = Signal::new(1);
1981        assert_eq!(s.get(), 1);
1982        s.set(5);
1983        assert_eq!(s.get(), 5);
1984        s.update(|v| *v += 1);
1985        assert_eq!(s.get(), 6);
1986    }
1987
1988    #[test]
1989    fn signal_teardown_does_not_write_after_scope_disposal() {
1990        let scope = Scope::child();
1991        let warned = with_rt(|rt| rt.warned_writes.len());
1992        scope.enter(|| {
1993            let signal = Signal::new(String::new());
1994            signal.write_preview("Fixture final edit".into());
1995            assert_eq!(signal.peek(), "Fixture final edit");
1996            Scope::current().on_cleanup(move || {
1997                signal.write_teardown("Fixture final edit".into());
1998            });
1999        });
2000        scope.dispose();
2001        assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
2002    }
2003
2004    #[test]
2005    fn persistent_binding_teardown_seals_preview() {
2006        #[derive(Clone)]
2007        struct FixtureBinding(Rc<RefCell<Vec<String>>>);
2008        impl Binding<String> for FixtureBinding {
2009            fn read(&self) -> String {
2010                String::new()
2011            }
2012            fn peek(&self) -> String {
2013                self.read()
2014            }
2015            fn write(&self, value: String) {
2016                self.0.borrow_mut().push(value);
2017            }
2018            fn write_preview(&self, _value: String) {}
2019        }
2020        let committed = Rc::new(RefCell::new(Vec::new()));
2021        let binding = FixtureBinding(committed.clone());
2022        let scope = Scope::child();
2023        scope.enter(|| {
2024            binding.write_preview("Fixture edit".into());
2025            Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2026        });
2027        assert!(committed.borrow().is_empty());
2028        scope.dispose();
2029        assert_eq!(*committed.borrow(), ["Fixture edit"]);
2030    }
2031
2032    #[test]
2033    fn effect_reruns_on_change() {
2034        let s = Signal::new(1);
2035        let (count, bump) = counter();
2036        Effect::new(move || {
2037            s.track();
2038            bump();
2039        });
2040        assert_eq!(count.get(), 1); // initial run
2041        batch(|| s.set(2));
2042        assert_eq!(count.get(), 2);
2043        batch(|| s.set(3));
2044        assert_eq!(count.get(), 3);
2045    }
2046
2047    #[test]
2048    fn batch_coalesces() {
2049        let s = Signal::new(0);
2050        let (count, bump) = counter();
2051        Effect::new(move || {
2052            s.track();
2053            bump();
2054        });
2055        batch(|| {
2056            s.set(1);
2057            s.set(2);
2058            s.set(3);
2059        });
2060        assert_eq!(count.get(), 2); // initial + one drain
2061        assert_eq!(s.get(), 3);
2062    }
2063
2064    #[test]
2065    fn set_if_changed_no_op() {
2066        let s = Signal::new(7);
2067        let (count, bump) = counter();
2068        Effect::new(move || {
2069            s.track();
2070            bump();
2071        });
2072        batch(|| s.set_if_changed(7));
2073        assert_eq!(count.get(), 1); // no re-run
2074    }
2075
2076    #[test]
2077    fn memo_caches_and_diffs() {
2078        let s = Signal::new(1);
2079        let computes = Rc::new(StdCell::new(0));
2080        let c2 = computes.clone();
2081        let doubled = Memo::new(move || {
2082            c2.set(c2.get() + 1);
2083            s.get() * 2
2084        });
2085        assert_eq!(doubled.get(), 2);
2086        assert_eq!(doubled.get(), 2);
2087        assert_eq!(computes.get(), 1); // cached
2088        let (effect_runs, bump) = counter();
2089        Effect::new(move || {
2090            let _ = doubled.get();
2091            bump();
2092        });
2093        assert_eq!(effect_runs.get(), 1);
2094        batch(|| s.set(1)); // same value → memo recomputes? signal changed, memo recomputes, same output
2095        // memo output unchanged (1*2 == 2)? s was already 1 → set(1) marks dirty (set is not diffed)
2096        assert_eq!(effect_runs.get(), 1); // memo diffing gates the effect
2097        batch(|| s.set(5));
2098        assert_eq!(doubled.get(), 10);
2099        assert_eq!(effect_runs.get(), 2);
2100    }
2101
2102    #[test]
2103    fn bind_applies_on_change_only() {
2104        let s = Signal::new(1);
2105        let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2106        let a2 = applied.clone();
2107        bind(
2108            move || s.get().to_string(),
2109            move |v| a2.borrow_mut().push(v.clone()),
2110        );
2111        assert_eq!(*applied.borrow(), vec!["1"]);
2112        batch(|| s.set(2));
2113        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2114        batch(|| s.update(|v| *v = 2)); // update always marks; bind's eq gate stops the apply
2115        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2116    }
2117
2118    #[test]
2119    fn watch_skips_initial_and_passes_old() {
2120        type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2121        let s = Signal::new(10);
2122        let log: Log = Rc::new(RefCell::new(Vec::new()));
2123        let l2 = log.clone();
2124        watch(
2125            move || s.get(),
2126            move |new, old| l2.borrow_mut().push((*new, old.copied())),
2127        );
2128        assert!(log.borrow().is_empty());
2129        batch(|| s.set(11));
2130        assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2131    }
2132
2133    #[test]
2134    fn scope_dispose_stops_effects_and_write_is_noop() {
2135        let s = Signal::new(0);
2136        let (count, bump) = counter();
2137        let scope = Scope::child();
2138        let inner = scope.enter(|| {
2139            let inner = Signal::new(1);
2140            Effect::new(move || {
2141                s.track();
2142                bump();
2143            });
2144            inner
2145        });
2146        assert_eq!(count.get(), 1);
2147        batch(|| s.set(1));
2148        assert_eq!(count.get(), 2);
2149        scope.dispose();
2150        batch(|| s.set(2));
2151        assert_eq!(count.get(), 2); // effect gone
2152        inner.set(9); // silent no-op
2153        assert_eq!(inner.try_get(), None);
2154    }
2155
2156    #[test]
2157    fn dispose_during_drain_skips_pending() {
2158        let s = Signal::new(0);
2159        let scope = Scope::child();
2160        let (count, bump) = counter();
2161        // Owner effect (created first in outer scope) disposes the child scope when s becomes 1.
2162        let scope_cell = Rc::new(StdCell::new(Some(scope)));
2163        let sc = scope_cell.clone();
2164        Effect::new(move || {
2165            if s.get() == 1
2166                && let Some(scope) = sc.take()
2167            {
2168                scope.dispose();
2169            }
2170        });
2171        scope.enter(|| {
2172            Effect::new(move || {
2173                s.track();
2174                bump();
2175            });
2176        });
2177        assert_eq!(count.get(), 1);
2178        batch(|| s.set(1));
2179        // Owner ran first (created earlier, same depth? owner depth 0 < child depth 1) and
2180        // disposed the child → child effect must not run again.
2181        assert_eq!(count.get(), 1);
2182    }
2183
2184    #[test]
2185    fn fixpoint_extends_drain() {
2186        let a = Signal::new(0);
2187        let b = Signal::new(0);
2188        let (count, bump) = counter();
2189        Effect::new(move || {
2190            if a.get() == 1 {
2191                b.set(1); // write during drain extends the drain
2192            }
2193        });
2194        Effect::new(move || {
2195            b.track();
2196            bump();
2197        });
2198        assert_eq!(count.get(), 1);
2199        batch(|| a.set(1));
2200        assert_eq!(count.get(), 2);
2201        assert_eq!(b.get(), 1);
2202    }
2203
2204    // Debug-only: release warns-and-defers instead of panicking (the release
2205    // side is pinned by `unwind_safety_tests::rerun_cap_defers_instead_of_killing_the_binding`).
2206    #[cfg(debug_assertions)]
2207    #[test]
2208    #[should_panic(expected = "re-ran more than")]
2209    fn rerun_cap_panics_in_debug() {
2210        let s = Signal::new(0);
2211        Effect::new(move || {
2212            let v = s.get();
2213            s.set(v + 1); // classic cycle
2214        });
2215        batch(|| s.set(1));
2216    }
2217
2218    #[test]
2219    fn context_provides_down() {
2220        #[derive(Clone, PartialEq, Debug)]
2221        struct Theme(u32);
2222        let scope = Scope::child();
2223        scope.provide(Theme(7));
2224        let child = scope.create_child();
2225        assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2226        scope.dispose();
2227    }
2228
2229    #[test]
2230    fn trigger_notifies() {
2231        let t = Trigger::new();
2232        let (count, bump) = counter();
2233        Effect::new(move || {
2234            t.track();
2235            bump();
2236        });
2237        batch(|| t.notify());
2238        assert_eq!(count.get(), 2);
2239    }
2240
2241    #[test]
2242    fn turn_end_runs_after_fixpoint() {
2243        let s = Signal::new(0);
2244        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2245        let o1 = order.clone();
2246        Effect::new(move || {
2247            s.track();
2248            o1.borrow_mut().push("effect");
2249        });
2250        let o2 = order.clone();
2251        on_turn_end(move || o2.borrow_mut().push("turn-end"));
2252        order.borrow_mut().clear();
2253        batch(|| s.set(1));
2254        assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2255    }
2256
2257    #[test]
2258    fn at_turn_end_waits_for_the_turn_and_runs_once() {
2259        let s = Signal::new(0);
2260        let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2261        // Outside a turn: now.
2262        let o = order.clone();
2263        at_turn_end(move || o.borrow_mut().push("now".into()));
2264        assert_eq!(*order.borrow(), vec!["now".to_string()]);
2265        order.borrow_mut().clear();
2266        // Inside a batch: after the drain, and before the standing hooks.
2267        let o1 = order.clone();
2268        Effect::new(move || {
2269            let v = s.get();
2270            o1.borrow_mut().push(format!("effect {v}"));
2271        });
2272        let o2 = order.clone();
2273        on_turn_end(move || o2.borrow_mut().push("standing".into()));
2274        order.borrow_mut().clear();
2275        let o3 = order.clone();
2276        batch(|| {
2277            at_turn_end(move || o3.borrow_mut().push("once".into()));
2278            s.set(1);
2279        });
2280        assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2281        // A batch with no reactive work still ends its turn for a deferred callback.
2282        order.borrow_mut().clear();
2283        let o4 = order.clone();
2284        batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2285        assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2286    }
2287
2288    #[test]
2289    fn bindings_run_before_effects() {
2290        let s = Signal::new(0);
2291        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2292        let o1 = order.clone();
2293        // Plain effect created first (lower seq); priority must still put the bind first.
2294        Effect::new(move || {
2295            s.track();
2296            o1.borrow_mut().push("effect");
2297        });
2298        let o2 = order.clone();
2299        bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2300        order.borrow_mut().clear();
2301        batch(|| s.set(1));
2302        assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2303    }
2304}
2305
2306#[cfg(test)]
2307mod resource_tests {
2308    use super::*;
2309    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2310
2311    // ---- test executor: mirrors day::task's shape (eager first poll; abort = remove+drop;
2312    // pump() re-polls whatever is still pending). `ABORTED` records aborts of still-pending
2313    // tasks, the probe the latest-wins/disposal tests read. All thread-local: each #[test]
2314    // thread gets a fresh Runtime and a fresh executor.
2315
2316    thread_local! {
2317        static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2318            const { RefCell::new(Vec::new()) };
2319        static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2320        static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2321        static INSTALLED: Cell<bool> = const { Cell::new(false) };
2322    }
2323
2324    fn noop_waker() -> Waker {
2325        fn raw() -> RawWaker {
2326            RawWaker::new(std::ptr::null(), &VT)
2327        }
2328        static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2329        // SAFETY: every vtable entry ignores the data pointer.
2330        unsafe { Waker::from_raw(raw()) }
2331    }
2332
2333    fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2334        let waker = noop_waker();
2335        let mut cx = Context::from_waker(&waker);
2336        fut.as_mut().poll(&mut cx).is_ready()
2337    }
2338
2339    fn install_test_spawner() {
2340        if INSTALLED.with(|c| c.replace(true)) {
2341            return;
2342        }
2343        install_spawner(|mut fut| {
2344            let id = NEXT_ID.with(|c| {
2345                let v = c.get();
2346                c.set(v + 1);
2347                v
2348            });
2349            if !poll_one(&mut fut) {
2350                TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2351            }
2352            Box::new(move || {
2353                let removed = TEST_TASKS.with(|t| {
2354                    let mut t = t.borrow_mut();
2355                    let before = t.len();
2356                    t.retain(|(i, _)| *i != id);
2357                    before != t.len()
2358                });
2359                if removed {
2360                    ABORTED.with(|a| a.borrow_mut().push(id));
2361                }
2362            })
2363        });
2364    }
2365
2366    fn aborted_count() -> usize {
2367        ABORTED.with(|a| a.borrow().len())
2368    }
2369
2370    /// Re-poll every pending task once (completions drop out).
2371    fn pump() {
2372        let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2373        for id in ids {
2374            let fut = TEST_TASKS.with(|t| {
2375                t.borrow_mut()
2376                    .iter_mut()
2377                    .find(|(i, _)| *i == id)
2378                    .and_then(|(_, s)| s.take())
2379            });
2380            let Some(mut fut) = fut else { continue };
2381            if poll_one(&mut fut) {
2382                TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2383            } else {
2384                TEST_TASKS.with(|t| {
2385                    if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2386                        *s = Some(fut);
2387                    }
2388                });
2389            }
2390        }
2391        // Completions wrote signals; with no scheduler installed a test must drain explicitly
2392        // (the production main loop drains via the installed scheduler).
2393        flush_sync();
2394    }
2395
2396    type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2397
2398    /// A future the test resolves by hand (fill the slot, then `pump()`); no waker wiring, since
2399    /// pump re-polls everything.
2400    fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2401        std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2402            Some(r) => Poll::Ready(r),
2403            None => Poll::Pending,
2404        })
2405    }
2406
2407    #[derive(Debug)]
2408    struct TestErr(&'static str);
2409    impl std::fmt::Display for TestErr {
2410        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2411            write!(f, "{}", self.0)
2412        }
2413    }
2414    impl std::error::Error for TestErr {}
2415
2416    #[test]
2417    fn resource_sync_fetcher_is_ready_immediately() {
2418        install_test_spawner();
2419        let r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(42) });
2420        assert!(r.ready());
2421        assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2422    }
2423
2424    #[test]
2425    fn resource_loading_then_ready() {
2426        install_test_spawner();
2427        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2428        let s2 = slot.clone();
2429        let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2430        assert!(r.loading());
2431        *slot.borrow_mut() = Some(Ok(7));
2432        pump();
2433        assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2434    }
2435
2436    #[test]
2437    fn resource_failed_preserves_error() {
2438        install_test_spawner();
2439        let r = Resource::new(|| (), |()| async { Err::<i32, _>(TestErr("boom")) });
2440        assert!(!r.ready());
2441        assert_eq!(
2442            r.with(|l| l.error().map(std::string::ToString::to_string)),
2443            Some("boom".into())
2444        );
2445    }
2446
2447    #[test]
2448    fn resource_refetches_on_source_change() {
2449        install_test_spawner();
2450        let src = Signal::new(1i32);
2451        let fetches = Rc::new(Cell::new(0));
2452        let f = fetches.clone();
2453        let r = Resource::new(
2454            move || src.get(),
2455            move |v| {
2456                f.set(f.get() + 1);
2457                async move { Ok::<_, TestErr>(v * 10) }
2458            },
2459        );
2460        assert_eq!(fetches.get(), 1);
2461        assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2462        batch(|| src.set(2));
2463        assert_eq!(fetches.get(), 2);
2464        assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2465    }
2466
2467    #[test]
2468    fn resource_source_equality_gates() {
2469        install_test_spawner();
2470        let a = Signal::new(1i32);
2471        let b = Signal::new(10i32);
2472        let fetches = Rc::new(Cell::new(0));
2473        let f = fetches.clone();
2474        let r = Resource::new(
2475            move || {
2476                let _ = b.get(); // tracked but not part of the source value
2477                a.get()
2478            },
2479            move |v| {
2480                f.set(f.get() + 1);
2481                async move { Ok::<_, TestErr>(v) }
2482            },
2483        );
2484        assert_eq!(fetches.get(), 1);
2485        batch(|| b.set(20)); // reruns the reaction; the source value is unchanged → no refetch
2486        assert_eq!(fetches.get(), 1);
2487        assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2488        batch(|| a.set(2)); // the value changed → refetch
2489        assert_eq!(fetches.get(), 2);
2490    }
2491
2492    #[test]
2493    fn resource_refetch_forces() {
2494        install_test_spawner();
2495        let fetches = Rc::new(Cell::new(0));
2496        let f = fetches.clone();
2497        let r = Resource::new(
2498            || (),
2499            move |()| {
2500                f.set(f.get() + 1);
2501                async { Ok::<_, TestErr>(0) }
2502            },
2503        );
2504        assert_eq!(fetches.get(), 1);
2505        batch(|| r.refetch()); // same source value; the refetch counter forces it past the gate
2506        assert_eq!(fetches.get(), 2);
2507    }
2508
2509    #[test]
2510    fn resource_latest_wins() {
2511        install_test_spawner();
2512        let src = Signal::new(1i32);
2513        let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2514        let sl = slots.clone();
2515        let r = Resource::new(
2516            move || src.get(),
2517            move |_| {
2518                let slot: Slot<i32> = Rc::new(RefCell::new(None));
2519                sl.borrow_mut().push(slot.clone());
2520                manual_future(slot)
2521            },
2522        );
2523        assert!(r.loading());
2524        let before = aborted_count();
2525        batch(|| src.set(2)); // supersede generation 1 while it is in flight
2526        assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2527        // Resolving generation 1 anyway must change nothing (its future is gone).
2528        *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2529        pump();
2530        assert!(r.loading(), "a stale result writes nothing");
2531        *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2532        pump();
2533        assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2534    }
2535
2536    #[test]
2537    fn resource_scope_disposal_aborts() {
2538        install_test_spawner();
2539        let scope = Scope::child();
2540        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2541        let s2 = slot.clone();
2542        let r = scope.enter(|| Resource::new(move || (), move |()| manual_future(s2.clone())));
2543        assert!(r.loading());
2544        let before = aborted_count();
2545        scope.dispose();
2546        assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2547        // Resolving afterwards is inert: the future is gone; nothing pends; no panic.
2548        *slot.borrow_mut() = Some(Ok(1));
2549        pump();
2550    }
2551
2552    #[test]
2553    fn resource_ready_is_tracked() {
2554        install_test_spawner();
2555        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2556        let s2 = slot.clone();
2557        let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2558        let runs = Rc::new(Cell::new(0));
2559        let rn = runs.clone();
2560        Effect::new(move || {
2561            let _ = r.ready();
2562            rn.set(rn.get() + 1);
2563        });
2564        assert_eq!(runs.get(), 1);
2565        *slot.borrow_mut() = Some(Ok(1));
2566        pump();
2567        assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2568    }
2569
2570    #[test]
2571    #[should_panic(expected = "no spawner installed")]
2572    fn spawner_missing_panics() {
2573        // No test spawner installed: this test thread's Runtime has none.
2574        let _r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(1) });
2575    }
2576}
2577
2578#[cfg(test)]
2579mod unwind_safety_tests {
2580    use super::*;
2581
2582    /// Run `f`, swallowing a panic, with the panic hook silenced so the test output stays clean.
2583    fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2584        let prev = std::panic::take_hook();
2585        std::panic::set_hook(Box::new(|_| {}));
2586        let r = std::panic::catch_unwind(f);
2587        std::panic::set_hook(prev);
2588        assert!(r.is_err(), "expected the closure to panic");
2589    }
2590
2591    /// A panic inside `Scope::enter` must not leave the runtime parented to the transient scope.
2592    /// Before the guard, every later `Signal::new` landed in a disposed scope and its first read
2593    /// panicked with a misleading "read of disposed Signal".
2594    #[test]
2595    fn panic_in_scope_enter_restores_current_scope() {
2596        let before = with_rt(|rt| rt.current_scope);
2597        let scope = Scope::detached();
2598        contained(|| scope.enter(|| panic!("boom in enter")));
2599        assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2600        // The real symptom: a signal created afterwards must still be alive and readable.
2601        let s = Signal::new(7u32);
2602        assert_eq!(s.get(), 7);
2603    }
2604
2605    /// A panic inside `untrack` must pop its `None` observer, or dependency tracking stays off
2606    /// for the rest of the process and nothing ever updates again.
2607    /// A panic inside an effect's own closure (contained by a backend trampoline) must pop
2608    /// the effect's observer frame during unwind; a stranded frame would attribute every
2609    /// later read to the dead run, even through a user's own `catch_unwind`, without any
2610    /// call to `recover_from_panic`.
2611    #[test]
2612    fn panic_in_effect_body_pops_its_observer_frame() {
2613        let depth = with_rt(|rt| rt.observers.len());
2614        let boom = Signal::new(false);
2615        Effect::new(move || {
2616            assert!(!boom.get(), "effect boom");
2617        });
2618        assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2619        contained(|| batch(|| boom.set(true)));
2620        assert_eq!(
2621            with_rt(|rt| rt.observers.len()),
2622            depth,
2623            "observer frame stranded by the panicking effect run"
2624        );
2625        recover_from_panic(); // clear draining/pending for the tests that follow
2626    }
2627
2628    #[test]
2629    fn panic_in_untrack_restores_tracking() {
2630        let depth = with_rt(|rt| rt.observers.len());
2631        contained(|| untrack(|| panic!("boom in untrack")));
2632        assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2633
2634        // Tracking still works: an effect re-runs when its source changes.
2635        let src = Signal::new(0i32);
2636        let runs = Rc::new(RefCell::new(0));
2637        let r2 = runs.clone();
2638        Effect::new(move || {
2639            let _ = src.get();
2640            *r2.borrow_mut() += 1;
2641        });
2642        flush_sync();
2643        let before = *runs.borrow();
2644        src.set(1);
2645        flush_sync();
2646        assert!(
2647            *runs.borrow() > before,
2648            "effect did not re-run — tracking is off"
2649        );
2650    }
2651
2652    /// A panic inside `batch` must not strand `batch_depth`, which would stop every later write
2653    /// from scheduling a drain.
2654    #[test]
2655    fn panic_in_batch_restores_depth() {
2656        let depth = with_rt(|rt| rt.batch_depth);
2657        contained(|| batch(|| panic!("boom in batch")));
2658        assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2659    }
2660
2661    /// A panic inside a `with` closure must not consume the signal's value. Before the value was
2662    /// shared it was taken out for the closure's duration, so an unwind lost it permanently and
2663    /// the signal was dead for the rest of the process.
2664    #[test]
2665    fn panic_in_with_leaves_the_value_intact() {
2666        let s = Signal::new(String::from("intact"));
2667        contained(|| s.with(|_| panic!("boom in with")));
2668        assert_eq!(s.with(std::clone::Clone::clone), "intact");
2669    }
2670
2671    /// Reading a signal from inside its own `with` closure now works. It used to find the hole
2672    /// left by the take and panic with "read of disposed Signal".
2673    #[test]
2674    fn reentrant_read_inside_with_succeeds() {
2675        let s = Signal::new(5u32);
2676        let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2677        assert_eq!(doubled, 10);
2678        assert_eq!(
2679            s.with(|v| *v),
2680            5,
2681            "value still in place after the nested read"
2682        );
2683    }
2684
2685    /// Two different signals read inside one another's closures: the ordinary case, and the
2686    /// reason the closure must run with the runtime borrow released.
2687    #[test]
2688    fn nested_reads_of_distinct_signals_succeed() {
2689        let a = Signal::new(2u32);
2690        let b = Signal::new(3u32);
2691        assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2692    }
2693
2694    /// Writing a signal while a read of it is in flight is reported instead of silently lost.
2695    #[test]
2696    fn write_during_read_panics_with_a_clear_message() {
2697        let s = Signal::new(1u32);
2698        let prev = std::panic::take_hook();
2699        std::panic::set_hook(Box::new(|_| {}));
2700        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2701            s.with(|_| s.set(2));
2702        }));
2703        std::panic::set_hook(prev);
2704        let payload = r.unwrap_err();
2705        // A `panic!` with no format arguments carries a `&'static str`, not a `String`.
2706        let msg = payload
2707            .downcast_ref::<&str>()
2708            .map(std::string::ToString::to_string)
2709            .or_else(|| payload.downcast_ref::<String>().cloned())
2710            .expect("panic payload should be a string");
2711        assert!(
2712            msg.contains("in flight") && msg.contains("Signal"),
2713            "message should name the cause, got: {msg}"
2714        );
2715    }
2716
2717    /// Release builds must survive a reactive cycle: the capped effect is skipped for the
2718    /// rest of the drain but re-arms on the next source write; it must not be permanently
2719    /// disabled. Release-only because the same cycle panics under
2720    /// `debug_assertions`; run via `cargo test --release -p day-reactive`.
2721    #[cfg(not(debug_assertions))]
2722    #[test]
2723    fn rerun_cap_defers_instead_of_killing_the_binding() {
2724        let s = Signal::new(0u32);
2725        let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2726        let r2 = runs.clone();
2727        Effect::new(move || {
2728            let v = s.get();
2729            r2.set(r2.get() + 1);
2730            if v < 1_000_000 {
2731                s.set(v + 1); // self-sustaining cycle: trips the cap every drain
2732            }
2733        });
2734        flush_sync();
2735        let after_cycle = runs.get();
2736        assert!(
2737            after_cycle <= RERUN_CAP + 1,
2738            "cap did not bound the drain: {after_cycle} runs"
2739        );
2740
2741        // A fresh external write must re-arm the effect with a new per-drain budget.
2742        batch(|| s.set(2_000_000)); // past the cycle threshold: the effect runs once, quietly
2743        assert_eq!(
2744            runs.get(),
2745            after_cycle + 1,
2746            "binding stayed dead after hitting the re-run cap"
2747        );
2748    }
2749}
2750
2751#[cfg(test)]
2752mod owner_scope_tests {
2753    use super::*;
2754
2755    #[test]
2756    fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2757        let outer = Scope::child();
2758        outer.provide("outer fixture");
2759        let first = outer.create_child();
2760        let second = outer.create_child();
2761        first.provide("first fixture");
2762        second.provide("second fixture");
2763        let source = Signal::new(0);
2764        let seen = Rc::new(RefCell::new(Vec::new()));
2765        let lazy = first.enter(|| {
2766            Memo::new(move || {
2767                (
2768                    source.get(),
2769                    Scope::current().use_context::<&str>().unwrap(),
2770                )
2771            })
2772        });
2773        let nested = second.enter(|| {
2774            Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2775        });
2776        second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2777        assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2778        for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2779            let seen = seen.clone();
2780            scope.enter(|| {
2781                Effect::new(move || {
2782                    seen.borrow_mut()
2783                        .push((source.get(), Scope::current().use_context::<&str>()));
2784                    assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2785                });
2786            });
2787        }
2788        second.enter(|| {
2789            batch(|| source.set(1));
2790            assert_eq!(
2791                Scope::current().use_context::<&str>(),
2792                Some("second fixture")
2793            );
2794        });
2795        assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2796        assert_eq!(seen.borrow().len(), 4);
2797        outer.dispose();
2798        batch(|| source.set(2));
2799        assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2800    }
2801
2802    #[test]
2803    fn watches_allocate_state_and_cleanup_in_their_owner() {
2804        let owner = Scope::child();
2805        let trigger = Signal::new(0);
2806        let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2807        let cleaned = Rc::new(Cell::new(0));
2808        owner.enter(|| {
2809            let allocated = allocated.clone();
2810            let cleaned = cleaned.clone();
2811            watch(
2812                move || trigger.get(),
2813                move |value, _| {
2814                    allocated.set(Some(Signal::new(*value)));
2815                    let cleaned = cleaned.clone();
2816                    Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2817                },
2818            );
2819        });
2820        batch(|| trigger.set(1));
2821        let state = allocated.get().unwrap();
2822        assert_eq!(state.get(), 1);
2823        owner.dispose();
2824        assert_eq!(cleaned.get(), 1);
2825        assert!(state.try_get().is_none());
2826    }
2827
2828    #[test]
2829    fn panic_in_owned_computations_restores_scope_and_tracking() {
2830        let owner = Scope::child();
2831        owner.provide("owner fixture");
2832        let caller = Scope::child();
2833        caller.provide("caller fixture");
2834        let trigger = Signal::new(false);
2835        let memo = owner.enter(|| {
2836            Memo::new(move || {
2837                assert_eq!(
2838                    Scope::current().use_context::<&str>(),
2839                    Some("owner fixture")
2840                );
2841                assert!(!trigger.get(), "synthetic memo failure");
2842                7
2843            })
2844        });
2845        assert_eq!(memo.get(), 7);
2846        batch(|| trigger.set(true));
2847        caller.enter(|| {
2848            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2849            assert!(result.is_err());
2850            assert_eq!(
2851                Scope::current().use_context::<&str>(),
2852                Some("caller fixture")
2853            );
2854            assert!(with_rt(|rt| rt.observers.is_empty()));
2855        });
2856        owner.dispose();
2857        caller.dispose();
2858    }
2859}