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