Skip to main content

glory_core/
runtime.rs

1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
4use std::future::Future;
5use std::marker::PhantomData;
6use std::pin::Pin;
7use std::rc::{Rc, Weak};
8use std::time::Duration;
9
10use crate::RuntimeId;
11use crate::arena::{Arena, Key};
12#[path = "dependencies.rs"]
13mod dependencies;
14use dependencies::Dependencies;
15#[path = "subscribers.rs"]
16mod subscribers;
17use glory_render::profile::{Phase, Profile};
18use subscribers::Subscribers;
19#[path = "fields.rs"]
20mod fields;
21#[path = "keyed.rs"]
22mod keyed;
23pub use keyed::{KeyedEntry, KeyedList, ListError, RowToken};
24
25pub type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
26type Cancel = Box<dyn FnOnce()>;
27type Value = Rc<RefCell<Box<dyn Any>>>;
28type Mapper = Rc<dyn Fn() -> Box<dyn Any>>;
29type Equal = Rc<dyn Fn(&dyn Any, &dyn Any) -> bool>;
30type Callback = Rc<RefCell<Box<dyn FnMut()>>>;
31type Shared = Rc<RefCell<State>>;
32const QUEUE_SLACK: usize = 64;
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct HostError(pub String);
36impl std::fmt::Display for HostError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.write_str(&self.0)
39    }
40}
41impl std::error::Error for HostError {}
42
43/// One host owns the event loop. Neither method may synchronously reenter a
44/// runtime; spawn queues a future without polling it before returning. Returned
45/// cancellation must stop/drop that future. No built-in block_on fallback.
46pub trait Host {
47    fn spawn(&self, future: LocalFuture) -> Result<Cancel, HostError>;
48    fn wake(&self);
49    fn now(&self) -> Duration;
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub enum AccessError {
54    RuntimeGone,
55    Disposed,
56    WrongRuntime,
57    Borrowed,
58    TypeMismatch,
59    Cycle,
60    WriteDuringCompute,
61    ReentrantFlush,
62    RunawayEffect,
63    NoHost,
64    Host(HostError),
65    InvalidField(&'static str),
66    MissingField,
67    OutOfBounds,
68    Capacity,
69}
70impl std::fmt::Display for AccessError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        write!(f, "{self:?}")
73    }
74}
75impl std::error::Error for AccessError {}
76
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub struct RuntimeStats {
79    pub source_writes: u64,
80    pub marked: u64,
81    pub validations: u64,
82    pub derived_runs: u64,
83    pub binding_runs: u64,
84    pub structural_runs: u64,
85    pub effect_runs: u64,
86    pub nodes: usize,
87    pub node_slots: usize,
88    pub owners: usize,
89    pub owner_slots: usize,
90    pub instances: usize,
91    pub instance_slots: usize,
92    pub tasks: usize,
93    pub task_slots: usize,
94    pub edges: usize,
95    pub queued: usize,
96    /// Physical FIFO entries, including bounded retired generational identities.
97    pub queue_entries: usize,
98    /// Allocated FIFO capacity; like arena slots it follows peak concurrent work.
99    pub queue_capacity: usize,
100    pub queue_compactions: u64,
101    /// Identities inspected by nonempty compaction, excluding constant-time clear.
102    pub queue_compaction_visits: u64,
103    pub fields: usize,
104    pub field_slots: usize,
105    pub entry_keys: usize,
106    pub entry_buckets: usize,
107    pub field_target_builds: u64,
108    pub field_target_hits: u64,
109    pub field_target_visits: u64,
110    pub field_target_caches: usize,
111    pub field_target_keys: usize,
112}
113
114/// Live graph shape. Kind order: Source, Derived, Structure, Binding, Effect.
115/// Degree bins: 0, 1, 2, 3-4, 5-8, 9-64, 65+. Snapshotting is opt-in;
116/// it performs no user callbacks and adds no persistent per-node counters.
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub struct GraphStats {
119    pub nodes: [usize; 5],
120    pub dependencies: [[usize; 7]; 5],
121    pub subscribers: [[usize; 7]; 5],
122}
123
124#[derive(Clone, Copy, PartialEq, Eq)]
125enum Mode {
126    Pure,
127    Effect,
128}
129#[derive(Clone, Copy, PartialEq, Eq)]
130enum Status {
131    Clean,
132    Check,
133    Dirty,
134    Computing,
135}
136
137#[derive(Clone)]
138enum Compute {
139    Source,
140    Derived {
141        mapper: Mapper,
142        equal: Option<Equal>,
143    },
144    Binding(Callback),
145    Structure(Callback),
146    Effect(Callback),
147}
148
149struct Node {
150    owner: Key,
151    compute: Compute,
152    value: Option<Value>,
153    version: u64,
154    status: Status,
155    rerun: bool,
156    // This node's current invalidation has reached its subscriber frontier.
157    // A validation/new subscription rearms it before any refreshed consumer
158    // could otherwise be hidden behind an already-pending ancestor.
159    propagated: bool,
160    queued: bool,
161    last_flush: u64,
162    flush_runs: u32,
163    dependencies: Dependencies,
164    subscribers: Subscribers,
165}
166
167#[derive(Default)]
168struct OwnerData {
169    parent: Option<Key>,
170    children: BTreeSet<Key>,
171    nodes: BTreeSet<Key>,
172    tasks: BTreeSet<Key>,
173    cleanup: Vec<Cancel>,
174    instance: Option<Key>,
175}
176
177struct Instance {
178    owner: Key,
179    parent: Option<Key>,
180}
181struct TaskState {
182    owner: Key,
183    cancel: Option<Cancel>,
184}
185
186struct State {
187    root: Key,
188    nodes: Arena<Node>,
189    owners: Arena<OwnerData>,
190    instances: Arena<Instance>,
191    tasks: Arena<TaskState>,
192    bindings: VecDeque<Key>,
193    structures: VecDeque<Key>,
194    effects: VecDeque<Key>,
195    queued: usize,
196    queue_retired: usize,
197    flushing: bool,
198    batch_depth: usize,
199    flush_epoch: u64,
200    host: Option<Rc<dyn Host>>,
201    stats: RuntimeStats,
202    profile: Option<Profile>,
203    fields: fields::Fields,
204}
205
206struct Frame {
207    runtime: RuntimeId,
208    key: Key,
209    dependencies: Dependencies,
210}
211thread_local! {
212    // This is only a handle lookup and stack of active evaluations. Every graph,
213    // queue, value, owner and scheduler flag lives in its own Runtime, not here.
214    static RUNTIMES: RefCell<HashMap<RuntimeId, Weak<RefCell<State>>>> = RefCell::new(HashMap::new());
215    static TRACKING: RefCell<Vec<Option<Frame>>> = const { RefCell::new(Vec::new()) };
216    static EVALUATING: RefCell<Vec<Mode>> = const { RefCell::new(Vec::new()) };
217    static CONSTRUCTING: RefCell<Vec<(RuntimeId, Key)>> = const { RefCell::new(Vec::new()) };
218}
219
220fn allow_creation() -> Result<(), AccessError> {
221    if EVALUATING.with_borrow(|stack| stack.last() == Some(&Mode::Pure)) {
222        Err(AccessError::WriteDuringCompute)
223    } else {
224        Ok(())
225    }
226}
227
228fn enter_owner<R>(runtime: RuntimeId, owner: Key, f: impl FnOnce() -> R) -> R {
229    struct Enter(usize);
230    impl Drop for Enter {
231        fn drop(&mut self) {
232            CONSTRUCTING.with_borrow_mut(|stack| stack.truncate(self.0));
233        }
234    }
235    let previous = CONSTRUCTING.with_borrow_mut(|stack| {
236        let len = stack.len();
237        stack.push((runtime, owner));
238        len
239    });
240    let _guard = Enter(previous);
241    f()
242}
243
244fn lookup(runtime: RuntimeId) -> Result<Shared, AccessError> {
245    RUNTIMES
246        .with_borrow(|runtimes| runtimes.get(&runtime).and_then(Weak::upgrade))
247        .ok_or(AccessError::RuntimeGone)
248}
249
250fn check_reader(runtime: RuntimeId) -> Result<(), AccessError> {
251    TRACKING.with_borrow(|stack| {
252        if stack
253            .last()
254            .and_then(Option::as_ref)
255            .is_some_and(|frame| frame.runtime != runtime)
256        {
257            Err(AccessError::WrongRuntime)
258        } else {
259            Ok(())
260        }
261    })
262}
263
264fn track(runtime: RuntimeId, key: Key, version: u64) -> Result<(), AccessError> {
265    TRACKING.with_borrow_mut(|stack| {
266        if let Some(Some(frame)) = stack.last_mut() {
267            if frame.runtime != runtime {
268                return Err(AccessError::WrongRuntime);
269            }
270            frame.dependencies.insert(key, version);
271        }
272        Ok(())
273    })
274}
275
276struct TrackingPause(usize);
277impl Drop for TrackingPause {
278    fn drop(&mut self) {
279        TRACKING.with_borrow_mut(|stack| stack.truncate(self.0));
280    }
281}
282
283/// Suppress only reads in this closure. Derived computations still track their
284/// own dependencies, and purity checks still apply inside untracked code.
285pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
286    let previous = TRACKING.with_borrow_mut(|stack| {
287        let len = stack.len();
288        stack.push(None);
289        len
290    });
291    let _guard = TrackingPause(previous);
292    f()
293}
294
295impl State {
296    fn new() -> Self {
297        let mut owners = Arena::default();
298        let root = owners.insert(OwnerData::default());
299        Self {
300            root,
301            owners,
302            nodes: Arena::default(),
303            instances: Arena::default(),
304            tasks: Arena::default(),
305            bindings: VecDeque::new(),
306            structures: VecDeque::new(),
307            effects: VecDeque::new(),
308            queued: 0,
309            queue_retired: 0,
310            flushing: false,
311            batch_depth: 0,
312            flush_epoch: 0,
313            host: None,
314            stats: RuntimeStats::default(),
315            profile: None,
316            fields: fields::Fields::default(),
317        }
318    }
319
320    fn enqueue(&mut self, key: Key) {
321        let Some(node) = self.nodes.get_mut(key) else {
322            return;
323        };
324        let phase = match node.compute {
325            Compute::Structure(_) => 0,
326            Compute::Binding(_) => 1,
327            Compute::Effect(_) => 2,
328            _ => return,
329        };
330        if !node.queued {
331            node.queued = true;
332            self.queued += 1;
333            match phase {
334                0 => self.structures.push_back(key),
335                1 => self.bindings.push_back(key),
336                _ => self.effects.push_back(key),
337            }
338        }
339    }
340
341    fn queue_entries(&self) -> usize {
342        self.structures.len() + self.bindings.len() + self.effects.len()
343    }
344
345    fn compact_queues(&mut self) {
346        debug_assert_eq!(self.queue_entries(), self.queued + self.queue_retired);
347        if self.queue_retired == 0 {
348            return;
349        }
350        let live = self.queued;
351        if live == 0 {
352            // Keys own no data. Clearing lengths needs no per-key destruction.
353            self.structures.clear();
354            self.bindings.clear();
355            self.effects.clear();
356        } else if self.queue_retired > live.saturating_add(QUEUE_SLACK) {
357            // Only node retirement leaves tombstones, so generation-checked
358            // arena lookup is sufficient. No callback, value or graph traversal.
359            self.stats.queue_compaction_visits += self.queue_entries() as u64;
360            self.structures.retain(|key| self.nodes.get(*key).is_some());
361            self.bindings.retain(|key| self.nodes.get(*key).is_some());
362            self.effects.retain(|key| self.nodes.get(*key).is_some());
363        } else {
364            return;
365        }
366        self.queue_retired = 0;
367        self.stats.queue_compactions += 1;
368    }
369
370    fn next_observer(&mut self) -> Option<Key> {
371        loop {
372            let key = self
373                .structures
374                .pop_front()
375                .or_else(|| self.bindings.pop_front())
376                .or_else(|| self.effects.pop_front())?;
377            if let Some(node) = self.nodes.get_mut(key)
378                && node.queued
379            {
380                node.queued = false;
381                self.queued -= 1;
382                // Draining live work can also change the live/tombstone ratio.
383                // Compact before callbacks so the bound holds during reentry.
384                self.compact_queues();
385                return Some(key);
386            }
387            self.queue_retired -= 1;
388        }
389    }
390
391    fn invalidate(&mut self, first: impl IntoIterator<Item = Key>) {
392        let mut pending: Vec<_> = first.into_iter().collect();
393        while let Some(key) = pending.pop() {
394            let Some(node) = self.nodes.get_mut(key) else {
395                continue;
396            };
397            if node.propagated {
398                continue;
399            }
400            node.propagated = true;
401            self.stats.marked += 1;
402            match node.status {
403                Status::Clean => node.status = Status::Check,
404                Status::Computing => node.rerun = true,
405                _ => {}
406            }
407            pending.extend(node.subscribers.iter().copied());
408            self.enqueue(key);
409        }
410    }
411
412    fn publish(&mut self, key: Key) {
413        let Some(node) = self.nodes.get_mut(key) else {
414            return;
415        };
416        node.version = node
417            .version
418            .checked_add(1)
419            .expect("source version exhausted");
420        self.stats.source_writes += 1;
421        if node.propagated {
422            return;
423        }
424        node.propagated = true;
425        let subscribers: Vec<_> = node.subscribers.iter().copied().collect();
426        self.invalidate(subscribers);
427    }
428
429    fn insert_node(&mut self, owner: Key, node: Node) -> Result<Key, AccessError> {
430        let owner = self.owners.get_mut(owner).ok_or(AccessError::Disposed)?;
431        let key = self.nodes.insert(node);
432        owner.nodes.insert(key);
433        self.enqueue(key);
434        Ok(key)
435    }
436
437    fn remove_node(&mut self, key: Key, cleanup: &mut Cleanup) {
438        let Some(node) = self.nodes.remove(key) else {
439            return;
440        };
441        if let Some(owner) = self.owners.get_mut(node.owner) {
442            owner.nodes.remove(&key);
443        }
444        for source in node.dependencies.keys() {
445            if let Some(source) = self.nodes.get_mut(*source) {
446                source.subscribers.remove(&key);
447            }
448        }
449        if node.queued {
450            self.queued -= 1;
451            // Cancel membership immediately. A small retirement must not scan
452            // unrelated ready work. Only numeric stale keys wait for compaction.
453            self.queue_retired += 1;
454            self.compact_queues();
455        }
456        self.invalidate(node.subscribers.iter().copied());
457        let removal = self.fields.detach(key, node.owner);
458        cleanup.fields.extend(removal.fields);
459        cleanup.nodes.push(node);
460        for alias in removal.aliases {
461            self.remove_node(alias, cleanup);
462        }
463    }
464
465    fn remove_task(&mut self, key: Key) -> Option<TaskState> {
466        let task = self.tasks.remove(key)?;
467        if let Some(owner) = self.owners.get_mut(task.owner) {
468            owner.tasks.remove(&key);
469        }
470        Some(task)
471    }
472
473    fn dispose_owner(&mut self, key: Key) -> Cleanup {
474        let mut cleanup = Cleanup::default();
475        let Some(mut owner) = self.owners.remove(key) else {
476            return cleanup;
477        };
478        // Most repeated disposals come from handles already retired by an
479        // ancestor. Do not allocate a traversal stack for them or for leaves.
480        let mut pending = Vec::new();
481        let mut key = key;
482        loop {
483            if let Some(parent) = owner.parent.and_then(|parent| self.owners.get_mut(parent)) {
484                parent.children.remove(&key);
485            }
486            pending.extend(owner.children);
487            if let Some(instance) = owner.instance {
488                self.instances.remove(instance);
489            }
490            if !owner.cleanup.is_empty() {
491                cleanup.callbacks.push((key, owner.cleanup));
492            }
493            for task in owner.tasks {
494                if let Some(task) = self.remove_task(task) {
495                    cleanup.tasks.push(task);
496                }
497            }
498            for node in owner.nodes {
499                self.remove_node(node, &mut cleanup);
500            }
501            loop {
502                let Some(next) = pending.pop() else {
503                    return cleanup;
504                };
505                if let Some(next_owner) = self.owners.remove(next) {
506                    key = next;
507                    owner = next_owner;
508                    break;
509                }
510            }
511        }
512    }
513}
514
515#[derive(Default)]
516struct Cleanup {
517    nodes: Vec<Node>,
518    tasks: Vec<TaskState>,
519    callbacks: Vec<(Key, Vec<Cancel>)>,
520    fields: Vec<fields::FieldData>,
521}
522impl Cleanup {
523    fn run(self, runtime: RuntimeId) {
524        // All identities and subscriptions have already been invalidated.
525        // Destructors and callbacks execute with no graph borrow held.
526        for task in self.tasks {
527            if let Some(cancel) = task.cancel {
528                untracked(|| enter_owner(runtime, task.owner, cancel));
529            }
530        }
531        for (owner, callbacks) in self.callbacks.into_iter().rev() {
532            untracked(|| {
533                enter_owner(runtime, owner, || {
534                    for callback in callbacks.into_iter().rev() {
535                        callback();
536                    }
537                });
538            });
539        }
540        drop(self.nodes);
541        drop(self.fields);
542    }
543}
544
545struct Evaluation {
546    state: Shared,
547    key: Key,
548    frame: Option<usize>,
549    complete: bool,
550}
551impl Evaluation {
552    fn new(state: &Shared, key: Key, mode: Mode) -> Self {
553        EVALUATING.with_borrow_mut(|stack| stack.push(mode));
554        Self {
555            state: state.clone(),
556            key,
557            frame: None,
558            complete: false,
559        }
560    }
561
562    fn start_tracking(&mut self, runtime: RuntimeId) {
563        self.frame = Some(TRACKING.with_borrow_mut(|stack| {
564            let previous = stack.len();
565            stack.push(Some(Frame {
566                runtime,
567                key: self.key,
568                dependencies: Dependencies::new(),
569            }));
570            previous
571        }));
572    }
573
574    fn dependencies(&mut self) -> Dependencies {
575        self.frame.take();
576        TRACKING.with_borrow_mut(|stack| {
577            let frame = stack.pop().flatten().expect("evaluation tracking frame");
578            debug_assert_eq!(frame.key, self.key);
579            frame.dependencies
580        })
581    }
582}
583
584impl Drop for Evaluation {
585    fn drop(&mut self) {
586        if let Some(previous) = self.frame {
587            TRACKING.with_borrow_mut(|stack| stack.truncate(previous));
588        }
589        if !self.complete {
590            let mut state = self.state.borrow_mut();
591            if let Some(node) = state.nodes.get_mut(self.key) {
592                node.status = Status::Dirty;
593                node.propagated = false;
594                state.enqueue(self.key);
595            }
596        }
597        EVALUATING.with_borrow_mut(|stack| {
598            stack.pop();
599        });
600    }
601}
602
603fn ensure(runtime: RuntimeId, state: &Shared, key: Key) -> Result<(), AccessError> {
604    let (compute, old_status, old_dependencies, old_value, profile) = {
605        let mut state = state.try_borrow_mut().map_err(|_| AccessError::Borrowed)?;
606        let node = state.nodes.get_mut(key).ok_or(AccessError::Disposed)?;
607        if node.status == Status::Computing {
608            return Err(AccessError::Cycle);
609        }
610        if node.status == Status::Clean {
611            return Ok(());
612        }
613        let job = (
614            node.compute.clone(),
615            node.status,
616            node.dependencies.clone(),
617            node.value.clone(),
618        );
619        node.status = Status::Computing;
620        node.propagated = false;
621        // Reads/validation can refresh only part of a pending graph. Rearm
622        // upstream frontiers before executing callbacks, including effects
623        // that write an existing dependency while this node is computing.
624        for dependency in job.2.keys() {
625            if let Some(source) = state.nodes.get_mut(*dependency) {
626                source.propagated = false;
627            }
628        }
629        state.stats.validations += 1;
630        (job.0, job.1, job.2, job.3, state.profile.clone())
631    };
632    let _validation = profile.as_ref().map(|profile| {
633        profile
634            .span(Phase::Validate)
635            .work(old_dependencies.len() as u64)
636    });
637    let mode = if matches!(compute, Compute::Effect(_) | Compute::Structure(_)) {
638        Mode::Effect
639    } else {
640        Mode::Pure
641    };
642    let mut evaluation = Evaluation::new(state, key, mode);
643    if old_status == Status::Check {
644        let mut changed = false;
645        for (dependency, version) in &old_dependencies {
646            if state.borrow().nodes.get(*dependency).is_none() {
647                changed = true;
648                continue;
649            }
650            ensure(runtime, state, *dependency)?;
651            changed |= state
652                .borrow()
653                .nodes
654                .get(*dependency)
655                .is_none_or(|source| source.version != *version);
656        }
657        if !changed {
658            if let Some(node) = state.borrow_mut().nodes.get_mut(key) {
659                node.status = Status::Clean;
660            }
661            evaluation.complete = true;
662            return Ok(());
663        }
664    }
665
666    evaluation.start_tracking(runtime);
667    let output = {
668        let phase = match &compute {
669            Compute::Derived { .. } => Some(Phase::Derive),
670            Compute::Binding(_) => Some(Phase::Bind),
671            Compute::Structure(_) => Some(Phase::Structure),
672            Compute::Effect(_) => Some(Phase::Effect),
673            Compute::Source => None,
674        };
675        let _compute = profile
676            .as_ref()
677            .zip(phase)
678            .map(|(profile, phase)| profile.span(phase));
679        // Dependency validation (or a profile clock) can retire this observer.
680        // Never execute a captured callback after its owning node disappeared.
681        let owner = state.borrow().nodes.get(key).map(|node| node.owner);
682        if let Some(owner) = owner {
683            enter_owner(runtime, owner, || {
684                Ok::<_, AccessError>(match &compute {
685                    Compute::Derived { mapper, .. } => Some(mapper()),
686                    Compute::Binding(callback)
687                    | Compute::Structure(callback)
688                    | Compute::Effect(callback) => {
689                        callback
690                            .try_borrow_mut()
691                            .map_err(|_| AccessError::Borrowed)?();
692                        None
693                    }
694                    Compute::Source => None,
695                })
696            })?
697        } else {
698            None
699        }
700    };
701    let dependencies = evaluation.dependencies();
702    let changed = if let (
703        Some(output),
704        Some(old),
705        Compute::Derived {
706            equal: Some(equal), ..
707        },
708    ) = (&output, &old_value, &compute)
709    {
710        untracked(|| !equal(old.borrow().as_ref(), output.as_ref()))
711    } else {
712        output.is_some()
713    };
714
715    let mut state = state.borrow_mut();
716    if state.nodes.get(key).is_none() {
717        evaluation.complete = true;
718        return Ok(());
719    }
720    for dependency in old_dependencies.keys() {
721        if !dependencies.contains_key(dependency)
722            && let Some(source) = state.nodes.get_mut(*dependency)
723        {
724            source.subscribers.remove(&key);
725        }
726    }
727    let mut needs_rerun = false;
728    for (dependency, version) in &dependencies {
729        if let Some(source) = state.nodes.get_mut(*dependency) {
730            // Existing edges remain registered while callbacks run. Still
731            // rearm/validate every dependency, even when insertion is skipped.
732            if !old_dependencies.contains_key(dependency) {
733                source.subscribers.insert(key);
734            }
735            // A new or recomputed subscriber has now observed this version.
736            // The next publication must reach it, even after unobserved writes.
737            source.propagated = false;
738            needs_rerun |= source.version != *version;
739        } else {
740            needs_rerun = true;
741        }
742    }
743    let node = state.nodes.get_mut(key).expect("live evaluation");
744    node.dependencies = dependencies;
745    let discarded = if changed {
746        node.version = node
747            .version
748            .checked_add(1)
749            .expect("derived version exhausted");
750        output.map(|output| node.value.replace(Rc::new(RefCell::new(output))))
751    } else {
752        None
753    };
754    needs_rerun |= node.rerun;
755    node.rerun = false;
756    node.status = if needs_rerun {
757        Status::Check
758    } else {
759        Status::Clean
760    };
761    node.propagated = false;
762    match compute {
763        Compute::Derived { .. } => state.stats.derived_runs += 1,
764        Compute::Binding(_) => state.stats.binding_runs += 1,
765        Compute::Structure(_) => state.stats.structural_runs += 1,
766        Compute::Effect(_) => state.stats.effect_runs += 1,
767        Compute::Source => {}
768    }
769    if needs_rerun {
770        state.enqueue(key);
771    }
772    evaluation.complete = true;
773    drop(state);
774    drop(discarded);
775    Ok(())
776}
777
778/// Owns one graph and its scheduler. Runtime is intentionally not Clone.
779pub struct Runtime {
780    id: RuntimeId,
781    state: Shared,
782}
783impl Default for Runtime {
784    fn default() -> Self {
785        Self::new()
786    }
787}
788impl Runtime {
789    pub fn new() -> Self {
790        let id = RuntimeId::new();
791        let state = Rc::new(RefCell::new(State::new()));
792        RUNTIMES.with_borrow_mut(|runtimes| runtimes.insert(id, Rc::downgrade(&state)));
793        Self { id, state }
794    }
795    pub fn with_host(host: Rc<dyn Host>) -> Self {
796        let runtime = Self::new();
797        runtime.state.borrow_mut().host = Some(host);
798        runtime
799    }
800    pub fn id(&self) -> RuntimeId {
801        self.id
802    }
803    pub fn profile(&self) -> Option<Profile> {
804        self.state.borrow().profile.clone()
805    }
806    pub fn set_profile(&self, profile: Option<Profile>) {
807        let previous = std::mem::replace(&mut self.state.borrow_mut().profile, profile);
808        drop(previous);
809    }
810    pub fn now(&self) -> Option<Duration> {
811        self.state.borrow().host.as_ref().map(|host| host.now())
812    }
813    /// Ask the attached event loop for an observation turn. This does not poll
814    /// tasks or execute application callbacks; host wake must only enqueue.
815    pub fn request_observe(&self) -> bool {
816        let host = self.state.borrow().host.clone();
817        if let Some(host) = host {
818            host.wake();
819            true
820        } else {
821            false
822        }
823    }
824    pub fn owner(&self) -> Owner {
825        let root = self.state.borrow().root;
826        make_owner(self.id, &self.state, root).expect("runtime root is live")
827    }
828    pub fn scope(&self) -> Scope {
829        make_scope(self.owner(), None).expect("runtime is live")
830    }
831
832    /// Run a synchronous callback under a live instance's Owner. This does not
833    /// retain the instance, borrow the graph during the callback, or flush work.
834    /// Foreign/stale identities are rejected before calling user code; nested
835    /// context is restored on return or panic. Future polls need their own entry.
836    #[inline]
837    pub fn enter<R>(&self, instance: InstanceId, f: impl FnOnce() -> R) -> Result<R, AccessError> {
838        if instance.runtime != self.id {
839            return Err(AccessError::WrongRuntime);
840        }
841        let owner = {
842            let state = self.state.borrow();
843            let owner = state
844                .instances
845                .get(instance.key)
846                .ok_or(AccessError::Disposed)?
847                .owner;
848            state.owners.get(owner).ok_or(AccessError::Disposed)?;
849            owner
850        };
851        Ok(enter_owner(self.id, owner, f))
852    }
853
854    /// Values enqueue work. Explicit flush/batch at an event/frame boundary
855    /// prevents a series of writes from rendering intermediate states.
856    pub fn batch<R>(&self, f: impl FnOnce() -> R) -> Result<R, AccessError> {
857        self.state.borrow_mut().batch_depth += 1;
858        struct Batch(Shared);
859        impl Drop for Batch {
860            fn drop(&mut self) {
861                self.0.borrow_mut().batch_depth -= 1;
862            }
863        }
864        let guard = Batch(self.state.clone());
865        let value = f();
866        drop(guard);
867        let flush = {
868            let state = self.state.borrow();
869            state.batch_depth == 0 && !state.flushing
870        };
871        if flush {
872            self.flush()?;
873        }
874        Ok(value)
875    }
876
877    pub fn flush(&self) -> Result<(), AccessError> {
878        if self.state.borrow().batch_depth != 0 {
879            return Ok(());
880        }
881        if self.state.borrow().flushing {
882            return Err(AccessError::ReentrantFlush);
883        }
884        let _span = self.profile().map(|profile| profile.span(Phase::Flush));
885        self.state.borrow_mut().flushing = true;
886        let epoch = {
887            let mut state = self.state.borrow_mut();
888            state.flush_epoch = state
889                .flush_epoch
890                .checked_add(1)
891                .expect("flush epoch exhausted");
892            state.flush_epoch
893        };
894        struct Flush(Shared);
895        impl Drop for Flush {
896            fn drop(&mut self) {
897                self.0.borrow_mut().flushing = false;
898            }
899        }
900        let _guard = Flush(self.state.clone());
901        loop {
902            let key = self.state.borrow_mut().next_observer();
903            let Some(key) = key else { break };
904            {
905                let mut state = self.state.borrow_mut();
906                let Some(node) = state.nodes.get_mut(key) else {
907                    continue;
908                };
909                if node.last_flush != epoch {
910                    node.last_flush = epoch;
911                    node.flush_runs = 0;
912                }
913                node.flush_runs += 1;
914                // Bound repeated feedback of one observer, not the total number
915                // of independent bindings in a large application/SSR document.
916                if node.flush_runs > 1024 {
917                    state.enqueue(key);
918                    return Err(AccessError::RunawayEffect);
919                }
920            }
921            ensure(self.id, &self.state, key)?;
922        }
923        Ok(())
924    }
925
926    /// Explicit O(live nodes) diagnostic. Fixed aggregate bins contain no
927    /// values, identities, visited rows or evaluation history.
928    pub fn graph_stats(&self) -> GraphStats {
929        fn bin(degree: usize) -> usize {
930            match degree {
931                0 => 0,
932                1 => 1,
933                2 => 2,
934                3..=4 => 3,
935                5..=8 => 4,
936                9..=64 => 5,
937                _ => 6,
938            }
939        }
940        let state = self.state.borrow();
941        let mut result = GraphStats::default();
942        for node in state.nodes.values() {
943            let kind = match node.compute {
944                Compute::Source => 0,
945                Compute::Derived { .. } => 1,
946                Compute::Structure(_) => 2,
947                Compute::Binding(_) => 3,
948                Compute::Effect(_) => 4,
949            };
950            result.nodes[kind] += 1;
951            result.dependencies[kind][bin(node.dependencies.len())] += 1;
952            result.subscribers[kind][bin(node.subscribers.len())] += 1;
953        }
954        result
955    }
956    pub fn stats(&self) -> RuntimeStats {
957        let state = self.state.borrow();
958        let (entry_keys, entry_buckets) = state.fields.entry_stats();
959        let (field_target_caches, field_target_keys) = state.fields.target_stats();
960        RuntimeStats {
961            nodes: state.nodes.len(),
962            node_slots: state.nodes.capacity(),
963            owners: state.owners.len(),
964            owner_slots: state.owners.capacity(),
965            instances: state.instances.len(),
966            instance_slots: state.instances.capacity(),
967            tasks: state.tasks.len(),
968            task_slots: state.tasks.capacity(),
969            edges: state
970                .nodes
971                .values()
972                .map(|node| node.dependencies.len())
973                .sum(),
974            queued: state.queued,
975            queue_entries: state.queue_entries(),
976            queue_capacity: state.structures.capacity()
977                + state.bindings.capacity()
978                + state.effects.capacity(),
979            fields: state.fields.len(),
980            field_slots: state.fields.capacity(),
981            entry_keys,
982            entry_buckets,
983            field_target_caches,
984            field_target_keys,
985            ..state.stats
986        }
987    }
988}
989impl Drop for Runtime {
990    fn drop(&mut self) {
991        RUNTIMES.with_borrow_mut(|runtimes| runtimes.remove(&self.id));
992        let root = self.state.borrow().root;
993        let cleanup = self.state.borrow_mut().dispose_owner(root);
994        cleanup.run(self.id);
995    }
996}
997
998pub struct Owner {
999    runtime: RuntimeId,
1000    key: Key,
1001    local: PhantomData<Rc<()>>,
1002}
1003/// Non-owning identity for internal controllers. It cannot prolong an Owner or
1004/// its Runtime, and every operation validates its generation.
1005#[derive(Clone, Copy)]
1006pub(crate) struct OwnerHandle {
1007    runtime: RuntimeId,
1008    key: Key,
1009}
1010impl Owner {
1011    pub(crate) fn handle(&self) -> OwnerHandle {
1012        OwnerHandle {
1013            runtime: self.runtime,
1014            key: self.key,
1015        }
1016    }
1017    /// Derived maps created by this widget/factory belong to this owner,
1018    /// even when their source is application-wide. The context never owns data.
1019    pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
1020        assert!(self.is_alive(), "enter live owner");
1021        enter_owner(self.runtime, self.key, f)
1022    }
1023    pub fn runtime(&self) -> RuntimeId {
1024        self.runtime
1025    }
1026    pub fn is_alive(&self) -> bool {
1027        lookup(self.runtime).is_ok_and(|state| state.borrow().owners.get(self.key).is_some())
1028    }
1029    pub fn child(&self) -> Self {
1030        make_owner(
1031            self.runtime,
1032            &lookup(self.runtime).expect("live runtime"),
1033            self.key,
1034        )
1035        .expect("live owner")
1036    }
1037    pub fn dispose(&self) {
1038        if let Ok(state) = lookup(self.runtime) {
1039            let cleanup = state.borrow_mut().dispose_owner(self.key);
1040            cleanup.run(self.runtime);
1041        }
1042    }
1043    /// Run untracked after this Owner and its descendants have been invalidated.
1044    /// Implicit map/path construction remains in the retired Owner and fails;
1045    /// explicit entry into another live Owner is allowed. Callbacks run without
1046    /// graph borrows, in reverse registration order (children before parents).
1047    /// A panic unwinds normally; there is no catch/retry of remaining callbacks.
1048    pub fn on_cleanup(&self, cleanup: impl FnOnce() + 'static) -> Result<(), AccessError> {
1049        let state = lookup(self.runtime)?;
1050        state
1051            .borrow_mut()
1052            .owners
1053            .get_mut(self.key)
1054            .ok_or(AccessError::Disposed)?
1055            .cleanup
1056            .push(Box::new(cleanup));
1057        Ok(())
1058    }
1059
1060    pub fn cage<T: 'static>(&self, value: T) -> Cage<T> {
1061        allow_creation().expect("state creation is not allowed in a pure computation");
1062        let node = Node {
1063            owner: self.key,
1064            compute: Compute::Source,
1065            value: Some(Rc::new(RefCell::new(Box::new(value)))),
1066            version: 1,
1067            status: Status::Clean,
1068            rerun: false,
1069            propagated: false,
1070            queued: false,
1071            last_flush: 0,
1072            flush_runs: 0,
1073            dependencies: Dependencies::new(),
1074            subscribers: Subscribers::new(),
1075        };
1076        let key = lookup(self.runtime)
1077            .expect("live runtime")
1078            .borrow_mut()
1079            .insert_node(self.key, node)
1080            .expect("live owner");
1081        Cage {
1082            handle: Handle::new(self.runtime, key),
1083        }
1084    }
1085
1086    /// Synchronous, untracked pure computation under this live Owner.
1087    /// Allocates no reactive node. Both reads and unwind restore the outer
1088    /// tracking/mode/construction context; writes/creation remain forbidden.
1089    pub fn compute<T>(&self, f: impl FnOnce() -> T) -> Result<T, AccessError> {
1090        let state = lookup(self.runtime)?;
1091        if state.borrow().owners.get(self.key).is_none() {
1092            return Err(AccessError::Disposed);
1093        }
1094        struct Pure;
1095        impl Drop for Pure {
1096            fn drop(&mut self) {
1097                EVALUATING.with_borrow_mut(|stack| {
1098                    stack.pop();
1099                });
1100            }
1101        }
1102        Ok(enter_owner(self.runtime, self.key, || {
1103            EVALUATING.with_borrow_mut(|stack| stack.push(Mode::Pure));
1104            let _pure = Pure;
1105            untracked(f)
1106        }))
1107    }
1108    pub fn bond<T: 'static>(&self, mapper: impl Fn() -> T + 'static) -> Bond<T> {
1109        make_bond(self.runtime, self.key, mapper).expect("live owner")
1110    }
1111
1112    pub fn binding(&self, callback: impl FnMut() + 'static) -> BindingId {
1113        self.observer(callback, 1)
1114    }
1115    /// Effects run after currently queued bindings. Writes enqueue another pass;
1116    /// reads still form direct dependencies, and runaway loops fail explicitly.
1117    pub fn effect(&self, callback: impl FnMut() + 'static) -> BindingId {
1118        self.observer(callback, 2)
1119    }
1120    /// Structural controllers update owned row state before prop bindings run.
1121    /// Use this for tree control flow; ordinary computed props remain pure.
1122    pub fn structural(&self, callback: impl FnMut() + 'static) -> BindingId {
1123        self.observer(callback, 0)
1124    }
1125    fn observer(&self, callback: impl FnMut() + 'static, phase: u8) -> BindingId {
1126        allow_creation().expect("observer creation is not allowed in a pure computation");
1127        let callback = Rc::new(RefCell::new(Box::new(callback) as Box<dyn FnMut()>));
1128        let compute = match phase {
1129            0 => Compute::Structure(callback),
1130            1 => Compute::Binding(callback),
1131            _ => Compute::Effect(callback),
1132        };
1133        let node = Node {
1134            owner: self.key,
1135            compute,
1136            value: None,
1137            version: 0,
1138            status: Status::Dirty,
1139            rerun: false,
1140            propagated: false,
1141            queued: false,
1142            last_flush: 0,
1143            flush_runs: 0,
1144            dependencies: Dependencies::new(),
1145            subscribers: Subscribers::new(),
1146        };
1147        let key = lookup(self.runtime)
1148            .expect("live runtime")
1149            .borrow_mut()
1150            .insert_node(self.key, node)
1151            .expect("live owner");
1152        BindingId {
1153            runtime: self.runtime,
1154            key,
1155            local: PhantomData,
1156        }
1157    }
1158
1159    pub fn task(&self) -> Task {
1160        self.handle().task()
1161    }
1162
1163    pub fn spawn(
1164        &self,
1165        future: impl Future<Output = ()> + 'static,
1166    ) -> Result<TaskToken, AccessError> {
1167        self.handle().spawn(future)
1168    }
1169}
1170impl OwnerHandle {
1171    fn task(self) -> Task {
1172        allow_creation().expect("task creation is not allowed in a pure computation");
1173        let state = lookup(self.runtime).expect("live runtime");
1174        let mut state = state.borrow_mut();
1175        assert!(state.owners.get(self.key).is_some(), "live owner");
1176        let key = state.tasks.insert(TaskState {
1177            owner: self.key,
1178            cancel: None,
1179        });
1180        state
1181            .owners
1182            .get_mut(self.key)
1183            .expect("live owner")
1184            .tasks
1185            .insert(key);
1186        Task {
1187            token: TaskToken {
1188                runtime: self.runtime,
1189                key,
1190                local: PhantomData,
1191            },
1192            detached: false,
1193        }
1194    }
1195
1196    pub(crate) fn spawn(
1197        self,
1198        future: impl Future<Output = ()> + 'static,
1199    ) -> Result<TaskToken, AccessError> {
1200        allow_creation()?;
1201        let state = lookup(self.runtime)?;
1202        if state.borrow().owners.get(self.key).is_none() {
1203            return Err(AccessError::Disposed);
1204        }
1205        let host = state.borrow().host.clone().ok_or(AccessError::NoHost)?;
1206        let task = self.task();
1207        let token = task.token();
1208        struct Completion(TaskToken);
1209        impl Drop for Completion {
1210            fn drop(&mut self) {
1211                finish_task(self.0, false);
1212            }
1213        }
1214        let cancel = host
1215            .spawn(Box::pin(async move {
1216                let _completion = Completion(token);
1217                if token.is_current() {
1218                    let mut future = Box::pin(future);
1219                    std::future::poll_fn(move |context| {
1220                        let Ok(state) = lookup(token.runtime) else {
1221                            return std::task::Poll::Ready(());
1222                        };
1223                        let owner = state.borrow().tasks.get(token.key).map(|task| task.owner);
1224                        let Some(owner) = owner else {
1225                            return std::task::Poll::Ready(());
1226                        };
1227                        let profile = state.borrow().profile.clone();
1228                        let _span = profile.map(|profile| profile.span(Phase::Task));
1229                        enter_owner(token.runtime, owner, || future.as_mut().poll(context))
1230                    })
1231                    .await;
1232                }
1233            }))
1234            .map_err(AccessError::Host)?;
1235        let mut cancel = Some(cancel);
1236        if let Some(task) = state.borrow_mut().tasks.get_mut(token.key) {
1237            task.cancel = cancel.take();
1238        }
1239        if let Some(cancel) = cancel {
1240            cancel();
1241        }
1242        Ok(task.detach())
1243    }
1244}
1245impl Drop for Owner {
1246    fn drop(&mut self) {
1247        self.dispose();
1248    }
1249}
1250impl std::fmt::Debug for Owner {
1251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1252        f.debug_struct("Owner")
1253            .field("runtime", &self.runtime)
1254            .field("key", &self.key)
1255            .finish()
1256    }
1257}
1258
1259fn make_owner(runtime: RuntimeId, state: &Shared, parent: Key) -> Result<Owner, AccessError> {
1260    let mut state = state.borrow_mut();
1261    if state.owners.get(parent).is_none() {
1262        return Err(AccessError::Disposed);
1263    }
1264    let key = state.owners.insert(OwnerData {
1265        parent: Some(parent),
1266        ..OwnerData::default()
1267    });
1268    state
1269        .owners
1270        .get_mut(parent)
1271        .expect("live parent")
1272        .children
1273        .insert(key);
1274    Ok(Owner {
1275        runtime,
1276        key,
1277        local: PhantomData,
1278    })
1279}
1280
1281#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1282pub struct InstanceId {
1283    runtime: RuntimeId,
1284    key: Key,
1285}
1286impl InstanceId {
1287    /// Create an owned child from a validated, non-owning parent identity.
1288    /// Controllers may capture this identity without retaining their own Scope.
1289    pub fn child_scope(self) -> Result<Scope, AccessError> {
1290        allow_creation()?;
1291        let state = lookup(self.runtime)?;
1292        let owner = {
1293            let state = state.borrow();
1294            let instance = state.instances.get(self.key).ok_or(AccessError::Disposed)?;
1295            if state.owners.get(instance.owner).is_none() {
1296                return Err(AccessError::Disposed);
1297            }
1298            instance.owner
1299        };
1300        make_scope(make_owner(self.runtime, &state, owner)?, Some(self.key))
1301    }
1302    /// Whether this generational instance and its Owner are still live.
1303    /// Does not enter construction context or invoke application code.
1304    pub fn is_alive(self) -> bool {
1305        lookup(self.runtime).is_ok_and(|state| {
1306            let state = state.borrow();
1307            state
1308                .instances
1309                .get(self.key)
1310                .is_some_and(|instance| state.owners.get(instance.owner).is_some())
1311        })
1312    }
1313    pub fn runtime(self) -> RuntimeId {
1314        self.runtime
1315    }
1316    pub fn slot(self) -> u32 {
1317        self.key.slot
1318    }
1319    pub fn generation(self) -> u32 {
1320        self.key.generation
1321    }
1322}
1323
1324#[derive(Debug)]
1325pub struct Scope {
1326    owner: Owner,
1327    id: InstanceId,
1328}
1329impl Scope {
1330    pub fn id(&self) -> InstanceId {
1331        self.id
1332    }
1333    pub fn owner(&self) -> &Owner {
1334        &self.owner
1335    }
1336    /// Whether this live Scope has an explicitly installed task execution service.
1337    /// This neither constructs/polls a future nor asks the host to perform work.
1338    /// An installed but closed/limited host still reports its normal spawn error.
1339    pub fn has_task_host(&self) -> Result<bool, AccessError> {
1340        let state = lookup(self.id.runtime)?;
1341        let state = state.borrow();
1342        let instance = state
1343            .instances
1344            .get(self.id.key)
1345            .ok_or(AccessError::Disposed)?;
1346        if instance.owner != self.owner.key || state.owners.get(self.owner.key).is_none() {
1347            return Err(AccessError::Disposed);
1348        }
1349        Ok(state.host.is_some())
1350    }
1351    pub fn child(&self) -> Self {
1352        make_scope(self.owner.child(), Some(self.id.key)).expect("live scope")
1353    }
1354    pub fn parent(&self) -> Option<InstanceId> {
1355        let state = lookup(self.id.runtime).ok()?;
1356        let state = state.borrow();
1357        let parent = state.instances.get(self.id.key)?.parent?;
1358        Some(InstanceId {
1359            runtime: self.id.runtime,
1360            key: parent,
1361        })
1362    }
1363    pub fn is_alive(&self) -> bool {
1364        lookup(self.id.runtime).is_ok_and(|state| {
1365            state
1366                .borrow()
1367                .instances
1368                .get(self.id.key)
1369                .is_some_and(|instance| instance.owner == self.owner.key)
1370        })
1371    }
1372}
1373impl std::ops::Deref for Scope {
1374    type Target = Owner;
1375    fn deref(&self) -> &Owner {
1376        &self.owner
1377    }
1378}
1379fn make_scope(owner: Owner, parent: Option<Key>) -> Result<Scope, AccessError> {
1380    let state = lookup(owner.runtime)?;
1381    let mut state = state.borrow_mut();
1382    if state.owners.get(owner.key).is_none() {
1383        return Err(AccessError::Disposed);
1384    }
1385    if let Some(parent) = parent
1386        && state.instances.get(parent).is_none()
1387    {
1388        return Err(AccessError::Disposed);
1389    }
1390    let key = state.instances.insert(Instance {
1391        owner: owner.key,
1392        parent,
1393    });
1394    state
1395        .owners
1396        .get_mut(owner.key)
1397        .expect("live owner")
1398        .instance = Some(key);
1399    Ok(Scope {
1400        id: InstanceId {
1401            runtime: owner.runtime,
1402            key,
1403        },
1404        owner,
1405    })
1406}
1407
1408#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1409pub struct BindingId {
1410    runtime: RuntimeId,
1411    key: Key,
1412    local: PhantomData<Rc<()>>,
1413}
1414impl BindingId {
1415    pub fn dispose(self) {
1416        if let Ok(state) = lookup(self.runtime) {
1417            let mut cleanup = Cleanup::default();
1418            state.borrow_mut().remove_node(self.key, &mut cleanup);
1419            cleanup.run(self.runtime);
1420        }
1421    }
1422    pub fn is_alive(self) -> bool {
1423        lookup(self.runtime).is_ok_and(|state| state.borrow().nodes.get(self.key).is_some())
1424    }
1425}
1426
1427struct Handle<T: 'static> {
1428    runtime: RuntimeId,
1429    key: Key,
1430    local: PhantomData<Rc<T>>,
1431}
1432impl<T> Copy for Handle<T> {}
1433impl<T> Clone for Handle<T> {
1434    fn clone(&self) -> Self {
1435        *self
1436    }
1437}
1438impl<T> Handle<T> {
1439    fn new(runtime: RuntimeId, key: Key) -> Self {
1440        Self {
1441            runtime,
1442            key,
1443            local: PhantomData,
1444        }
1445    }
1446    fn with<R>(self, tracked: bool, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1447        fields::allow_read()?;
1448        if tracked {
1449            check_reader(self.runtime)?;
1450        }
1451        let state = lookup(self.runtime)?;
1452        ensure(self.runtime, &state, self.key)?;
1453        let (path, version) = {
1454            let state = state.borrow();
1455            let node = state.nodes.get(self.key).ok_or(AccessError::Disposed)?;
1456            (state.value_path(self.key, node)?, node.version)
1457        };
1458        if tracked {
1459            track(self.runtime, self.key, version)?;
1460        }
1461        let value = path.value.try_borrow().map_err(|_| AccessError::Borrowed)?;
1462        let value = path.read(value.as_ref())?;
1463        Ok(f(value.downcast_ref().ok_or(AccessError::TypeMismatch)?))
1464    }
1465}
1466
1467/// Copy, thread-local reactive identity. `get` returns an owned clone; use
1468/// `with` for large collections so indexed reads never clone the whole data set.
1469///
1470/// ```compile_fail
1471/// let runtime = glory_core::Runtime::new();
1472/// let owner = runtime.owner();
1473/// let value = owner.cage(1);
1474/// std::thread::spawn(move || value.get()); // Handles cannot cross UI threads.
1475/// ```
1476pub struct Cage<T: 'static> {
1477    handle: Handle<T>,
1478}
1479pub struct Bond<T: 'static> {
1480    handle: Handle<T>,
1481}
1482macro_rules! read_handle {
1483    ($name:ident) => {
1484        impl<T> Copy for $name<T> {}
1485        impl<T> Clone for $name<T> {
1486            fn clone(&self) -> Self {
1487                *self
1488            }
1489        }
1490        impl<T> std::fmt::Debug for $name<T> {
1491            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1492                f.debug_struct(stringify!($name))
1493                    .field("runtime", &self.handle.runtime)
1494                    .field("key", &self.handle.key)
1495                    .finish()
1496            }
1497        }
1498        impl<T> $name<T> {
1499            pub fn runtime(self) -> RuntimeId {
1500                self.handle.runtime
1501            }
1502            pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1503                self.handle.with(true, f)
1504            }
1505            pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1506                self.try_with(f).expect("read live reactive value")
1507            }
1508            pub fn try_with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1509                self.handle.with(false, f)
1510            }
1511            pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1512                self.try_with_untracked(f)
1513                    .expect("read live reactive value")
1514            }
1515            pub fn try_get(self) -> Result<T, AccessError>
1516            where
1517                T: Clone,
1518            {
1519                self.try_with(Clone::clone)
1520            }
1521            pub fn get(self) -> T
1522            where
1523                T: Clone,
1524            {
1525                self.with(Clone::clone)
1526            }
1527            pub fn get_untracked(self) -> T
1528            where
1529                T: Clone,
1530            {
1531                self.with_untracked(Clone::clone)
1532            }
1533            pub fn is_alive(self) -> bool {
1534                lookup(self.handle.runtime)
1535                    .is_ok_and(|state| state.borrow().nodes.get(self.handle.key).is_some())
1536            }
1537        }
1538    };
1539}
1540read_handle!(Cage);
1541read_handle!(Bond);
1542
1543struct Write {
1544    state: Shared,
1545    key: Key,
1546}
1547impl Drop for Write {
1548    fn drop(&mut self) {
1549        let host = {
1550            let mut state = self.state.borrow_mut();
1551            state.publish(self.key);
1552            state.host.clone()
1553        };
1554        if let Some(host) = host {
1555            host.wake();
1556        }
1557    }
1558}
1559impl<T> Cage<T> {
1560    /// Current source version, without subscribing or borrowing the value.
1561    /// Every successful write advances this stamp, even when equal data is
1562    /// restored. The identity is generation checked; a live collection path
1563    /// may still refer to a missing value. This does not flush pending work.
1564    pub fn try_version(self) -> Result<u64, AccessError> {
1565        fields::allow_read()?;
1566        let state = lookup(self.handle.runtime)?;
1567        let state = state.borrow();
1568        Ok(state
1569            .nodes
1570            .get(self.handle.key)
1571            .ok_or(AccessError::Disposed)?
1572            .version)
1573    }
1574    pub fn try_revise<R>(self, f: impl FnOnce(&mut T) -> R) -> Result<R, AccessError> {
1575        if EVALUATING.with_borrow(|stack| stack.last().is_some_and(|mode| *mode == Mode::Pure)) {
1576            return Err(AccessError::WriteDuringCompute);
1577        }
1578        let state = lookup(self.handle.runtime)?;
1579        let value = {
1580            let state = state.borrow();
1581            let node = state
1582                .nodes
1583                .get(self.handle.key)
1584                .ok_or(AccessError::Disposed)?;
1585            if !matches!(node.compute, Compute::Source) {
1586                return Err(AccessError::TypeMismatch);
1587            }
1588            node.version
1589                .checked_add(1)
1590                .expect("source version exhausted");
1591            if state.fields.has_root(self.handle.key) {
1592                None
1593            } else {
1594                node.value.clone()
1595            }
1596        };
1597        let Some(value) = value else {
1598            return fields::revise(state, self.handle.key, f);
1599        };
1600        let mut borrowed = value.try_borrow_mut().map_err(|_| AccessError::Borrowed)?;
1601        let value = borrowed.downcast_mut().ok_or(AccessError::TypeMismatch)?;
1602        let write = Write {
1603            state,
1604            key: self.handle.key,
1605        };
1606        let result = f(value);
1607        drop(borrowed);
1608        drop(write);
1609        Ok(result)
1610    }
1611    pub fn revise<R>(self, f: impl FnOnce(&mut T) -> R) -> R {
1612        self.try_revise(f)
1613            .expect("revise live reactive value outside pure computation")
1614    }
1615    pub fn map<U: 'static>(self, mapper: impl Fn(&T) -> U + 'static) -> Bond<U> {
1616        let state = lookup(self.handle.runtime).expect("live runtime");
1617        let source_owner = state
1618            .borrow()
1619            .nodes
1620            .get(self.handle.key)
1621            .expect("live source")
1622            .owner;
1623        let owner = CONSTRUCTING.with_borrow(|stack| {
1624            stack
1625                .last()
1626                .filter(|(runtime, _)| *runtime == self.handle.runtime)
1627                .map(|(_, owner)| *owner)
1628                .unwrap_or(source_owner)
1629        });
1630        make_bond(self.handle.runtime, owner, move || self.with(&mapper)).expect("live owner")
1631    }
1632}
1633
1634fn make_bond<T: 'static>(
1635    runtime: RuntimeId,
1636    owner: Key,
1637    mapper: impl Fn() -> T + 'static,
1638) -> Result<Bond<T>, AccessError> {
1639    allow_creation()?;
1640    let compute = Compute::Derived {
1641        mapper: Rc::new(move || Box::new(mapper())),
1642        equal: None,
1643    };
1644    let node = Node {
1645        owner,
1646        compute,
1647        value: None,
1648        version: 0,
1649        status: Status::Dirty,
1650        rerun: false,
1651        propagated: false,
1652        queued: false,
1653        last_flush: 0,
1654        flush_runs: 0,
1655        dependencies: Dependencies::new(),
1656        subscribers: Subscribers::new(),
1657    };
1658    let key = lookup(runtime)?.borrow_mut().insert_node(owner, node)?;
1659    Ok(Bond {
1660        handle: Handle::new(runtime, key),
1661    })
1662}
1663impl<T> Bond<T> {
1664    pub fn with_eq(self, equal: impl Fn(&T, &T) -> bool + 'static) -> Self {
1665        let state = lookup(self.handle.runtime).expect("live runtime");
1666        let mut state = state.borrow_mut();
1667        let node = state.nodes.get_mut(self.handle.key).expect("live bond");
1668        let Compute::Derived {
1669            equal: comparator, ..
1670        } = &mut node.compute
1671        else {
1672            unreachable!()
1673        };
1674        let previous = comparator.replace(Rc::new(move |a, b| {
1675            equal(
1676                a.downcast_ref().expect("bond type"),
1677                b.downcast_ref().expect("bond type"),
1678            )
1679        }));
1680        drop(state);
1681        drop(previous);
1682        self
1683    }
1684    pub fn with_partial_eq(self) -> Self
1685    where
1686        T: PartialEq,
1687    {
1688        self.with_eq(PartialEq::eq)
1689    }
1690}
1691
1692#[derive(Clone, Debug)]
1693pub enum Vary<T: 'static> {
1694    Value(T),
1695    Cage(Cage<T>),
1696    Bond(Bond<T>),
1697}
1698impl<T> Vary<T> {
1699    pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1700        match self {
1701            Self::Value(value) => Ok(f(value)),
1702            Self::Cage(value) => value.try_with(f),
1703            Self::Bond(value) => value.try_with(f),
1704        }
1705    }
1706    pub fn try_get(&self) -> Result<T, AccessError>
1707    where
1708        T: Clone,
1709    {
1710        self.try_with(Clone::clone)
1711    }
1712    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1713        match self {
1714            Self::Value(value) => f(value),
1715            Self::Cage(value) => value.with(f),
1716            Self::Bond(value) => value.with(f),
1717        }
1718    }
1719    pub fn get(&self) -> T
1720    where
1721        T: Clone,
1722    {
1723        self.with(Clone::clone)
1724    }
1725    pub fn is_reactive(&self) -> bool {
1726        !matches!(self, Self::Value(_))
1727    }
1728}
1729impl<T> From<T> for Vary<T> {
1730    fn from(value: T) -> Self {
1731        Self::Value(value)
1732    }
1733}
1734impl<T> From<Cage<T>> for Vary<T> {
1735    fn from(value: Cage<T>) -> Self {
1736        Self::Cage(value)
1737    }
1738}
1739impl<T> From<Bond<T>> for Vary<T> {
1740    fn from(value: Bond<T>) -> Self {
1741        Self::Bond(value)
1742    }
1743}
1744impl From<&str> for Vary<String> {
1745    fn from(value: &str) -> Self {
1746        Self::Value(value.to_owned())
1747    }
1748}
1749
1750#[derive(Clone, Copy, Debug)]
1751pub struct TaskToken {
1752    runtime: RuntimeId,
1753    key: Key,
1754    local: PhantomData<Rc<()>>,
1755}
1756impl TaskToken {
1757    pub fn is_current(self) -> bool {
1758        lookup(self.runtime).is_ok_and(|state| state.borrow().tasks.get(self.key).is_some())
1759    }
1760    pub fn commit<R>(self, f: impl FnOnce() -> R) -> Result<R, AccessError> {
1761        let state = lookup(self.runtime)?;
1762        let owner = state
1763            .borrow()
1764            .tasks
1765            .get(self.key)
1766            .ok_or(AccessError::Disposed)?
1767            .owner;
1768        Ok(enter_owner(self.runtime, owner, f))
1769    }
1770    pub fn cancel(self) {
1771        finish_task(self, true);
1772    }
1773}
1774
1775pub struct Task {
1776    token: TaskToken,
1777    detached: bool,
1778}
1779impl Task {
1780    pub fn token(&self) -> TaskToken {
1781        self.token
1782    }
1783    pub fn on_cancel(&self, cancel: impl FnOnce() + 'static) -> Result<(), AccessError> {
1784        let state = lookup(self.token.runtime)?;
1785        let mut state = state.borrow_mut();
1786        let task = state
1787            .tasks
1788            .get_mut(self.token.key)
1789            .ok_or(AccessError::Disposed)?;
1790        let previous = task.cancel.take();
1791        task.cancel = Some(Box::new(move || {
1792            if let Some(previous) = previous {
1793                previous();
1794            }
1795            cancel();
1796        }));
1797        Ok(())
1798    }
1799    pub fn detach(mut self) -> TaskToken {
1800        self.detached = true;
1801        self.token
1802    }
1803    pub fn complete(mut self) {
1804        finish_task(self.token, false);
1805        self.detached = true;
1806    }
1807}
1808impl Drop for Task {
1809    fn drop(&mut self) {
1810        if !self.detached {
1811            finish_task(self.token, true);
1812        }
1813    }
1814}
1815fn finish_task(token: TaskToken, cancel: bool) {
1816    if let Ok(state) = lookup(token.runtime) {
1817        let task = state.borrow_mut().remove_task(token.key);
1818        if cancel
1819            && let Some(task) = task
1820            && let Some(cancel) = task.cancel
1821        {
1822            untracked(|| enter_owner(token.runtime, task.owner, cancel));
1823        }
1824    }
1825}