pax-runtime-api 0.39.1

Userland constructs used at the runtime API boundary of Pax Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
use std::{
    any::Any,
    cell::RefCell,
    collections::{HashMap, HashSet, VecDeque},
    rc::Rc,
};

use slotmap::SlotMap;
#[cfg(debug_assertions)]
use slotmap::SparseSecondaryMap;

use crate::{LocalProperty, TransitionManager, TransitionQueueEntry};

use super::{private::PropertyId, PropertyValue};

#[derive(Clone, Debug, Default)]
pub struct EffectDrainReport {
    pub ran: usize,
    pub popped: usize,
    pub skipped_clean: usize,
    pub skipped_unregistered: usize,
    pub skipped_missing: usize,
    pub remaining: usize,
    pub cutoffs_evaluated: usize,
    pub cutoffs_suppressed: usize,
    pub cutoffs_propagated: usize,
    pub remaining_cutoffs: usize,
    pub budget_exhausted: bool,
    pub top_effects: Vec<(String, usize)>,
    pub top_cutoffs: Vec<(String, usize)>,
}

thread_local! {
    // Global property table used to store data backing dirty-dag
    pub(crate) static PROPERTY_TABLE: PropertyTable = PropertyTable::default();
    // Global frame timestamp.
    pub(crate) static PROPERTY_TIME: RefCell<LocalProperty<u64>> = RefCell::new(LocalProperty::new(0));
    // Global wall-clock timestamp in milliseconds.
    pub(crate) static PROPERTY_MILLIS: RefCell<LocalProperty<u64>> = RefCell::new(LocalProperty::new(0));
}

// The main collection of data associated with a specific property id
pub struct PropertyData {
    owner_graph: Option<u64>,
    owner_scope: Option<std::rc::Weak<super::shared_graph::BindingScopeInner>>,
    // typed data for this property,
    // can always be downcast to TypedPropertyData<T>
    // where T matches the property type
    typed_data: Box<dyn Any>,
    // List of properties that this property depends on
    pub inbound: Vec<PropertyId>,
    // List of properties that depend on this value
    pub outbound: Vec<PropertyId>,
    // Dirty bit set if a dependency further up in the dirty-dag tree
    // has been changed. For computed this can be any other props,
    // for literals, only time variable
    pub dirty: bool,
    // Type-erased entry point used to settle cutoff properties from the
    // synchronous reactive worklist.
    pub(super) cutoff_settler: Option<Rc<dyn Fn(&PropertyTable, PropertyId) -> CutoffEvaluation>>,
}

impl PropertyData {
    fn typed_data<T: 'static>(&mut self) -> &mut TypedPropertyData<T> {
        self.typed_data
            .downcast_mut::<TypedPropertyData<T>>()
            .unwrap_or_else(|| panic!("Failed to downcast to TypedPropertyData<{}>. The actual type does not match the expected type.", std::any::type_name::<T>()))
    }
}

// Type-specialized payload for one `LocalProperty<T>` table entry.
pub struct TypedPropertyData<T> {
    value: T,
    shared: Option<std::sync::Weak<super::shared_property::SharedCell<T>>>,
    publisher: Option<Rc<dyn Fn(&T)>>,
    transition_manager: Option<TransitionManager<T>>,
    // Specialization data (computed/literal etc)
    property_type: PropertyType<T>,
}

// Specialization data only needed for different kinds of properties
#[derive(Clone)]
pub(crate) enum PropertyType<T> {
    Literal,
    Computed {
        // Information needed to recompute on change
        evaluator: Rc<dyn Fn() -> T>,
        cutoff: Option<Cutoff<T>>,
    },
}

#[derive(Clone)]
pub(crate) struct Cutoff<T> {
    pub(super) predicate: Rc<dyn Fn(&T, &T) -> bool>,
    pub(super) initialized: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CutoffEvaluation {
    NotCutoff,
    Initialized,
    Suppressed,
    Propagated,
}

// Main propertytable, containing data associated with each property
#[derive(Default)]
pub(crate) struct PropertyTable {
    // Main property table containing property data
    // Box<dyn Any> is of type Box<Entry<T>> where T is the proptype
    pub(crate) property_map: RefCell<SlotMap<PropertyId, Entry>>,
    #[cfg(debug_assertions)]
    debug_names: RefCell<SparseSecondaryMap<PropertyId, String>>,
    effect_debug_names: RefCell<HashMap<PropertyId, String>>,
    effect_properties: RefCell<HashSet<PropertyId>>,
    queued_effects: RefCell<VecDeque<PropertyId>>,
    queued_effect_set: RefCell<HashSet<PropertyId>>,
    queued_cutoffs: RefCell<VecDeque<PropertyId>>,
    queued_cutoff_set: RefCell<HashSet<PropertyId>>,
}

// Reference-counted slotmap entry for one property id.
pub struct Entry {
    ref_count: usize,
    data: Option<PropertyData>,
}

impl PropertyTable {
    pub(super) fn set_shared<T: super::SharedPropertyValue>(
        &self,
        id: PropertyId,
        shared: std::sync::Weak<super::shared_property::SharedCell<T>>,
        publisher: Rc<dyn Fn(&T)>,
    ) {
        self.with_property_data_mut(id, |data| {
            let typed = data.typed_data::<T>();
            typed.shared = Some(shared);
            typed.publisher = Some(publisher);
        });
    }

    pub(super) fn clear_shared<T: PropertyValue>(&self, id: PropertyId) {
        self.with_property_data_mut(id, |data| {
            let typed = data.typed_data::<T>();
            typed.shared = None;
            typed.publisher = None;
        });
    }

    pub(super) fn shared_storage<T: super::SharedPropertyValue>(
        &self,
        id: PropertyId,
    ) -> Option<std::sync::Arc<super::shared_property::SharedCell<T>>> {
        self.with_property_data_mut(id, |data| data.typed_data::<T>().shared.as_ref()?.upgrade())
    }

    fn publish_stored<T: PropertyValue>(&self, id: PropertyId) {
        let publication = self.with_property_data_mut(id, |data| {
            let typed = data.typed_data::<T>();
            Some((typed.publisher.as_ref()?.clone(), typed.value.clone()))
        });
        if let Some((publish, value)) = publication {
            publish(&value);
        }
    }

    pub(crate) fn has_value_type<T: PropertyValue>(&self, id: PropertyId) -> bool {
        self.with_property_data(id, |data| data.typed_data.is::<TypedPropertyData<T>>())
    }

    // Main function to get access to a value inside of a property.
    // Makes sure the value is up to date before returning in the case
    // of computed properties.
    pub fn get_value<T: PropertyValue>(&self, id: PropertyId) -> T {
        self.update_value::<T>(id);
        self.with_property_data_mut(id, |property_data| {
            property_data.typed_data::<T>().value.clone()
        })
    }

    // Reads a property value by reference after updating dirty dependencies.
    pub fn read_value<T: PropertyValue, V>(&self, id: PropertyId, f: impl FnOnce(&T) -> V) -> V {
        self.update_value::<T>(id);
        self.with_property_data_mut(id, |property_data| {
            f(&property_data.typed_data::<T>().value)
        })
    }

    // Main function to set a value of a property.
    // NOTE: This always assumes the underlying data was changed, and marks
    // it and its dependents as dirty irrespective of actual modification
    pub fn set_value<T: PropertyValue>(&self, id: PropertyId, new_val: T) {
        self.import_shared(id, new_val);
        self.publish_stored::<T>(id);
    }

    // Importing must not echo a worker publication back into shared storage.
    pub(super) fn import_shared<T: PropertyValue>(&self, id: PropertyId, new_val: T) {
        self.with_property_data_mut(id, |property_data: &mut PropertyData| {
            let typed_data = property_data.typed_data();
            typed_data.value = new_val;
            property_data.dirty = false;
        });
        self.dirtify_outbound(id);
    }

    pub fn invalidate(&self, id: PropertyId) {
        let (newly_dirty, is_cutoff) = self.with_property_data_mut(id, |property_data| {
            if property_data.dirty {
                (false, property_data.cutoff_settler.is_some())
            } else {
                property_data.dirty = true;
                (true, property_data.cutoff_settler.is_some())
            }
        });
        if newly_dirty {
            if is_cutoff {
                self.enqueue_cutoff(id);
            } else {
                self.enqueue_effect_if_registered(id);
                self.dirtify_outbound(id);
            }
        }
    }

    // Adds a new untyped property entry
    pub fn add_entry<T: PropertyValue>(
        &self,
        start_val: T,
        inbound: Vec<PropertyId>,
        data: PropertyType<T>,
        debug_name: Option<&str>,
    ) -> PropertyId {
        #[cfg(not(debug_assertions))]
        let _ = debug_name;

        let is_cutoff = matches!(
            &data,
            PropertyType::Computed {
                cutoff: Some(_),
                ..
            }
        );
        let cutoff_settler = is_cutoff.then(|| {
            Rc::new(|table: &PropertyTable, id| table.update_value::<T>(id))
                as Rc<dyn Fn(&PropertyTable, PropertyId) -> CutoffEvaluation>
        });

        let id = {
            let Ok(mut sm) = self.property_map.try_borrow_mut() else {
                #[cfg(debug_assertions)]
                panic!(
                    "couldn't create new property \"{}\"- table already borrowed",
                    debug_name.unwrap_or("<no name>")
                );
                #[cfg(not(debug_assertions))]
                panic!("couldn't create new property - table already borrowed");
            };
            let entry = Entry {
                ref_count: 1,
                data: Some(PropertyData {
                    owner_graph: super::shared_graph::current_graph_id(),
                    owner_scope: super::shared_graph::current_binding_scope(),
                    inbound,
                    dirty: true,
                    typed_data: Box::new(TypedPropertyData {
                        value: start_val,
                        shared: None,
                        publisher: None,
                        property_type: data,
                        transition_manager: None,
                    }),
                    outbound: Vec::with_capacity(0),
                    cutoff_settler,
                }),
            };
            sm.insert(entry)
        };
        #[cfg(debug_assertions)]
        {
            if let Some(name) = debug_name {
                self.debug_names.borrow_mut().insert(id, name.to_owned());
            }
        }
        self.connect_inbound(id);
        id
    }

    // Add a transition to the transitionmanager, making the value slowly change over time
    // Currently this only transitions the literal value of the property (and updates dependents accordingly)
    // This has no special interactions with computed properties
    pub fn transition<T: PropertyValue>(
        &self,
        id: PropertyId,
        transition: TransitionQueueEntry<T>,
        overwrite: bool,
    ) {
        let mut should_reconnect_inbound = false;
        let (time_id, curr_time) = PROPERTY_TIME.with_borrow(|time| (time.untyped.id, time.get()));
        let (millis_id, curr_millis) =
            PROPERTY_MILLIS.with_borrow(|time| (time.untyped.id, time.get()));
        self.with_property_data_mut(id, |property_data: &mut PropertyData| {
            let typed_data = property_data.typed_data::<T>();
            let transition_manager = typed_data.transition_manager.get_or_insert_with(|| {
                TransitionManager::new(typed_data.value.clone(), curr_time, curr_millis)
            });
            if overwrite {
                transition_manager.reset_transitions(curr_time, curr_millis);
            }
            transition_manager.push_transition(transition);
            if !property_data.inbound.contains(&time_id) {
                should_reconnect_inbound = true;
                property_data.inbound.push(time_id);
            }
            if !property_data.inbound.contains(&millis_id) {
                should_reconnect_inbound = true;
                property_data.inbound.push(millis_id);
            }
        });
        if should_reconnect_inbound {
            self.disconnect_inbound(id);
            self.connect_inbound(id);
        }
    }

    pub fn cancel_transitions<T: PropertyValue>(&self, id: PropertyId) {
        let (time_id, curr_time) = PROPERTY_TIME.with_borrow(|time| (time.untyped.id, time.get()));
        let (millis_id, curr_millis) =
            PROPERTY_MILLIS.with_borrow(|time| (time.untyped.id, time.get()));
        let has_transition = self.with_property_data(id, |property_data| {
            property_data
                .typed_data
                .downcast_ref::<TypedPropertyData<T>>()
                .expect("property type should match")
                .transition_manager
                .is_some()
        });
        if !has_transition {
            return;
        }

        self.disconnect_inbound(id);
        let value_changed = self.with_property_data_mut(id, |property_data| {
            let typed_data = property_data.typed_data::<T>();
            let current_value = typed_data
                .transition_manager
                .as_mut()
                .and_then(|manager| manager.compute_eased_value(curr_time, curr_millis));
            let value_changed = current_value.is_some();
            if let Some(current_value) = current_value {
                typed_data.value = current_value;
            }
            typed_data.transition_manager = None;
            property_data
                .inbound
                .retain(|dependency| *dependency != time_id && *dependency != millis_id);
            property_data.dirty = false;
            value_changed
        });
        self.connect_inbound(id);

        if value_changed {
            self.dirtify_outbound(id);
        }
    }

    // Gives mutable access to a entry in the property table
    // WARNING: this function is dangerous, f can not drop, create, set, get
    // or in any other way modify the global property table or this will panic
    // with multiple mutable borrows. Letting f contain any form of userland
    // code is NOT a good idea.
    fn with_entry_mut<V>(&self, id: PropertyId, f: impl FnOnce(&mut Entry) -> V) -> V {
        let mut sm = self.property_map.borrow_mut();
        let data = sm.get_mut(id).unwrap();
        let return_value = f(data);
        return_value
    }

    // Allows mutable access to the data associated with a property id.
    // WARNING while this method is being run, the entry corresponding to id
    // is not present in the table, and methods such as .get(), .set(), and
    // possibly others on the property with the id parameter bellow will panic.
    pub fn with_property_data_mut<V>(
        &self,
        id: PropertyId,
        f: impl FnOnce(&mut PropertyData) -> V,
    ) -> V {
        // take the value out of the table
        let mut property_data = self.with_entry_mut(id, |entry| {
            entry
                .data
                .take()
                .expect("property data should not have already been taken")
        });

        // run f, without table being borrowed
        // NOTE: need to make sure with_property_data_mut is not run recursively
        // with the same id
        let res = f(&mut property_data);

        // return value to the table that was taken
        self.with_entry_mut(id, |entry| {
            entry.data = Some(property_data);
        });

        res
    }

    // Allows access to the data associated with a property id.
    // WARNING while this method is being run, the entry corresponding to id
    // is not present in the table, and methods such as .get(), .set(), and
    // possibly others on the property with the id parameter bellow will panic.
    pub fn with_property_data<V>(&self, id: PropertyId, f: impl FnOnce(&PropertyData) -> V) -> V {
        self.with_property_data_mut(id, |property_data| f(&*property_data))
    }

    // Increase the ref count of a property
    pub fn increase_ref_count(&self, id: PropertyId) -> usize {
        self.with_entry_mut(id, |entry| {
            entry.ref_count += 1;
            entry.ref_count
        })
    }

    // Decrease the ref count of a property
    pub fn decrease_ref_count(&self, id: PropertyId) -> usize {
        self.with_entry_mut(id, |entry| {
            entry.ref_count -= 1;
            entry.ref_count
        })
    }

    // Replaces the way the source parameters property is being
    // computed / its value to the way target does.
    // NOTE: source_id and target_id need to both contain
    // the type T, or else this panics
    pub fn replace_property_keep_outbound_connections<T: PropertyValue>(
        &self,
        source_id: PropertyId,
        target_id: PropertyId,
    ) {
        if source_id == target_id {
            return;
        }

        // Reconnect even identical dependencies: their outbound order affects
        // effect scheduling. Only the vector's allocation is reusable.
        self.disconnect_inbound(source_id);

        // copy necessary internal state from target to source
        self.with_property_data_mut(source_id, |source_property_data| {
            self.with_property_data_mut(target_id, |target_property_data| {
                // Copy over inbound, dirty state, and current value to source
                source_property_data
                    .inbound
                    .clone_from(&target_property_data.inbound);
                // Literal replacement is already resolved. Mark it clean so
                // the new authored value publishes below, without evaluating
                // computations eagerly or echoing an old projection snapshot.
                source_property_data.dirty = target_property_data.dirty
                    && !matches!(
                        target_property_data.typed_data::<T>().property_type,
                        PropertyType::Literal
                    );
                source_property_data.cutoff_settler = target_property_data.cutoff_settler.clone();
                source_property_data.owner_graph = target_property_data.owner_graph;
                source_property_data.owner_scope = target_property_data.owner_scope.clone();
                let source_typed = source_property_data.typed_data::<T>();
                let target_typed = target_property_data.typed_data::<T>();
                source_typed.value = target_typed.value.clone();
                source_typed.property_type = target_typed.property_type.clone();
                if target_property_data.dirty {
                    if let PropertyType::Computed {
                        cutoff: Some(cutoff),
                        ..
                    } = &mut source_typed.property_type
                    {
                        cutoff.initialized = false;
                    }
                }
            });
        });

        // Reconnect the new dependencies and enqueue any dirty upstream cutoffs.
        self.connect_inbound(source_id);

        if self.is_registered_effect(source_id) && self.is_cutoff(source_id) {
            panic!("cutoff properties cannot be registered as effects");
        }
        if self.is_cutoff(source_id) && self.is_dirty(source_id) {
            self.enqueue_cutoff(source_id);
        }

        // make sure dependencies of self
        // know that something has changed
        self.dirtify_outbound(source_id);

        #[cfg(debug_assertions)]
        {
            // overwrite with more descriptive name
            let target_name = self.debug_name(target_id);
            let mut names = self.debug_names.borrow_mut();
            names.insert(source_id, format!("{}", target_name));
        }

        self.enqueue_effect_if_registered(source_id);
        if !self.is_dirty(source_id) {
            self.publish_stored::<T>(source_id);
        }
    }

    // re-computes the value if dirty
    pub fn update_value<T: PropertyValue>(&self, id: PropertyId) -> CutoffEvaluation {
        let mut remove_dep_from_literal = false;
        let mut publish_literal = false;
        let evaluator = self.with_property_data_mut(id, |property_data| {
            //short circuit if the value is still up to date
            if property_data.dirty == false {
                return None;
            }
            property_data.dirty = false;
            let typed_data = property_data.typed_data::<T>();
            match &mut typed_data.property_type {
                PropertyType::Computed { evaluator, cutoff } => Some((
                    Rc::clone(&evaluator),
                    cutoff.as_ref().map(|cutoff| {
                        (
                            Rc::clone(&cutoff.predicate),
                            cutoff.initialized,
                            typed_data.value.clone(),
                        )
                    }),
                )),
                PropertyType::Literal => {
                    let tm = typed_data.transition_manager.as_mut()?;
                    let curr_time = PROPERTY_TIME.with_borrow(|time| time.get());
                    let curr_millis = PROPERTY_MILLIS.with_borrow(|time| time.get());
                    let value = tm.compute_eased_value(curr_time, curr_millis);
                    if let Some(interp_value) = value {
                        typed_data.value = interp_value;
                        publish_literal = true;
                    } else {
                        //transition must be over, let's remove dependencies
                        remove_dep_from_literal = true;
                        typed_data.transition_manager = None;
                    }
                    None
                }
            }
        });

        if remove_dep_from_literal {
            self.disconnect_inbound(id);
            self.with_property_data_mut(id, |property_data| {
                property_data.inbound.clear();
            });
        }

        if publish_literal {
            self.publish_stored::<T>(id);
        }

        if let Some((evaluator, cutoff)) = evaluator {
            // WARNING: the evaluator should not be run while the table is in
            // an invalid state (borrowed, in with_property_data closure, etc.)
            // as this function is provided by a user of the property system and
            // can do arbitrary sets/ gets/drops etc (that need the prop data)
            let new_value = { evaluator() };
            // Cutoff predicates are API callbacks too, so run them while the
            // property is present in the table for the same reason as evaluators.
            let cutoff_evaluation = match cutoff.as_ref() {
                None => CutoffEvaluation::NotCutoff,
                Some((_, false, _)) => CutoffEvaluation::Initialized,
                Some((predicate, true, old_value)) if predicate(old_value, &new_value) => {
                    CutoffEvaluation::Suppressed
                }
                Some(_) => CutoffEvaluation::Propagated,
            };
            self.with_property_data_mut(id, |property_data| {
                let typed_data = property_data.typed_data();
                if let PropertyType::Computed {
                    cutoff: Some(cutoff),
                    ..
                } = &mut typed_data.property_type
                {
                    cutoff.initialized = true;
                }

                if cutoff_evaluation != CutoffEvaluation::Suppressed {
                    typed_data.value = new_value;
                }
            });

            if cutoff_evaluation == CutoffEvaluation::Propagated {
                self.dirtify_outbound(id);
            }
            if cutoff_evaluation != CutoffEvaluation::Suppressed {
                self.publish_stored::<T>(id);
            }
            cutoff_evaluation
        } else {
            CutoffEvaluation::NotCutoff
        }
    }

    // drop a properties underlying data, making any subsequent calls invalid by panic
    pub fn remove_entry(&self, id: PropertyId) {
        let res = {
            self.unregister_effect(id);
            self.queued_cutoff_set.borrow_mut().remove(&id);
            self.disconnect_outbound(id);
            self.disconnect_inbound(id);
            let Ok(mut sm) = self.property_map.try_borrow_mut() else {
                #[cfg(debug_assertions)]
                panic!(
                    "failed to remove property \"{}\" - propertytable already borrowed",
                    self.debug_name(id),
                );
                #[cfg(not(debug_assertions))]
                panic!("failed to remove property - propertytable already borrowed");
            };
            sm.remove(id).expect("tried to remove non-existent prop")
        };
        drop(res);
    }

    // Returns a human-readable name for diagnostics, falling back to the raw id.
    #[cfg(debug_assertions)]
    pub fn debug_name(&self, id: PropertyId) -> String {
        self.debug_names
            .borrow()
            .get(id)
            .as_ref()
            .map(|s| s.as_str())
            .unwrap_or("<NO DEBUG NAME>")
            .to_owned()
    }

    // Returns the number of live property-table slots.
    pub(crate) fn total_properties_count(&self) -> usize {
        self.property_map.borrow().len()
    }

    pub(crate) fn register_effect(&self, id: PropertyId) {
        self.register_effect_with_name(id, None);
    }

    pub(crate) fn register_effect_with_name(&self, id: PropertyId, debug_name: Option<&str>) {
        if self.is_cutoff(id) {
            panic!("cutoff properties cannot be registered as effects");
        }
        if let Some(debug_name) = debug_name {
            self.effect_debug_names
                .borrow_mut()
                .insert(id, debug_name.to_owned());
        }
        self.effect_properties.borrow_mut().insert(id);
        self.enqueue_effect_if_registered(id);
    }

    pub(crate) fn drain_effects(&self, max_iterations: usize) -> usize {
        let mut work_ran = 0;
        while work_ran < max_iterations {
            if let Some(id) = self.pop_queued_cutoff() {
                if !self.has_live_entry(id)
                    || !self.is_cutoff(id)
                    || !self.is_dirty(id)
                    || !self.work_enabled(id)
                {
                    continue;
                }
                let settler = self.cutoff_settler(id);
                settler(self, id);
                work_ran += 1;
                continue;
            }

            let Some(id) = self.pop_queued_effect() else {
                break;
            };
            if !self.is_registered_effect(id) || !self.has_live_entry(id) {
                continue;
            }
            let dirty = self.with_property_data(id, |property_data| property_data.dirty);
            if !self.work_enabled(id) {
                continue;
            }
            if dirty {
                self.update_value::<()>(id);
                work_ran += 1;
            }
        }
        work_ran
    }

    pub(crate) fn drain_effects_with_report(&self, max_iterations: usize) -> EffectDrainReport {
        let mut report = EffectDrainReport::default();
        let mut effect_counts = HashMap::new();
        let mut cutoff_counts = HashMap::new();

        let mut work_ran = 0;
        while work_ran < max_iterations {
            if let Some(id) = self.pop_queued_cutoff() {
                if !self.has_live_entry(id)
                    || !self.is_cutoff(id)
                    || !self.is_dirty(id)
                    || !self.work_enabled(id)
                {
                    continue;
                }
                let cutoff_name = self.debug_name_for_diagnostics(id);
                let cutoff_category = cutoff_name
                    .split_once(" (")
                    .map(|(category, _)| category)
                    .unwrap_or(&cutoff_name)
                    .to_owned();
                let settler = self.cutoff_settler(id);
                match settler(self, id) {
                    CutoffEvaluation::Suppressed => report.cutoffs_suppressed += 1,
                    CutoffEvaluation::Propagated => report.cutoffs_propagated += 1,
                    CutoffEvaluation::NotCutoff | CutoffEvaluation::Initialized => {}
                }
                report.cutoffs_evaluated += 1;
                work_ran += 1;
                *cutoff_counts.entry(cutoff_category).or_insert(0) += 1;
                continue;
            }

            let Some(id) = self.pop_queued_effect() else {
                break;
            };
            report.popped += 1;

            if !self.is_registered_effect(id) {
                report.skipped_unregistered += 1;
                continue;
            }
            if !self.has_live_entry(id) {
                report.skipped_missing += 1;
                continue;
            }

            if !self.work_enabled(id) {
                continue;
            }
            let dirty = self.with_property_data(id, |property_data| property_data.dirty);
            if dirty {
                let effect_name = self.debug_name_for_diagnostics(id);
                self.update_value::<()>(id);
                report.ran += 1;
                work_ran += 1;
                *effect_counts.entry(effect_name).or_insert(0) += 1;
            } else {
                report.skipped_clean += 1;
            }
        }

        report.remaining = self.queued_effects.borrow().len();
        report.remaining_cutoffs = self.queued_cutoffs.borrow().len();
        report.budget_exhausted =
            work_ran == max_iterations && (report.remaining > 0 || report.remaining_cutoffs > 0);
        report.top_effects = effect_counts.into_iter().collect();
        report
            .top_effects
            .sort_by(|(left_name, left_count), (right_name, right_count)| {
                right_count
                    .cmp(left_count)
                    .then_with(|| left_name.cmp(right_name))
            });
        report.top_effects.truncate(8);
        report.top_cutoffs = cutoff_counts.into_iter().collect();
        report
            .top_cutoffs
            .sort_by(|(left_name, left_count), (right_name, right_count)| {
                right_count
                    .cmp(left_count)
                    .then_with(|| left_name.cmp(right_name))
            });
        report.top_cutoffs.truncate(8);
        report
    }

    pub(crate) fn enqueue_effect_if_registered(&self, id: PropertyId) {
        if self.is_registered_effect(id) {
            self.enqueue_effect(id);
        }
    }

    fn enqueue_effect(&self, id: PropertyId) {
        let mut queued_set = self.queued_effect_set.borrow_mut();
        if queued_set.insert(id) {
            self.queued_effects.borrow_mut().push_back(id);
        }
    }

    fn pop_queued_effect(&self) -> Option<PropertyId> {
        let id = self.pop_owned_work(&self.queued_effects)?;
        self.queued_effect_set.borrow_mut().remove(&id);
        Some(id)
    }

    pub(crate) fn enqueue_cutoff(&self, id: PropertyId) {
        let mut queued_set = self.queued_cutoff_set.borrow_mut();
        if queued_set.insert(id) {
            self.queued_cutoffs.borrow_mut().push_back(id);
        }
    }

    fn pop_queued_cutoff(&self) -> Option<PropertyId> {
        let id = self.pop_owned_work(&self.queued_cutoffs)?;
        self.queued_cutoff_set.borrow_mut().remove(&id);
        Some(id)
    }

    fn pop_owned_work(&self, queue: &RefCell<VecDeque<PropertyId>>) -> Option<PropertyId> {
        let owner = super::shared_graph::current_graph_id();
        let mut queue = queue.borrow_mut();
        let position = queue.iter().position(|id| {
            let map = self.property_map.borrow();
            let graph = map
                .get(*id)
                .and_then(|entry| entry.data.as_ref())
                .and_then(|data| data.owner_graph);
            owner.is_none() || graph.is_none() || graph == owner
        })?;
        queue.remove(position)
    }

    fn work_enabled(&self, id: PropertyId) -> bool {
        self.with_property_data(id, |data| {
            data.owner_scope.as_ref().map_or(true, |scope| {
                scope.upgrade().is_some_and(|scope| !scope.closed.get())
            })
        })
    }

    fn unregister_effect(&self, id: PropertyId) {
        self.effect_properties.borrow_mut().remove(&id);
        self.effect_debug_names.borrow_mut().remove(&id);
        self.queued_effect_set.borrow_mut().remove(&id);
    }

    fn is_registered_effect(&self, id: PropertyId) -> bool {
        self.effect_properties.borrow().contains(&id)
    }

    pub(crate) fn is_cutoff(&self, id: PropertyId) -> bool {
        self.with_property_data(id, |data| data.cutoff_settler.is_some())
    }

    fn is_dirty(&self, id: PropertyId) -> bool {
        self.with_property_data(id, |data| data.dirty)
    }

    fn cutoff_settler(
        &self,
        id: PropertyId,
    ) -> Rc<dyn Fn(&PropertyTable, PropertyId) -> CutoffEvaluation> {
        self.with_property_data(id, |data| {
            data.cutoff_settler
                .as_ref()
                .expect("queued cutoff property must have a settler")
                .clone()
        })
    }

    pub(super) fn has_live_entry(&self, id: PropertyId) -> bool {
        self.property_map
            .borrow()
            .get(id)
            .and_then(|entry| entry.data.as_ref())
            .is_some()
    }

    fn debug_name_for_diagnostics(&self, id: PropertyId) -> String {
        if let Some(name) = self.effect_debug_names.borrow().get(&id) {
            return name.clone();
        }

        #[cfg(debug_assertions)]
        {
            if let Some(name) = self.debug_names.borrow().get(id) {
                return name.clone();
            }
        }

        format!("{id:?}")
    }

    pub(crate) fn outbound_debug_names(&self, id: PropertyId) -> Vec<String> {
        self.with_property_data(id, |data| {
            data.outbound
                .iter()
                .copied()
                .filter(|outbound_id| self.has_live_entry(*outbound_id))
                .map(|outbound_id| self.debug_name_for_diagnostics(outbound_id))
                .collect()
        })
    }

    pub(crate) fn has_direct_outbound(
        &self,
        source_id: PropertyId,
        outbound_id: PropertyId,
    ) -> bool {
        self.with_property_data(source_id, |data| data.outbound.contains(&outbound_id))
    }
}