asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! RRef access violation oracle.
//!
//! Tracks RRef heap accesses and detects violations of region ownership
//! invariants. This oracle catches:
//!
//! 1. **Cross-region access**: Task accesses an RRef belonging to a different region.
//! 2. **Post-close access**: Task accesses an RRef after the owning region is closed.
//! 3. **Witness mismatch**: Access witness references wrong region for the RRef.
//!
//! # Integration
//!
//! The oracle records events via `on_*` methods and verifies at `check()` time.
//! It does not prevent violations — it records them for post-mortem analysis.
//!
//! # Usage
//!
//! ```ignore
//! let mut oracle = RRefAccessOracle::new();
//!
//! oracle.on_rref_create(rref_id, owner_region);
//! oracle.on_rref_access(rref_id, accessing_task, task_region, time);
//! oracle.on_region_close(region_id, time);
//!
//! oracle.check()?;
//! ```

use crate::types::{RegionId, TaskId, Time};
use std::collections::BTreeMap;
use std::fmt;

/// A unique identifier for an RRef allocation, combining region and heap index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RRefId {
    /// The region that owns this RRef.
    pub owner_region: RegionId,
    /// An opaque allocation index (from HeapIndex).
    pub alloc_index: u32,
}

impl RRefId {
    /// Creates a new RRef identifier.
    #[must_use]
    pub const fn new(owner_region: RegionId, alloc_index: u32) -> Self {
        Self {
            owner_region,
            alloc_index,
        }
    }
}

/// Types of RRef access violations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RRefAccessViolationKind {
    /// A task in region A accessed an RRef owned by region B.
    CrossRegionAccess {
        /// The region the RRef belongs to.
        rref_region: RegionId,
        /// The region the accessing task belongs to.
        task_region: RegionId,
    },
    /// An RRef was accessed after its owning region closed.
    PostCloseAccess {
        /// The region that was closed.
        region: RegionId,
        /// When the region was closed.
        close_time: Time,
        /// When the access occurred.
        access_time: Time,
    },
    /// Access witness references a different region than the RRef.
    WitnessMismatch {
        /// The region the RRef belongs to.
        rref_region: RegionId,
        /// The region the witness references.
        witness_region: RegionId,
    },
}

/// An RRef access violation detected by the oracle.
#[derive(Debug, Clone)]
pub struct RRefAccessViolation {
    /// The RRef that was accessed improperly.
    pub rref: RRefId,
    /// The task that performed the access.
    pub task: TaskId,
    /// When the violation occurred.
    pub time: Time,
    /// The specific type of violation.
    pub kind: RRefAccessViolationKind,
}

impl fmt::Display for RRefAccessViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            RRefAccessViolationKind::CrossRegionAccess {
                rref_region,
                task_region,
            } => {
                write!(
                    f,
                    "Cross-region RRef access: task {:?} (region {:?}) \
                     accessed RRef owned by region {:?} at {:?}",
                    self.task, task_region, rref_region, self.time
                )
            }
            RRefAccessViolationKind::PostCloseAccess {
                region,
                close_time,
                access_time,
            } => {
                write!(
                    f,
                    "Post-close RRef access: task {:?} accessed RRef in \
                     closed region {:?} (closed at {:?}) at {:?}",
                    self.task, region, close_time, access_time
                )
            }
            RRefAccessViolationKind::WitnessMismatch {
                rref_region,
                witness_region,
            } => {
                write!(
                    f,
                    "Witness mismatch: task {:?} used witness for region {:?} \
                     to access RRef in region {:?} at {:?}",
                    self.task, witness_region, rref_region, self.time
                )
            }
        }
    }
}

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

/// Oracle for detecting RRef access violations.
///
/// Tracks RRef creation, access events, and region lifecycle to detect
/// improper cross-region or post-close heap accesses.
#[derive(Debug, Default)]
pub struct RRefAccessOracle {
    /// Active RRefs by owner region.
    rrefs: BTreeMap<RRefId, RegionId>,
    /// Set of regions that are closed.
    closed_regions: BTreeMap<RegionId, Time>,
    /// Task-to-region mapping.
    task_regions: BTreeMap<TaskId, RegionId>,
    /// Violations detected so far.
    violations: Vec<RRefAccessViolation>,
}

impl RRefAccessOracle {
    /// Creates a new RRef access oracle.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Records an RRef allocation in a region.
    pub fn on_rref_create(&mut self, rref: RRefId, owner_region: RegionId) {
        self.rrefs.insert(rref, owner_region);
    }

    /// Records a task spawn with its owning region.
    pub fn on_task_spawn(&mut self, task: TaskId, region: RegionId) {
        self.task_regions.insert(task, region);
    }

    /// Records an RRef access by a task.
    ///
    /// Checks for cross-region and post-close violations.
    pub fn on_rref_access(&mut self, rref: RRefId, task: TaskId, time: Time) {
        let task_region = self.task_regions.get(&task).copied();
        let rref_region = self.rrefs.get(&rref).copied().unwrap_or(rref.owner_region);

        // Check cross-region access
        if let Some(task_reg) = task_region {
            if task_reg != rref_region {
                self.violations.push(RRefAccessViolation {
                    rref,
                    task,
                    time,
                    kind: RRefAccessViolationKind::CrossRegionAccess {
                        rref_region,
                        task_region: task_reg,
                    },
                });
            }
        }

        // Check post-close access
        if let Some(&close_time) = self.closed_regions.get(&rref_region) {
            if time >= close_time {
                self.violations.push(RRefAccessViolation {
                    rref,
                    task,
                    time,
                    kind: RRefAccessViolationKind::PostCloseAccess {
                        region: rref_region,
                        close_time,
                        access_time: time,
                    },
                });
            }
        }
    }

    /// Records a witness-gated RRef access. Checks witness region matches RRef region.
    pub fn on_rref_access_with_witness(
        &mut self,
        rref: RRefId,
        task: TaskId,
        witness_region: RegionId,
        time: Time,
    ) {
        let rref_region = self.rrefs.get(&rref).copied().unwrap_or(rref.owner_region);

        // Check witness mismatch
        if witness_region != rref_region {
            self.violations.push(RRefAccessViolation {
                rref,
                task,
                time,
                kind: RRefAccessViolationKind::WitnessMismatch {
                    rref_region,
                    witness_region,
                },
            });
        }

        // Delegate to standard access check (cross-region + post-close)
        self.on_rref_access(rref, task, time);
    }

    /// Records a region close event.
    pub fn on_region_close(&mut self, region: RegionId, time: Time) {
        self.closed_regions.insert(region, time);
    }

    /// Verifies no RRef access violations occurred.
    ///
    /// Returns the first violation found, or `Ok(())`.
    pub fn check(&self) -> Result<(), RRefAccessViolation> {
        if let Some(v) = self.violations.first() {
            return Err(v.clone());
        }
        Ok(())
    }

    /// Returns all violations detected.
    #[must_use]
    pub fn all_violations(&self) -> &[RRefAccessViolation] {
        &self.violations
    }

    /// Resets the oracle to its initial state.
    pub fn reset(&mut self) {
        self.rrefs.clear();
        self.closed_regions.clear();
        self.task_regions.clear();
        self.violations.clear();
    }

    /// Returns the number of tracked RRefs.
    #[must_use]
    pub fn rref_count(&self) -> usize {
        self.rrefs.len()
    }

    /// Returns the number of tracked tasks.
    #[must_use]
    pub fn task_count(&self) -> usize {
        self.task_regions.len()
    }

    /// Returns the number of closed regions.
    #[must_use]
    pub fn closed_region_count(&self) -> usize {
        self.closed_regions.len()
    }

    /// Returns the number of violations detected.
    #[must_use]
    pub fn violation_count(&self) -> usize {
        self.violations.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::ArenaIndex;

    fn region(n: u32) -> RegionId {
        RegionId::from_arena(ArenaIndex::new(n, 0))
    }

    fn task(n: u32) -> TaskId {
        TaskId::from_arena(ArenaIndex::new(n, 0))
    }

    fn t(nanos: u64) -> Time {
        Time::from_nanos(nanos)
    }

    fn rref(region_n: u32, alloc: u32) -> RRefId {
        RRefId::new(region(region_n), alloc)
    }

    // ================================================================
    // Positive tests (no violations)
    // ================================================================

    #[test]
    fn same_region_access_no_violation() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_rref_access(rref(0, 0), tid, t(10));

        assert!(oracle.check().is_ok());
        assert_eq!(oracle.violation_count(), 0);
    }

    #[test]
    fn access_before_close_no_violation() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_rref_access(rref(0, 0), tid, t(10));
        oracle.on_region_close(r, t(100));

        assert!(oracle.check().is_ok());
    }

    #[test]
    fn witness_matching_no_violation() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_rref_access_with_witness(rref(0, 0), tid, r, t(10));

        assert!(oracle.check().is_ok());
    }

    #[test]
    fn multiple_rrefs_same_region_no_violation() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_rref_create(rref(0, 1), r);
        oracle.on_rref_create(rref(0, 2), r);
        oracle.on_task_spawn(tid, r);

        oracle.on_rref_access(rref(0, 0), tid, t(10));
        oracle.on_rref_access(rref(0, 1), tid, t(20));
        oracle.on_rref_access(rref(0, 2), tid, t(30));

        assert!(oracle.check().is_ok());
    }

    // ================================================================
    // Cross-region violation tests
    // ================================================================

    #[test]
    fn cross_region_access_detected() {
        let mut oracle = RRefAccessOracle::new();
        let r_a = region(0);
        let r_b = region(1);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r_a);
        oracle.on_task_spawn(tid, r_b); // Task is in region B
        oracle.on_rref_access(rref(0, 0), tid, t(10)); // Accessing region A's RRef

        let err = oracle.check().unwrap_err();
        assert_eq!(
            err.kind,
            RRefAccessViolationKind::CrossRegionAccess {
                rref_region: r_a,
                task_region: r_b,
            }
        );
    }

    // ================================================================
    // Post-close violation tests
    // ================================================================

    #[test]
    fn post_close_access_detected() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_region_close(r, t(50));
        oracle.on_rref_access(rref(0, 0), tid, t(100)); // After close

        let err = oracle.check().unwrap_err();
        assert_eq!(
            err.kind,
            RRefAccessViolationKind::PostCloseAccess {
                region: r,
                close_time: t(50),
                access_time: t(100),
            }
        );
    }

    #[test]
    fn access_at_close_time_detected() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_region_close(r, t(50));
        oracle.on_rref_access(rref(0, 0), tid, t(50)); // Exactly at close time

        assert!(oracle.check().is_err());
    }

    // ================================================================
    // Witness mismatch tests
    // ================================================================

    #[test]
    fn witness_mismatch_detected() {
        let mut oracle = RRefAccessOracle::new();
        let r_a = region(0);
        let r_b = region(1);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r_a);
        oracle.on_task_spawn(tid, r_a);
        // Witness from region B used with region A's RRef
        oracle.on_rref_access_with_witness(rref(0, 0), tid, r_b, t(10));

        let violations = oracle.all_violations();
        assert!(
            violations
                .iter()
                .any(|v| matches!(v.kind, RRefAccessViolationKind::WitnessMismatch { .. }))
        );
    }

    // ================================================================
    // Multiple violation tests
    // ================================================================

    #[test]
    fn multiple_violations_all_recorded() {
        let mut oracle = RRefAccessOracle::new();
        let r_a = region(0);
        let r_b = region(1);
        let t1 = task(1);
        let t2 = task(2);

        oracle.on_rref_create(rref(0, 0), r_a);
        oracle.on_rref_create(rref(1, 0), r_b);
        oracle.on_task_spawn(t1, r_a);
        oracle.on_task_spawn(t2, r_b);

        // Cross-region: t2 accesses region A's rref
        oracle.on_rref_access(rref(0, 0), t2, t(10));
        // Post-close: close region B, then t1 accesses it
        oracle.on_region_close(r_b, t(20));
        oracle.on_rref_access(rref(1, 0), t1, t(30));

        let violations = oracle.all_violations();
        // 3 violations: cross-region (t2→rref in r_a), cross-region (t1→rref in r_b),
        // and post-close (r_b closed before t1 access)
        assert_eq!(violations.len(), 3);
    }

    // ================================================================
    // Reset and stats tests
    // ================================================================

    #[test]
    fn reset_clears_all_state() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);
        let tid = task(1);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_task_spawn(tid, r);
        oracle.on_region_close(r, t(10));
        oracle.on_rref_access(rref(0, 0), tid, t(20));

        assert!(oracle.check().is_err());

        oracle.reset();
        assert!(oracle.check().is_ok());
        assert_eq!(oracle.rref_count(), 0);
        assert_eq!(oracle.task_count(), 0);
        assert_eq!(oracle.closed_region_count(), 0);
        assert_eq!(oracle.violation_count(), 0);
    }

    #[test]
    fn stats_track_entities() {
        let mut oracle = RRefAccessOracle::new();
        let r = region(0);

        oracle.on_rref_create(rref(0, 0), r);
        oracle.on_rref_create(rref(0, 1), r);
        oracle.on_task_spawn(task(1), r);
        oracle.on_task_spawn(task(2), r);
        oracle.on_task_spawn(task(3), r);
        oracle.on_region_close(r, t(100));

        assert_eq!(oracle.rref_count(), 2);
        assert_eq!(oracle.task_count(), 3);
        assert_eq!(oracle.closed_region_count(), 1);
    }

    #[test]
    fn violation_display_formats() {
        let r_a = region(0);
        let r_b = region(1);
        let tid = task(1);

        let violations = vec![
            RRefAccessViolation {
                rref: rref(0, 0),
                task: tid,
                time: t(10),
                kind: RRefAccessViolationKind::CrossRegionAccess {
                    rref_region: r_a,
                    task_region: r_b,
                },
            },
            RRefAccessViolation {
                rref: rref(0, 0),
                task: tid,
                time: t(100),
                kind: RRefAccessViolationKind::PostCloseAccess {
                    region: r_a,
                    close_time: t(50),
                    access_time: t(100),
                },
            },
            RRefAccessViolation {
                rref: rref(0, 0),
                task: tid,
                time: t(10),
                kind: RRefAccessViolationKind::WitnessMismatch {
                    rref_region: r_a,
                    witness_region: r_b,
                },
            },
        ];

        for v in &violations {
            let msg = format!("{v}");
            assert!(!msg.is_empty(), "violation display should not be empty");
        }
    }

    // --- wave 76 trait coverage ---

    #[test]
    fn rref_id_debug_clone_copy_eq_ord_hash() {
        use std::collections::HashSet;
        let id = rref(0, 5);
        let id2 = id; // Copy
        let id3 = id; // Copy (RRefId is Copy)
        assert_eq!(id, id2);
        assert_eq!(id, id3);
        assert_ne!(id, rref(0, 6));
        assert!(id < rref(0, 6));
        let dbg = format!("{id:?}");
        assert!(dbg.contains("RRefId"));
        let mut set = HashSet::new();
        set.insert(id);
        assert!(set.contains(&id2));
    }

    #[test]
    fn rref_access_violation_kind_debug_clone_eq() {
        let r_a = region(0);
        let r_b = region(1);
        let k = RRefAccessViolationKind::CrossRegionAccess {
            rref_region: r_a,
            task_region: r_b,
        };
        let k2 = k.clone();
        assert_eq!(k, k2);
        assert_ne!(
            k,
            RRefAccessViolationKind::WitnessMismatch {
                rref_region: r_a,
                witness_region: r_b,
            }
        );
        let dbg = format!("{k:?}");
        assert!(dbg.contains("CrossRegionAccess"));
    }

    #[test]
    fn rref_access_violation_debug_clone() {
        let v = RRefAccessViolation {
            rref: rref(0, 1),
            task: task(2),
            time: t(100),
            kind: RRefAccessViolationKind::PostCloseAccess {
                region: region(0),
                close_time: t(50),
                access_time: t(100),
            },
        };
        let v2 = v.clone();
        assert_eq!(v.rref, v2.rref);
        assert_eq!(v.task, v2.task);
        let dbg = format!("{v:?}");
        assert!(dbg.contains("RRefAccessViolation"));
    }
}