forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorca_cycle.rs
More file actions
1677 lines (1483 loc) · 61.8 KB
/
Copy pathorca_cycle.rs
File metadata and controls
1677 lines (1483 loc) · 61.8 KB
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
996
997
998
999
1000
//! ORCA Cycle Detector — Stage A3 of the Nulang v0.4 Garbage Collector.
//!
//! This module implements the centralized cycle detection component of ORCA
//! (Optimized Reference Counting Architecture). While per-actor reference
//! counting handles acyclic garbage efficiently, cross-actor references can
//! form cycles that naive reference counting never reclaims. This module
//! detects and breaks such cycles.
//!
//! # Algorithm Overview
//!
//! ORCA's key insight is that **cycles can only form through cross-actor
//! references** (foreign references). The cycle detector maintains a directed
//! graph of all foreign references between objects owned by different actors,
//! then periodically searches this graph for cycles.
//!
//! The detection pipeline has five phases:
//!
//! 1. **Registration** — Build the foreign reference graph as actors send
//! and receive references.
//! 2. **Suspicion** — Use a weighted heuristic to flag objects that are
//! likely to be part of cycles, avoiding expensive DFS on every object.
//! 3. **Detection** — For each suspect, run depth-first search following
//! foreign edges. A path back to the starting node indicates a cycle.
//! 4. **Trial Decrement** — Temporarily decrement reference counts along
//! a detected cycle to test whether the objects are truly garbage.
//! 5. **Reclamation** — If trial decrements cause counts to reach zero,
//! the cycle is garbage and all objects in it are reclaimed.
//!
//! # Weighted Heuristic
//!
//! To avoid scanning the entire graph, ORCA assigns each object a *weight*:
//!
//! ```text
//! weight(object) = foreign_count(object) - Σ(ref_count of outgoing foreign edges)
//! ```
//!
//! An object with `weight <= suspect_threshold` has no "extra" foreign
//! references beyond what we can account for in the graph — it is a strong
//! candidate for being in a cycle. Objects with high weight have external
//! references keeping them alive and can be skipped.
//!
//! # Thread Safety
//!
//! The cycle detector runs on the single scheduler thread (the runtime is a
//! single-threaded synchronous coordinator). It does **not** require
//! internal locking for the graph itself, and header refcounts plus the
//! statistics counters are plain integers — no atomics anywhere in this
//! module.
//!
//! # Safety
//!
//! This module uses `unsafe` blocks when dereferencing `*mut OrcaHeader`
//! pointers stored in the graph. These pointers are valid only while the
//! corresponding object is alive. Every dereference checks the object's
//! reference count first (non-zero count implies the object is alive).
//!
//! The invariant that the cycle detector's graph reflects the actual runtime
//! foreign reference graph is maintained by the runtime calling
//! `register_foreign_ref` and `remove_foreign_ref` on every foreign
//! reference operation.
use crate::runtime::gc::ForeignRefOp;
use crate::runtime::heap::OrcaHeader;
use std::collections::{HashMap, HashSet, VecDeque};
// ---------------------------------------------------------------------------
// CycleRuntime trait
// ---------------------------------------------------------------------------
/// Runtime capability required by the cycle detector to reclaim garbage cycles.
///
/// The cycle detector is intentionally decoupled from [`Runtime`](super::Runtime);
/// this trait is the only bridge it needs to free objects on the correct actor
/// heap and to drop any pending deferred-decrement entries for those objects.
pub trait CycleRuntime {
/// Free the object identified by `header` on `actor_id`'s heap.
///
/// # Safety
/// `header` must point to a live object owned by `actor_id`.
unsafe fn free_object(&mut self, actor_id: u64, header: *mut OrcaHeader);
}
// ---------------------------------------------------------------------------
// Data Structures
// ---------------------------------------------------------------------------
/// Color used during the cycle detector's own mark phase.
///
/// These colors are conceptually similar to tricolor GC marking but serve a
/// different purpose: they track which nodes have been visited during a
/// single DFS traversal for cycle detection, not for general GC reachability.
///
/// - **White** — Node has not been visited in the current detection pass.
/// - **Gray** — Node is currently on the DFS recursion stack (part of the
/// active path being explored).
/// - **Black** — Node has been fully explored and is not part of any cycle
/// rooted in the current search.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeColor {
White,
Gray,
Black,
}
/// A directed edge in the foreign reference graph.
///
/// Represents a foreign reference from one object to another. The edge is
/// *directed* from the source object (which holds the reference) to the
/// target object (which is referenced). Multiple references between the
/// same pair of objects are collapsed into a single edge with a `ref_count`
/// indicating how many references exist.
///
/// # Invariants
///
/// - `ref_count` is always > 0 for edges stored in the graph.
/// - `target_actor` must differ from the source object's owning actor
/// (otherwise it would not be a *foreign* reference).
#[derive(Debug, Clone, Copy)]
pub struct ForeignEdge {
/// The actor that owns the target object.
pub target_actor: u64,
/// Pointer to the target object's header.
pub target_object: *mut OrcaHeader,
/// Number of references along this edge (>= 1).
pub ref_count: u32,
}
// SAFETY: ForeignEdge contains a raw pointer, but we only use it as an opaque
// handle for HashMap keys. Equality and hashing are based on the pointer
// address value, not the pointed-to data.
unsafe impl Send for ForeignEdge {}
unsafe impl Sync for ForeignEdge {}
impl PartialEq for ForeignEdge {
fn eq(&self, other: &Self) -> bool {
self.target_actor == other.target_actor && self.target_object == other.target_object
}
}
impl Eq for ForeignEdge {}
impl std::hash::Hash for ForeignEdge {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.target_actor.hash(state);
self.target_object.hash(state);
}
}
/// A node in the foreign reference graph.
///
/// Each node represents a single heap object (identified by its header
/// pointer) and tracks all outgoing foreign reference edges from that object.
///
/// # Lifetime
///
/// A node is valid as long as its `object_header` pointer is valid. The
/// cycle detector should remove nodes when their corresponding objects are
/// freed. The `is_alive` method checks whether the object still exists by
/// verifying that its reference count is non-zero.
#[derive(Debug)]
pub struct ForeignRefNode {
/// The actor that owns this object.
pub actor_id: u64,
/// Pointer to the object's GC header.
///
/// # Safety
///
/// This pointer is valid only while the object is alive. Always check
/// `is_alive()` before dereferencing.
pub object_header: *mut OrcaHeader,
/// All outgoing foreign reference edges from this object.
pub foreign_refs: Vec<ForeignEdge>,
/// Weight for the heuristic: `foreign_count - sum(outgoing_edge_ref_counts)`.
/// Updated lazily during suspicion phase.
pub weight: u32,
/// Color for mark phase during detection.
pub color: NodeColor,
/// Epoch when this node was last visited (for incremental detection).
pub visited_epoch: u64,
}
// SAFETY: ForeignRefNode stores a raw pointer, but the CycleDetector that
// owns the node is !Sync (single-threaded), so there are no data races.
// The pointer is only dereferenced after checking the object is alive.
unsafe impl Send for ForeignRefNode {}
impl ForeignRefNode {
/// Check whether the object this node represents is still alive.
///
/// An object is considered alive if its total reference count
/// (local + foreign) is greater than zero. If the count has reached
/// zero, the object may have been or is about to be reclaimed.
///
/// # Safety
///
/// This method dereferences `self.object_header`. The caller must ensure
/// that the header pointer is still valid (i.e., points to mapped memory).
/// In practice, the runtime only frees objects after the cycle detector
/// has been notified, so this is safe as long as the notification
/// protocol is followed.
pub unsafe fn is_alive(&self) -> bool {
// Dereference the header pointer to read reference counts.
// SAFETY: The runtime guarantees that headers are not freed until
// the cycle detector processes the removal notification.
let header = &*self.object_header;
let local = header.ref_count;
let foreign = header.foreign_count;
(local + foreign) > 0
}
/// Compute the current weight of this node.
///
/// Weight = foreign_count(object) - sum of ref_counts of all outgoing edges.
/// A low weight means the object's foreign references are mostly
/// accounted for by edges in our graph, suggesting it may be in a cycle.
///
/// # Safety
///
/// Reads `self.object_header`. Caller must ensure the pointer is valid.
pub unsafe fn compute_weight(&self) -> u32 {
let header = &*self.object_header;
let foreign_count = header.foreign_count;
let outgoing_sum: u32 = self.foreign_refs.iter().map(|e| e.ref_count).sum();
// Saturating subtraction to avoid underflow.
foreign_count.saturating_sub(outgoing_sum)
}
}
impl PartialEq for ForeignRefNode {
fn eq(&self, other: &Self) -> bool {
self.actor_id == other.actor_id && self.object_header == other.object_header
}
}
impl Eq for ForeignRefNode {}
/// A suspect object flagged by the weighted heuristic.
///
/// When the cycle detector scans the graph, objects with weight below the
/// threshold are enqueued as suspects. Suspects are processed incrementally
/// (one at a time) to avoid long pause times.
#[derive(Debug, Clone, Copy)]
pub struct Suspect {
/// Actor owning the suspected object.
pub actor_id: u64,
/// Pointer to the object's header.
///
/// # Safety
///
/// Must be checked for liveness before dereferencing.
pub object_header: *mut OrcaHeader,
/// Computed weight at the time of flagging.
pub weight: u32,
/// Epoch when this suspect was flagged.
pub flagged_epoch: u64,
}
/// The centralized ORCA cycle detector.
///
/// The cycle detector maintains a directed graph of all cross-actor
/// (foreign) object references and periodically searches it for cycles.
/// It uses a weighted heuristic to prioritize which objects to examine,
/// reducing the overhead of full graph traversal.
///
/// # Design
///
/// - Single-threaded: The cycle detector runs on one coordinator thread.
/// No internal synchronization is needed for graph mutations.
/// - Incremental: Detection work is spread across multiple calls to
/// `incremental_detect`, each processing a bounded amount of work.
/// - Conservative: Trial decrements ensure we only reclaim objects that
/// are provably unreachable.
///
/// # Example
///
/// ```ignore
/// let mut detector = CycleDetector::new();
/// // When actor 1 sends a ref to actor 2:
/// detector.register_foreign_ref(1, obj_a, 2, obj_b);
/// // Periodically:
/// detector.incremental_detect(&runtime);
/// ```
pub struct CycleDetector {
/// The foreign reference graph.
///
/// Key: (actor_id, object_header_address) — using the header pointer's
/// address as a usize gives us a stable, hashable identifier.
///
/// Value: The node representing this object and its outgoing edges.
graph: HashMap<(u64, usize), ForeignRefNode>,
/// Queue of suspect objects to investigate.
///
/// Suspects are processed FIFO. New suspects are appended at the back;
/// `incremental_detect` pops from the front.
suspects: VecDeque<Suspect>,
/// Current epoch counter.
///
/// Incremented on each detection pass. Used to avoid revisiting nodes
/// multiple times within the same pass and to age out old suspects.
epoch: u64,
/// Set of actor IDs that are local to this node. When `Some`, the
/// detector only processes suspects and references belonging to local
/// actors, keeping it strictly intra-node. `None` disables filtering
/// (used in unit tests with mock runtimes).
local_actors: Option<HashSet<u64>>,
/// Threshold for flagging objects as suspects.
///
/// Objects with `weight <= suspect_threshold` are enqueued for deeper
/// inspection. The default value of 1 catches objects whose foreign
/// references are fully accounted for by graph edges.
suspect_threshold: u32,
/// How many epochs between full detection passes.
///
/// A full pass scans all nodes and rebuilds the suspect queue.
/// Incremental steps process one suspect at a time.
detection_interval: u64,
/// Number of cycles found and reclaimed (for statistics).
cycles_found: u64,
/// Number of objects reclaimed from broken cycles (for statistics).
objects_reclaimed: u64,
/// Snapshot of graph keys for the current incremental full scan.
/// `None` when no scan is in progress.
scan_keys: Option<Vec<(u64, usize)>>,
/// How many keys have been processed in the current scan.
scan_cursor: usize,
/// Maximum number of nodes to scan per `refresh_suspects` call.
scan_batch_size: usize,
}
// ---------------------------------------------------------------------------
// CycleDetector Implementation
// ---------------------------------------------------------------------------
impl CycleDetector {
/// Create a new cycle detector with sensible default parameters.
///
/// Defaults:
/// - `suspect_threshold`: 1 (objects with weight 0 or 1 are suspects)
/// - `detection_interval`: 10 (full scan every 10 epochs)
pub fn new() -> Self {
Self {
scan_keys: None,
scan_cursor: 0,
scan_batch_size: 100, // process at most 100 nodes per call
graph: HashMap::new(),
suspects: VecDeque::new(),
epoch: 0,
suspect_threshold: 1,
detection_interval: 10,
local_actors: None,
cycles_found: 0,
objects_reclaimed: 0,
}
}
/// Restrict cycle detection to the given set of local actor IDs.
///
/// When called with a non-empty set, the detector ignores any foreign
/// reference whose target actor is not in the set, and skips suspects
/// owned by non-local actors. This satisfies the v1.0 requirement that
/// the centralized cycle detector operate intra-node only.
pub fn set_local_actors(&mut self, local_actor_ids: HashSet<u64>) {
self.local_actors = Some(local_actor_ids);
}
/// Remove the local-actor restriction.
pub fn clear_local_actors(&mut self) {
self.local_actors = None;
}
/// Return the current local-actor restriction, if any.
pub fn local_actors(&self) -> Option<&HashSet<u64>> {
self.local_actors.as_ref()
}
fn is_local(&self, actor_id: u64) -> bool {
match &self.local_actors {
Some(set) => set.contains(&actor_id),
None => true,
}
}
// -- Graph construction ------------------------------------------------
/// Register a new foreign reference edge in the graph.
///
/// Called by the runtime whenever an actor sends a reference to an
/// object it owns to another actor. This creates (or strengthens) a
/// directed edge from the source object to the target object.
///
/// # Parameters
///
/// - `from_actor` — ID of the actor that owns the source object.
/// - `from_object` — Header pointer of the source object.
/// - `to_actor` — ID of the actor that owns the target object.
/// - `to_object` — Header pointer of the target object.
///
/// # Safety
///
/// `from_object` and `to_object` must point to valid, live `OrcaHeader`
/// structures. The runtime guarantees this by only calling this method
/// during active reference-sending operations.
pub fn register_foreign_ref(
&mut self,
from_actor: u64,
from_object: *mut OrcaHeader,
to_actor: u64,
to_object: *mut OrcaHeader,
) {
// Ignore self-references within the same actor — these are not
// *foreign* references and cannot participate in cross-actor cycles.
if from_actor == to_actor {
return;
}
// When restricted to local actors, ignore edges that target (or originate from)
// remote actors. This keeps the centralized detector intra-node only.
if !self.is_local(to_actor) {
return;
}
if self.local_actors.is_some() && !self.is_local(from_actor) {
return;
}
let key = (from_actor, from_object as usize);
// Get or create the source node.
let node = self.graph.entry(key).or_insert_with(|| ForeignRefNode {
actor_id: from_actor,
object_header: from_object,
foreign_refs: Vec::new(),
weight: 0,
color: NodeColor::White,
visited_epoch: 0,
});
// Check if an edge to this target already exists; if so, increment
// its ref_count. Otherwise, create a new edge.
if let Some(edge) = node
.foreign_refs
.iter_mut()
.find(|e| e.target_actor == to_actor && e.target_object == to_object)
{
edge.ref_count = edge.ref_count.saturating_add(1);
} else {
node.foreign_refs.push(ForeignEdge {
target_actor: to_actor,
target_object: to_object,
ref_count: 1,
});
}
}
/// Remove a foreign reference edge from the graph.
///
/// Called by the runtime when a foreign reference is dropped (e.g., via
/// `drop_local_ref` on a received reference). Decrements or removes the
/// corresponding edge.
///
/// # Parameters
///
/// Same as `register_foreign_ref`.
///
/// # Edge Cases
///
/// - If the edge's ref_count drops to zero, the edge is removed.
/// - If the node has no remaining edges after removal, the node itself
/// is removed from the graph.
/// - If the node or edge does not exist, this is a no-op (idempotent).
pub fn remove_foreign_ref(
&mut self,
from_actor: u64,
from_object: *mut OrcaHeader,
to_actor: u64,
to_object: *mut OrcaHeader,
) {
let key = (from_actor, from_object as usize);
let should_remove_node = if let Some(node) = self.graph.get_mut(&key) {
if let Some(pos) = node
.foreign_refs
.iter()
.position(|e| e.target_actor == to_actor && e.target_object == to_object)
{
let edge = &mut node.foreign_refs[pos];
if edge.ref_count <= 1 {
node.foreign_refs.swap_remove(pos);
} else {
edge.ref_count -= 1;
}
}
// Remove the node if it has no more outgoing foreign refs.
node.foreign_refs.is_empty()
} else {
false
};
if should_remove_node {
self.graph.remove(&key);
}
}
// -- Detection entry points --------------------------------------------
/// Run one incremental cycle detection step.
///
/// This method is designed to be called frequently (e.g., every N
/// scheduling rounds) with a bounded amount of work per call. It
/// processes at most one suspect per invocation, keeping pause times low.
///
/// # Algorithm
///
/// 1. Increment the epoch.
/// 2. If the epoch aligns with `detection_interval`, run a full scan
/// to refresh the suspect queue (`refresh_suspects`).
/// 3. Otherwise, if suspects are queued, pop one and process it
/// (`process_suspect`).
///
/// # Parameters
///
/// - `runtime` — The runtime context, used to send trial decrements
/// and reclaim objects.
pub fn incremental_detect<R: CycleRuntime>(&mut self, runtime: &mut R) {
self.epoch += 1;
if self.epoch % self.detection_interval == 0 {
// Full scan: rebuild the suspect queue from the current graph.
self.refresh_suspects(runtime);
}
// Process one suspect per incremental step.
if let Some(suspect) = self.suspects.pop_front() {
// SAFETY: process_suspect reads object headers. We verify
// liveness before any dereference.
unsafe {
self.process_suspect(&suspect, runtime);
}
}
}
fn refresh_suspects<R>(&mut self, _runtime: &R) {
// Start a new scan if none is in progress.
if self.scan_keys.is_none() {
self.suspects.clear();
self.scan_keys = Some(self.graph.keys().copied().collect());
self.scan_cursor = 0;
}
let keys = match self.scan_keys.as_ref() {
Some(k) => k,
None => return,
};
let end = (self.scan_cursor + self.scan_batch_size).min(keys.len());
for &key in &keys[self.scan_cursor..end] {
let is_local = if let Some(node) = self.graph.get(&key) {
self.is_local(node.actor_id)
} else {
true
};
if !is_local {
continue;
}
if let Some(node) = self.graph.get_mut(&key) {
let alive = unsafe {
(*node.object_header).ref_count + (*node.object_header).foreign_count > 0
};
if !alive {
node.weight = u32::MAX;
continue;
}
let weight = unsafe { node.compute_weight() };
node.weight = weight;
if weight <= self.suspect_threshold {
self.suspects.push_back(Suspect {
actor_id: node.actor_id,
object_header: node.object_header,
weight,
flagged_epoch: self.epoch,
});
}
}
}
self.scan_cursor = end;
// Scan complete: clean up dead nodes and reset state.
if self.scan_cursor >= keys.len() {
self.graph.retain(|_, node| node.weight != u32::MAX);
self.scan_keys = None;
self.scan_cursor = 0;
}
}
/// Run a full cycle detection pass.
///
/// This is the core algorithm that searches the entire foreign reference
/// graph for cycles. Unlike `incremental_detect`, this processes **all**
/// suspects in a single call. Use with care, as it may have longer pause
/// times.
///
/// # Algorithm
///
/// 1. Refresh the suspect queue (scan all nodes, recompute weights).
/// 2. For each suspect, perform DFS following foreign edges.
/// 3. If DFS returns to the starting node, a cycle is found.
/// 4. Send trial decrements, confirm, and reclaim if garbage.
///
/// # Parameters
///
/// - `runtime` — Mutable reference to the runtime for sending operations
/// and reclaiming objects.
pub fn detect_cycles<R: CycleRuntime>(&mut self, runtime: &mut R) {
self.epoch += 1;
self.refresh_suspects(runtime);
// Process all suspects. We collect them first to avoid borrowing
// issues between suspect iteration and graph mutation.
let suspects: Vec<Suspect> = self.suspects.drain(..).collect();
for suspect in &suspects {
// SAFETY: process_suspect dereferences object headers.
unsafe {
self.process_suspect(suspect, runtime);
}
}
}
// -- Per-suspect processing --------------------------------------------
/// Process a single suspect object.
///
/// Uses the weighted heuristic: if the object's total foreign weight
/// is below the threshold, it's a candidate for cycle testing. This
/// method performs a DFS from the suspect to detect cycles.
///
/// # Algorithm
///
/// 1. Verify the suspect object is still alive.
/// 2. Reset colors for all nodes to White (new detection pass).
/// 3. Run DFS from the suspect, following foreign_ref edges.
/// 4. If DFS finds a path back to the starting node, extract the cycle.
/// 5. Send trial decrements, confirm, and reclaim if appropriate.
///
/// # Parameters
///
/// - `suspect` — The suspect object to investigate.
/// - `runtime` — The runtime context.
///
/// # Safety
///
/// Dereferences `suspect.object_header` and potentially other headers
/// during DFS. All headers are checked for liveness before dereferencing.
unsafe fn process_suspect<R: CycleRuntime>(&mut self, suspect: &Suspect, runtime: &mut R) {
if !self.is_local(suspect.actor_id) {
return;
}
// Verify the suspect object is still alive.
let key = (suspect.actor_id, suspect.object_header as usize);
let Some(start_node) = self.graph.get(&key) else {
// Object no longer has any foreign refs — not in a cycle.
return;
};
// Check liveness.
if !start_node.is_alive() {
return;
}
// Reset all node colors to White for a fresh detection pass.
for node in self.graph.values_mut() {
node.color = NodeColor::White;
}
// Run DFS from the suspect to find cycles.
let mut path: Vec<(u64, *mut OrcaHeader)> = Vec::new();
if let Some(cycle) = self.dfs_find_cycle(suspect.actor_id, suspect.object_header, &mut path)
{
// Cycle found! Send trial decrements.
self.send_trial_decrements(&cycle);
// Check if the cycle is garbage (all objects have zero count).
if self.is_cycle_garbage(&cycle) {
self.confirm_and_reclaim(&cycle, runtime);
} else {
self.cancel_trial_decrements(&cycle);
}
}
}
/// Depth-first search for cycles starting from a given node.
///
/// Follows foreign reference edges recursively. If we encounter a Gray
/// node (on the current path), a cycle is found. If we encounter a
/// Black node, that subtree has already been explored and has no cycles.
///
/// # Parameters
///
/// - `actor_id` — Actor ID of the current node.
/// - `object` — Header pointer of the current node.
/// - `path` — Current DFS path (stack of visited nodes).
///
/// # Returns
///
/// `Some(cycle)` if a cycle is found, where `cycle` is the sequence of
/// nodes forming the cycle. `None` if no cycle was found from this node.
///
/// # Safety
///
/// Dereferences header pointers in the graph. Nodes are checked for
/// existence in the graph before use.
unsafe fn dfs_find_cycle(
&mut self,
actor_id: u64,
object: *mut OrcaHeader,
path: &mut Vec<(u64, *mut OrcaHeader)>,
) -> Option<Vec<(u64, *mut OrcaHeader)>> {
// Only follow edges within the local node set when restricted.
if !self.is_local(actor_id) {
return None;
}
let key = (actor_id, object as usize);
// If the node is not in our graph, dead end.
let edge_targets: Vec<(u64, *mut OrcaHeader)> = {
let node = self.graph.get_mut(&key)?;
match node.color {
NodeColor::Black => {
return None;
}
NodeColor::Gray => {
let cycle_start = path
.iter()
.position(|(a, o)| *a == actor_id && *o == object)?;
let cycle = path[cycle_start..].to_vec();
return Some(cycle);
}
NodeColor::White => {
node.color = NodeColor::Gray;
}
}
// Collect edge targets before recursing — avoids cloning the
// full ForeignEdge vec (which includes ref_count, unused here).
node.foreign_refs
.iter()
.map(|e| (e.target_actor, e.target_object))
.collect()
};
// `node` borrow is dropped; safe to borrow `self.graph` again below.
// Push current node onto the path.
path.push((actor_id, object));
// Explore each outgoing edge.
for &(target_actor, target_object) in &edge_targets {
if !self.is_local(target_actor) {
continue;
}
let child_key = (target_actor, target_object as usize);
if self.graph.contains_key(&child_key) {
if let Some(cycle) = self.dfs_find_cycle(target_actor, target_object, path) {
return Some(cycle);
}
}
}
// All children explored — mark Black and backtrack.
path.pop();
if let Some(node) = self.graph.get_mut(&key) {
node.color = NodeColor::Black;
}
None
}
// -- Trial decrement protocol ------------------------------------------
/// Send trial decrements along a detected cycle.
///
/// For each edge in the cycle, this constructs a `ForeignRefOp` with
/// delta = -1 (a trial decrement). The caller must later either confirm
/// (reclaim) or cancel (restore) these decrements.
///
/// # Parameters
///
/// - `cycle` — A sequence of `(actor_id, object_header)` tuples
/// forming a cycle. Each consecutive pair represents an edge.
///
/// # Returns
///
/// A vector of `ForeignRefOp` representing the trial decrements.
fn send_trial_decrements(&mut self, cycle: &[(u64, *mut OrcaHeader)]) -> Vec<ForeignRefOp> {
let mut ops = Vec::with_capacity(cycle.len());
// For a cycle [A, B, C], we send decrements along edges A->B, B->C, C->A.
for i in 0..cycle.len() {
let (_from_actor, _from_object) = cycle[i];
let (to_actor, to_object) = cycle[(i + 1) % cycle.len()];
// SAFETY: We are constructing an operation, not yet applying it.
// The header pointer is validated before any decrement is applied.
let op = ForeignRefOp {
target_actor: to_actor,
owner_actor: to_actor,
object_header: to_object as *mut crate::runtime::OrcaHeader,
delta: -1,
};
ops.push(op);
// Decrement the target's foreign count
// to simulate the reference being dropped within the cycle.
unsafe {
// SAFETY: The objects were verified alive during DFS, and the
// single scheduler thread is the only mutator of any header.
let target_header = &mut *to_object;
target_header.foreign_count -= 1;
}
}
ops
}
/// Check whether all objects in a cycle have zero reference counts.
///
/// This is called after trial decrements have been sent. If every
/// object's total count (local + foreign) is zero, the cycle is
/// unreachable garbage and can be reclaimed.
///
/// # Parameters
///
/// - `cycle` — The cycle to check.
///
/// # Returns
///
/// `true` if all objects in the cycle have zero total count.
///
/// # Safety
///
/// Dereferences object headers. All headers are verified alive.
fn is_cycle_garbage(&self, cycle: &[(u64, *mut OrcaHeader)]) -> bool {
for &(_actor, object) in cycle {
// SAFETY: Object headers were validated during DFS and have not
// been freed (trial decrements prevent concurrent reclamation).
let (local, foreign) = unsafe {
let header = &*object;
(header.ref_count, header.foreign_count)
};
if local + foreign > 0 {
// At least one object still has references — the cycle is
// still reachable from outside.
return false;
}
}
true
}
/// Confirm trial decrements and reclaim all objects in a garbage cycle.
///
/// This is called when `is_cycle_garbage` returns `true`. All objects
/// in the cycle are freed and removed from the graph.
///
/// # Parameters
///
/// - `cycle` — The confirmed garbage cycle.
/// - `runtime` — The runtime context for freeing objects.
fn confirm_and_reclaim<R: CycleRuntime>(
&mut self,
cycle: &[(u64, *mut OrcaHeader)],
runtime: &mut R,
) {
self.cycles_found += 1;
self.objects_reclaimed += cycle.len() as u64;
for &(actor_id, object) in cycle {
let key = (actor_id, object as usize);
// Remove the node from the graph.
self.graph.remove(&key);
// SAFETY: `object` was verified alive during DFS and the trial
// decrements proved it has no remaining references.
unsafe {
runtime.free_object(actor_id, object);
}
}
}
/// Cancel trial decrements for a cycle that is still reachable.
///
/// This restores the reference counts that were temporarily decremented
/// by `send_trial_decrements`. The cycle is not garbage — external
/// references keep it alive — so we must undo the trial.
///
/// # Parameters
///
/// - `cycle` — The cycle whose trial decrements should be cancelled.
fn cancel_trial_decrements(&mut self, cycle: &[(u64, *mut OrcaHeader)]) {
// For each edge in the cycle, increment the counts back.
for i in 0..cycle.len() {
let (_from_actor, _from_object) = cycle[i];
let (_to_actor, to_object) = cycle[(i + 1) % cycle.len()];
// SAFETY: The object was alive during DFS and hasn't been freed
// (we only free after confirming garbage), and the single
// scheduler thread is the only mutator of any header.
unsafe {
let target_header = &mut *to_object;
target_header.foreign_count += 1;
}
}
// Mark nodes as Black so we don't re-examine them in this pass.
for &(actor_id, object) in cycle {
let key = (actor_id, object as usize);
if let Some(node) = self.graph.get_mut(&key) {
node.color = NodeColor::Black;
}
}
}
// -- Queries & configuration -------------------------------------------
/// Check whether a full cycle detection should be triggered.
///
/// Returns `true` when the current epoch aligns with the detection
/// interval. The runtime can use this to decide whether to call
/// `detect_cycles` (full pass) or just `incremental_detect`.
pub fn should_detect(&self) -> bool {
self.epoch % self.detection_interval == 0
}
/// Get cycle detector statistics.
///
/// Returns a tuple of `(cycles_found, objects_reclaimed)`.
pub fn stats(&self) -> (u64, u64) {
(self.cycles_found, self.objects_reclaimed)
}
/// Update the suspect threshold.
///
/// A lower threshold means fewer objects are flagged as suspects,
/// reducing detection overhead but potentially missing cycles.
/// A higher threshold casts a wider net, catching more potential
/// cycles at the cost of increased detection work.
///
/// # Parameters
///
/// - `threshold` — New threshold value. Objects with `weight <= threshold`
/// will be flagged as suspects.
pub fn set_threshold(&mut self, threshold: u32) {
self.suspect_threshold = threshold;
}
/// Get the number of nodes currently in the foreign reference graph.
///
/// Primarily useful for diagnostics and testing.
pub fn graph_size(&self) -> usize {
self.graph.len()
}
/// Get the number of suspects currently queued for investigation.
///
/// Primarily useful for diagnostics and testing.
pub fn suspect_queue_len(&self) -> usize {
self.suspects.len()
}
/// Get the current epoch.
///
/// Primarily useful for testing epoch progression.
pub fn current_epoch(&self) -> u64 {
self.epoch
}
}
impl Default for CycleDetector {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Unit Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod mock {
//! Minimal mocks for testing the cycle detector in isolation.
//!
//! Since the cycle detector depends on `Runtime`, `OrcaHeader`, and