reinhardt-core 0.4.0-alpha.2

Core components for Reinhardt framework
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! Scope-owned storage for arena-backed reactive handles.

use core::any::Any;
use core::cell::{Cell, RefCell};
use core::fmt;
use core::marker::PhantomData;
use core::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};

extern crate alloc;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;

use super::runtime::{NodeId, run_without_observer, try_with_runtime};

/// Identifier for a live reactive scope.
///
/// The identifier records its owner thread so deferred work cannot enter an
/// unrelated worker-local scope that happens to have the same local counter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ScopeId {
	value: u64,
	owner_thread: std::thread::ThreadId,
	owner_thread_index: u32,
}

impl PartialOrd for ScopeId {
	fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for ScopeId {
	fn cmp(&self, other: &Self) -> core::cmp::Ordering {
		(self.owner_thread_index, self.value).cmp(&(other.owner_thread_index, other.value))
	}
}

/// Generational key for a node stored inside a reactive scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeKey {
	scope: ScopeId,
	index: usize,
	generation: u32,
	node_id: NodeId,
	kind: NodeKind,
	owner_thread: std::thread::ThreadId,
	_thread_bound: PhantomData<Rc<()>>,
}

/// Kind of reactive node stored in a scope arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NodeKind {
	/// Signal source node.
	Signal,
	/// Memoized derived node.
	Memo,
	/// Effect observer node.
	Effect,
}

/// Errors produced by scope-owned reactive node access.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReactiveScopeError {
	/// An operation required an active scope but none was present.
	NoActiveScope {
		/// Operation that attempted to access the active scope.
		operation: &'static str,
	},
	/// A disposed scope was accessed.
	DisposedScope {
		/// Disposed scope identifier.
		scope: ScopeId,
	},
	/// A node key points at disposed or stale storage.
	DisposedNode {
		/// Kind of node being accessed.
		kind: NodeKind,
		/// Scope that owned the node.
		scope: ScopeId,
		/// Arena slot index.
		index: usize,
		/// Generation captured in the key.
		expected_generation: u32,
		/// Current slot generation, if the slot still exists.
		actual_generation: Option<u32>,
	},
	/// A node key was read as the wrong concrete value type.
	TypeMismatch {
		/// Kind of node being accessed.
		kind: NodeKind,
		/// Requested Rust type name.
		type_name: &'static str,
	},
	/// A node was accessed while it was mutably borrowed.
	BorrowConflict {
		/// Kind of node being accessed.
		kind: NodeKind,
		/// Scope that owns the node.
		scope: ScopeId,
		/// Arena slot index.
		index: usize,
	},
	/// A key was accessed from a thread other than the one that owns its scope.
	WrongThread {
		/// Scope that owns the key.
		scope: ScopeId,
		/// Thread that created the key.
		owner_thread: std::thread::ThreadId,
		/// Thread that attempted to access the key.
		current_thread: std::thread::ThreadId,
	},
}

impl fmt::Display for ReactiveScopeError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::NoActiveScope { operation } => write!(
				f,
				"{operation} requires an active ReactiveScope; wrap low-level code in ReactiveScope::run(...) or use a Reinhardt Pages entrypoint"
			),
			Self::DisposedScope { scope } => {
				write!(f, "disposed reactive scope access: scope={scope:?}")
			}
			Self::DisposedNode {
				kind,
				scope,
				index,
				expected_generation,
				actual_generation,
			} => write!(
				f,
				"disposed reactive node access: kind={kind:?}, scope={scope:?}, index={index}, expected_generation={expected_generation}, actual_generation={actual_generation:?}"
			),
			Self::TypeMismatch { kind, type_name } => {
				write!(
					f,
					"reactive node type mismatch: kind={kind:?}, requested={type_name}"
				)
			}
			Self::BorrowConflict { kind, scope, index } => write!(
				f,
				"reactive node borrow conflict: kind={kind:?}, scope={scope:?}, index={index}"
			),
			Self::WrongThread {
				scope,
				owner_thread,
				current_thread,
			} => write!(
				f,
				"reactive scope accessed from a different thread: scope={scope:?}, owner_thread={owner_thread:?}, current_thread={current_thread:?}"
			),
		}
	}
}

impl std::error::Error for ReactiveScopeError {}

struct CoreSlot {
	generation: u32,
	kind: NodeKind,
	node_id: NodeId,
	dirty: Cell<bool>,
	disposed: Cell<bool>,
	value: RefCell<Option<Box<dyn Any>>>,
}

struct ScopeState {
	slots: Vec<Rc<CoreSlot>>,
	cleanup: Vec<Box<dyn FnOnce()>>,
	after_node_cleanup: Vec<Box<dyn FnOnce()>>,
}

impl ScopeState {
	fn new() -> Self {
		Self {
			slots: Vec::new(),
			cleanup: Vec::new(),
			after_node_cleanup: Vec::new(),
		}
	}
}

static NEXT_SCOPE_OWNER_INDEX: AtomicU32 = AtomicU32::new(1);

thread_local! {
	static NEXT_SCOPE_ID: Cell<u64> = const { Cell::new(1) };
	static SCOPE_OWNER_INDEX: u32 = NEXT_SCOPE_OWNER_INDEX.fetch_add(1, AtomicOrdering::Relaxed);
	static ACTIVE_SCOPES: RefCell<Vec<ScopeId>> = const { RefCell::new(Vec::new()) };
	static SCOPES: RefCell<BTreeMap<ScopeId, ScopeState>> = const { RefCell::new(BTreeMap::new()) };
}

/// Owner for reactive nodes allocated during a scoped execution.
///
/// A scope is thread-affine and cannot be sent or shared across threads.
pub struct ReactiveScope {
	id: ScopeId,
	disposed: Cell<bool>,
	_thread_bound: PhantomData<Rc<()>>,
}

impl ReactiveScope {
	/// Create an empty reactive scope.
	pub fn new() -> Self {
		let id = NEXT_SCOPE_ID.with(|next| {
			let id = ScopeId {
				value: next.get(),
				owner_thread: std::thread::current().id(),
				owner_thread_index: SCOPE_OWNER_INDEX.with(|index| *index),
			};
			next.set(next.get() + 1);
			id
		});
		SCOPES.with(|scopes| {
			scopes.borrow_mut().insert(id, ScopeState::new());
		});
		Self {
			id,
			disposed: Cell::new(false),
			_thread_bound: PhantomData,
		}
	}

	/// Return this scope's identifier.
	pub fn id(&self) -> ScopeId {
		self.id
	}

	/// Run a closure inside a fresh reactive scope.
	pub fn run<R>(f: impl FnOnce() -> R) -> R {
		let scope = Self::new();
		scope.enter(f)
	}

	/// Run a closure with this scope as the current active scope.
	pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
		enter_scope(self.id, f).unwrap_or_else(|err| panic!("{err}"))
	}

	/// Dispose this scope and run registered cleanup callbacks.
	pub fn dispose(&self) {
		if self.disposed.replace(true) {
			return;
		}
		dispose_scope(self.id);
	}
}

impl Default for ReactiveScope {
	fn default() -> Self {
		Self::new()
	}
}

impl Drop for ReactiveScope {
	fn drop(&mut self) {
		if self.disposed.replace(true) {
			return;
		}

		// A scope retained in thread-local storage can outlive the `SCOPES`
		// thread-local during process or worker teardown.
		let _ = SCOPES.try_with(|_| dispose_scope(self.id));
	}
}

/// Return the current active scope identifier, if any.
pub fn current_scope_id() -> Option<ScopeId> {
	ACTIVE_SCOPES
		.try_with(|active| active.borrow().last().copied())
		.unwrap_or(None)
}

/// Run a closure with an existing live scope active.
///
/// This is intended for deferred callbacks that retain a [`ScopeId`] after
/// their creating render turn has completed. The caller must handle a disposed
/// scope, because the scope can be torn down before a deferred callback runs.
pub fn enter_scope<R>(scope: ScopeId, f: impl FnOnce() -> R) -> Result<R, ReactiveScopeError> {
	let current_thread = std::thread::current().id();
	if scope.owner_thread != current_thread {
		return Err(ReactiveScopeError::WrongThread {
			scope,
			owner_thread: scope.owner_thread,
			current_thread,
		});
	}

	let exists = SCOPES
		.try_with(|scopes| scopes.borrow().contains_key(&scope))
		.unwrap_or(false);
	if !exists {
		return Err(ReactiveScopeError::DisposedScope { scope });
	}

	ACTIVE_SCOPES
		.try_with(|active| active.borrow_mut().push(scope))
		.map_err(|_| ReactiveScopeError::DisposedScope { scope })?;
	struct PopScope;
	impl Drop for PopScope {
		fn drop(&mut self) {
			let _ = ACTIVE_SCOPES.try_with(|active| {
				active.borrow_mut().pop();
			});
		}
	}
	let _guard = PopScope;
	Ok(f())
}

/// Return the current active scope identifier or panic with diagnostics.
pub fn active_scope_id() -> ScopeId {
	require_active_scope("active_scope_id")
}

/// Return the current active scope identifier or panic for the given operation.
pub fn require_active_scope(_operation: &'static str) -> ScopeId {
	current_scope_id().unwrap_or_else(|| {
		panic!(
			"{}",
			ReactiveScopeError::NoActiveScope {
				operation: _operation,
			}
		);
	})
}

pub(crate) fn allocate_node<T: 'static>(kind: NodeKind, value: T) -> NodeKey {
	let scope = require_active_scope("reactive node creation");
	SCOPES.with(|scopes| {
		let mut scopes = scopes.borrow_mut();
		let state = scopes
			.get_mut(&scope)
			.expect("active ReactiveScope must have scope state");
		let index = state.slots.len();
		let node_id = NodeId::new();
		let generation = 1;
		state.slots.push(Rc::new(CoreSlot {
			generation,
			kind,
			node_id,
			dirty: Cell::new(false),
			disposed: Cell::new(false),
			value: RefCell::new(Some(Box::new(value))),
		}));
		NodeKey {
			scope,
			index,
			generation,
			node_id,
			kind,
			owner_thread: std::thread::current().id(),
			_thread_bound: PhantomData,
		}
	})
}

#[cfg(test)]
pub(crate) fn allocate_empty_node(kind: NodeKind) -> NodeKey {
	allocate_node(kind, ())
}

#[cfg(test)]
pub(crate) fn lookup_empty_node(key: NodeKey) -> Result<(), ReactiveScopeError> {
	with_node::<(), _>(key, |_| ())
}

pub(crate) fn with_node<T: 'static, R>(
	key: NodeKey,
	f: impl FnOnce(&T) -> R,
) -> Result<R, ReactiveScopeError> {
	let slot = lookup_node_slot(key)?;
	ensure_node_is_live(key, &slot)?;
	let value = slot
		.value
		.try_borrow()
		.map_err(|_| ReactiveScopeError::BorrowConflict {
			kind: slot.kind,
			scope: key.scope,
			index: key.index,
		})?;
	let value = value
		.as_ref()
		.and_then(|value| value.downcast_ref::<T>())
		.ok_or(ReactiveScopeError::TypeMismatch {
			kind: slot.kind,
			type_name: core::any::type_name::<T>(),
		})?;
	Ok(f(value))
}

pub(crate) fn with_node_mut<T: 'static, R>(
	key: NodeKey,
	f: impl FnOnce(&mut T) -> R,
) -> Result<R, ReactiveScopeError> {
	let slot = lookup_node_slot(key)?;
	ensure_node_is_live(key, &slot)?;
	let mut value =
		slot.value
			.try_borrow_mut()
			.map_err(|_| ReactiveScopeError::BorrowConflict {
				kind: slot.kind,
				scope: key.scope,
				index: key.index,
			})?;
	let value = value
		.as_mut()
		.and_then(|value| value.downcast_mut::<T>())
		.ok_or(ReactiveScopeError::TypeMismatch {
			kind: slot.kind,
			type_name: core::any::type_name::<T>(),
		})?;
	Ok(f(value))
}

fn lookup_node_slot(key: NodeKey) -> Result<Rc<CoreSlot>, ReactiveScopeError> {
	ensure_owner_thread(key)?;
	SCOPES.with(|scopes| {
		let scopes = scopes.borrow();
		let state = scopes
			.get(&key.scope)
			.ok_or_else(|| disposed_node_error(key, key.kind, None))?;
		let slot = state
			.slots
			.get(key.index)
			.map(Rc::clone)
			.ok_or_else(|| disposed_node_error(key, key.kind, None))?;
		if slot.generation != key.generation {
			return Err(disposed_node_error(key, slot.kind, Some(slot.generation)));
		}
		Ok(slot)
	})
}

fn ensure_node_is_live(key: NodeKey, slot: &CoreSlot) -> Result<(), ReactiveScopeError> {
	if slot.disposed.get() {
		return Err(disposed_node_error(key, slot.kind, Some(slot.generation)));
	}
	Ok(())
}

fn disposed_node_error(
	key: NodeKey,
	kind: NodeKind,
	actual_generation: Option<u32>,
) -> ReactiveScopeError {
	ReactiveScopeError::DisposedNode {
		kind,
		scope: key.scope,
		index: key.index,
		expected_generation: key.generation,
		actual_generation,
	}
}

pub(crate) fn find_node_key(node_id: NodeId, kind: NodeKind) -> Option<NodeKey> {
	SCOPES.with(|scopes| {
		let scopes = scopes.borrow();
		for (&scope, state) in scopes.iter() {
			for (index, slot) in state.slots.iter().enumerate() {
				let Ok(value) = slot.value.try_borrow() else {
					continue;
				};
				if slot.node_id == node_id
					&& slot.kind == kind
					&& !slot.disposed.get()
					&& value.is_some()
				{
					return Some(NodeKey {
						scope,
						index,
						generation: slot.generation,
						node_id,
						kind,
						owner_thread: std::thread::current().id(),
						_thread_bound: PhantomData,
					});
				}
			}
		}
		None
	})
}

pub(crate) fn node_is_dirty(key: NodeKey) -> Result<bool, ReactiveScopeError> {
	let slot = lookup_node_slot(key)?;
	ensure_node_is_live(key, &slot)?;
	Ok(slot.dirty.get())
}

pub(crate) fn set_node_dirty(key: NodeKey, dirty: bool) -> Result<(), ReactiveScopeError> {
	let slot = lookup_node_slot(key)?;
	ensure_node_is_live(key, &slot)?;
	slot.dirty.set(dirty);
	Ok(())
}

pub(crate) fn mark_node_disposed(key: NodeKey) -> Result<(), ReactiveScopeError> {
	ensure_owner_thread(key)?;
	SCOPES.with(|scopes| {
		let scopes = scopes.borrow();
		let state = scopes
			.get(&key.scope)
			.ok_or(ReactiveScopeError::DisposedScope { scope: key.scope })?;
		let slot = state
			.slots
			.get(key.index)
			.ok_or(ReactiveScopeError::DisposedNode {
				kind: key.kind,
				scope: key.scope,
				index: key.index,
				expected_generation: key.generation,
				actual_generation: None,
			})?;
		if slot.generation != key.generation {
			return Err(ReactiveScopeError::DisposedNode {
				kind: slot.kind,
				scope: key.scope,
				index: key.index,
				expected_generation: key.generation,
				actual_generation: Some(slot.generation),
			});
		}
		slot.disposed.set(true);
		Ok(())
	})
}

fn ensure_owner_thread(key: NodeKey) -> Result<(), ReactiveScopeError> {
	let current_thread = std::thread::current().id();
	if key.owner_thread == current_thread {
		Ok(())
	} else {
		Err(ReactiveScopeError::WrongThread {
			scope: key.scope,
			owner_thread: key.owner_thread,
			current_thread,
		})
	}
}

/// Register a callback to run when the given scope is disposed.
pub fn on_scope_dispose(
	scope: ScopeId,
	cleanup: impl FnOnce() + 'static,
) -> Result<(), ReactiveScopeError> {
	SCOPES.with(|scopes| {
		let mut scopes = scopes.borrow_mut();
		let state = scopes
			.get_mut(&scope)
			.ok_or(ReactiveScopeError::DisposedScope { scope })?;
		state.cleanup.push(Box::new(cleanup));
		Ok(())
	})
}

/// Register a callback to run after the scope's stored nodes are dropped.
///
/// This is intended for teardown that may be observed by effect cleanup
/// callbacks while the scope is disposing.
pub fn on_scope_dispose_after_nodes(
	scope: ScopeId,
	cleanup: impl FnOnce() + 'static,
) -> Result<(), ReactiveScopeError> {
	SCOPES.with(|scopes| {
		let mut scopes = scopes.borrow_mut();
		let state = scopes
			.get_mut(&scope)
			.ok_or(ReactiveScopeError::DisposedScope { scope })?;
		state.after_node_cleanup.push(Box::new(cleanup));
		Ok(())
	})
}

fn take_scope_node_value(scope: ScopeId, kind: Option<NodeKind>) -> Option<Box<dyn Any>> {
	let slot = SCOPES.with(|scopes| {
		let scopes = scopes.borrow();
		let state = scopes.get(&scope)?;
		state.slots.iter().find_map(|slot| {
			let matches_kind = kind.is_none_or(|kind| slot.kind == kind);
			(matches_kind && slot.value.borrow().is_some()).then(|| Rc::clone(slot))
		})
	});
	slot.and_then(|slot| slot.value.borrow_mut().take())
}

fn remove_scope_runtime_nodes(scope: ScopeId) {
	let node_ids = SCOPES.with(|scopes| {
		scopes
			.borrow()
			.get(&scope)
			.map(|state| {
				state
					.slots
					.iter()
					.map(|slot| slot.node_id)
					.collect::<Vec<_>>()
			})
			.unwrap_or_default()
	});
	for node_id in node_ids {
		let _ = try_with_runtime(|runtime| runtime.remove_node(node_id));
	}
}

fn drop_scope_nodes(scope: ScopeId) {
	remove_scope_runtime_nodes(scope);

	// Effect cleanup callbacks may read signals captured by the effect. Drop those
	// slots while every non-effect node remains available in the scope arena.
	while let Some(value) = take_scope_node_value(scope, Some(NodeKind::Effect)) {
		drop(value);
		// Effect cleanup may allocate more reactive nodes. Snapshot after every
		// cleanup so their graph entries and pending updates cannot outlive the scope.
		remove_scope_runtime_nodes(scope);
	}

	while let Some(value) = take_scope_node_value(scope, None) {
		drop(value);
	}
}

pub(crate) fn dispose_scope(scope: ScopeId) {
	let is_live = SCOPES
		.try_with(|scopes| scopes.borrow().contains_key(&scope))
		.unwrap_or(false);
	if !is_live {
		return;
	}

	loop {
		let cleanup = SCOPES.with(|scopes| {
			scopes
				.borrow_mut()
				.get_mut(&scope)
				.map(|state| core::mem::take(&mut state.cleanup))
		});
		let Some(cleanup) = cleanup else {
			return;
		};
		if cleanup.is_empty() {
			break;
		}
		for cleanup in cleanup.into_iter().rev() {
			let _ = enter_scope(scope, || run_without_observer(cleanup));
		}
	}

	drop_scope_nodes(scope);

	loop {
		let cleanup = SCOPES.with(|scopes| {
			scopes
				.borrow_mut()
				.get_mut(&scope)
				.map(|state| core::mem::take(&mut state.after_node_cleanup))
		});
		let Some(cleanup) = cleanup else {
			return;
		};
		if cleanup.is_empty() {
			break;
		}
		for cleanup in cleanup.into_iter().rev() {
			let _ = enter_scope(scope, || run_without_observer(cleanup));
		}
	}

	// After-node callbacks are allowed to allocate while their owner is active.
	// Dispose anything they created before removing the scope state itself.
	drop_scope_nodes(scope);

	SCOPES.with(|scopes| {
		scopes.borrow_mut().remove(&scope);
	});
}

impl NodeKey {
	/// Return the runtime node identifier linked to this key.
	pub fn node_id(self) -> NodeId {
		self.node_id
	}

	/// Return the scope that owns this key.
	pub fn scope(self) -> ScopeId {
		self.scope
	}

	/// Return the generation captured by this key.
	pub fn generation(self) -> u32 {
		self.generation
	}
}

#[cfg(test)]
mod tests {
	use super::super::{deps::Deps, effect::Effect, signal::Signal};
	use super::*;
	use serial_test::serial;

	#[test]
	#[serial(reactive_runtime)]
	fn reactive_scope_run_sets_current_scope() {
		ReactiveScope::run(|| {
			let id = current_scope_id().expect("scope must be active inside run");
			assert_eq!(active_scope_id(), id);
		});
		assert!(current_scope_id().is_none());
	}

	#[cfg(not(target_arch = "wasm32"))]
	#[test]
	#[serial(reactive_runtime)]
	fn entering_a_same_numbered_worker_scope_is_rejected() {
		let scope = ReactiveScope::new();
		let scope_id = scope.id();

		let result = std::thread::spawn(move || {
			let _worker_scope = ReactiveScope::new();
			enter_scope(scope_id, || ())
		})
		.join()
		.expect("worker thread should finish without panicking");

		assert!(matches!(
			result,
			Err(ReactiveScopeError::WrongThread { .. })
		));
	}

	#[test]
	#[serial(reactive_runtime)]
	#[should_panic(expected = "requires an active ReactiveScope")]
	fn require_active_scope_panics_without_scope() {
		let _ = require_active_scope("Signal::new");
	}

	#[test]
	#[serial(reactive_runtime)]
	fn disposed_generation_is_detected() {
		let key = ReactiveScope::run(|| allocate_empty_node(NodeKind::Signal));
		let err = lookup_empty_node(key).expect_err("scope was disposed after run");
		assert!(err.to_string().contains("disposed reactive node"));
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_dispose_runs_registered_cleanup() {
		let cleaned = alloc::rc::Rc::new(RefCell::new(false));
		let cleaned_for_scope = alloc::rc::Rc::clone(&cleaned);
		ReactiveScope::run(|| {
			let scope = current_scope_id().expect("scope must be active");
			on_scope_dispose(scope, move || {
				*cleaned_for_scope.borrow_mut() = true;
			})
			.expect("active scope should accept cleanup callback");
		});
		assert!(
			*cleaned.borrow(),
			"scope disposal must run cleanup callbacks"
		);
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_cleanup_can_read_live_nodes() {
		let scope = ReactiveScope::new();
		let observed = alloc::rc::Rc::new(Cell::new(None));
		let observed_for_cleanup = alloc::rc::Rc::clone(&observed);
		let scope_id = scope.id();

		scope.enter(|| {
			let signal = super::super::signal::Signal::new(42_i32);
			on_scope_dispose(scope_id, move || {
				observed_for_cleanup.set(Some(signal.get()));
			})
			.expect("live scope should accept cleanup callbacks");
		});

		scope.dispose();

		assert_eq!(observed.get(), Some(42));
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_cleanup_can_allocate_nodes_in_owner_scope() {
		let scope = ReactiveScope::new();
		let created_id = alloc::rc::Rc::new(Cell::new(None));
		let created_id_for_cleanup = alloc::rc::Rc::clone(&created_id);
		let scope_id = scope.id();

		scope.enter(|| {
			on_scope_dispose(scope_id, move || {
				let signal = Signal::new(7_i32);
				created_id_for_cleanup.set(Some(signal.id()));
			})
			.expect("live scope should accept cleanup callbacks");
		});

		scope.dispose();

		let created_id = created_id
			.get()
			.expect("cleanup should create a signal in the owner scope");
		super::super::runtime::with_runtime(|runtime| {
			let removed = !runtime.has_node(created_id);
			assert!(
				removed,
				"cleanup-created nodes must be removed with their scope"
			);
		});
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_effect_cleanup_can_read_captured_signal_before_node_drop() {
		let scope = ReactiveScope::new();
		let observed = alloc::rc::Rc::new(Cell::new(None));
		let observed_for_effect = alloc::rc::Rc::clone(&observed);

		scope.enter(|| {
			let signal = Signal::new(42_i32);
			let signal_for_cleanup = signal;
			let _effect = Effect::new_with_deps(
				move || {
					let observed_for_cleanup = alloc::rc::Rc::clone(&observed_for_effect);
					Some(move || {
						observed_for_cleanup.set(Some(signal_for_cleanup.get_untracked()));
					})
				},
				Deps::from_signals(&[]),
			);
		});

		scope.dispose();

		assert_eq!(observed.get(), Some(42));
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_dispose_removes_nodes_created_by_effect_cleanup() {
		let scope = ReactiveScope::new();
		let cleanup_nodes = alloc::rc::Rc::new(RefCell::new(None));
		let cleanup_nodes_for_effect = alloc::rc::Rc::clone(&cleanup_nodes);

		scope.enter(|| {
			let _effect = Effect::new_with_deps(
				move || {
					let cleanup_nodes = alloc::rc::Rc::clone(&cleanup_nodes_for_effect);
					Some(move || {
						let signal = Signal::new(0_i32);
						let signal_for_effect = signal;
						let effect = Effect::new(move || {
							let _ = signal_for_effect.get();
						});
						*cleanup_nodes.borrow_mut() = Some((signal.id(), effect.id()));
					})
				},
				Deps::from_signals(&[]),
			);
		});

		scope.dispose();

		let (signal_id, effect_id) = cleanup_nodes
			.borrow()
			.expect("effect cleanup should create reactive nodes");
		super::super::runtime::with_runtime(|runtime| {
			let signal_removed = !runtime.has_node(signal_id);
			let effect_removed = !runtime.has_node(effect_id);
			let effect_not_pending = !runtime.debug_pending_updates().contains(&effect_id);
			assert!(
				signal_removed,
				"scope disposal must remove cleanup-created signal nodes"
			);
			assert!(
				effect_removed,
				"scope disposal must remove cleanup-created effect nodes"
			);
			assert!(
				effect_not_pending,
				"scope disposal must clear cleanup-created pending updates"
			);
		});
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_cleanup_callbacks_do_not_track_the_current_observer() {
		ReactiveScope::run(|| {
			let cleanup_signal = Signal::new(0_i32);
			let child_scope = Rc::new(ReactiveScope::new());
			child_scope.enter(|| {
				let scope_id = current_scope_id().expect("child scope must be active");
				on_scope_dispose(scope_id, move || {
					let _ = cleanup_signal.get();
				})
				.expect("active scope should accept cleanup callback");
				on_scope_dispose_after_nodes(scope_id, move || {
					let _ = cleanup_signal.get();
				})
				.expect("active scope should accept post-node cleanup callback");
			});

			let runs = Rc::new(Cell::new(0_i32));
			let runs_for_effect = Rc::clone(&runs);
			let child_scope_for_effect = Rc::clone(&child_scope);
			let _effect = Effect::new(move || {
				runs_for_effect.set(runs_for_effect.get() + 1);
				child_scope_for_effect.dispose();
			});

			cleanup_signal.set(1);
			super::super::runtime::with_runtime(|runtime| runtime.flush_updates());

			assert_eq!(runs.get(), 1);
		});
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_node_reads_can_reenter_the_same_signal() {
		ReactiveScope::run(|| {
			let signal = Signal::new(42_i32);

			let observed = signal.with_untracked(|_| signal.get_untracked());

			assert_eq!(observed, 42);
		});
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_post_node_cleanup_runs_after_node_values_drop() {
		struct DropMarker(alloc::rc::Rc<Cell<bool>>);

		impl Drop for DropMarker {
			fn drop(&mut self) {
				self.0.set(true);
			}
		}

		let scope = ReactiveScope::new();
		let dropped = alloc::rc::Rc::new(Cell::new(false));
		let observed = alloc::rc::Rc::new(Cell::new(false));
		let dropped_for_node = alloc::rc::Rc::clone(&dropped);
		let dropped_for_cleanup = alloc::rc::Rc::clone(&dropped);
		let observed_for_cleanup = alloc::rc::Rc::clone(&observed);
		let scope_id = scope.id();

		scope.enter(|| {
			allocate_node(NodeKind::Signal, DropMarker(dropped_for_node));
			on_scope_dispose_after_nodes(scope_id, move || {
				observed_for_cleanup.set(dropped_for_cleanup.get());
			})
			.expect("live scope should accept post-node cleanup callbacks");
		});

		scope.dispose();

		assert!(observed.get());
	}

	#[test]
	#[serial(reactive_runtime)]
	fn scope_post_node_cleanup_can_allocate_nodes_in_owner_scope() {
		let scope = ReactiveScope::new();
		let created_id = alloc::rc::Rc::new(Cell::new(None));
		let created_id_for_cleanup = alloc::rc::Rc::clone(&created_id);
		let scope_id = scope.id();

		scope.enter(|| {
			on_scope_dispose_after_nodes(scope_id, move || {
				let signal = Signal::new(8_i32);
				created_id_for_cleanup.set(Some(signal.id()));
			})
			.expect("live scope should accept post-node cleanup callbacks");
		});

		scope.dispose();

		let created_id = created_id
			.get()
			.expect("post-node cleanup should create a signal in the owner scope");
		super::super::runtime::with_runtime(|runtime| {
			assert!(
				!runtime.has_node(created_id),
				"post-node cleanup-created nodes must be removed with their scope"
			);
		});
	}
}