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
//! Region-owned reference type.
//!
//! `RRef` provides a way for migrating (`Send`) tasks to reference data
//! allocated in the region heap safely.
//!
//! # Design
//!
//! `RRef<T>` is a smart reference that:
//! - Stores a `RegionId` and `HeapIndex` for runtime lookup
//! - Is `Send + Sync` when `T: Send + Sync`
//! - Requires passing the `RegionRecord` to access the underlying value
//! - Validates region and allocation validity at access time
//!
//! The key invariant is that region heap allocations remain valid for all
//! tasks owned by the region. Since tasks cannot outlive their owning region
//! (structured concurrency guarantee), `RRef`s held by tasks are always valid
//! while those tasks are running.
//!
//! # Example
//!
//! ```ignore
//! // In region context
//! let data = region.heap_alloc(vec![1, 2, 3]).expect("heap alloc");
//! let rref = RRef::<Vec<i32>>::new(region_id, data);
//!
//! // Pass to spawned task
//! spawn(async move {
//!     // Access via region reference
//!     let value = rref.get(&runtime_state, region_id)?;
//!     println!("data: {:?}", value);
//! });
//! ```
//!
//! # Safety
//!
//! This type uses no unsafe code. Safety is enforced through:
//! 1. Structured concurrency: tasks cannot outlive their region
//! 2. Runtime validation: access checks region/index validity
//! 3. Type safety: HeapIndex includes TypeId for type checking

use crate::runtime::region_heap::HeapIndex;
use crate::types::RegionId;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

/// A region-owned reference to heap-allocated data.
///
/// `RRef<T>` allows tasks to hold references to data allocated in a region's
/// heap. The reference is valid as long as the owning region is open.
///
/// # Send/Sync
///
/// `RRef<T>` is `Send` when `T: Send` and `Sync` when `T: Sync`. This allows
/// `RRef`s to be safely passed to worker threads. The bounds are automatically
/// provided through `PhantomData<T>` - no unsafe code required.
///
/// # Cloning
///
/// `RRef` is `Clone + Copy` because it contains only indices, not the actual
/// data. Multiple `RRef`s can point to the same heap allocation.
pub struct RRef<T> {
    /// The region that owns this allocation.
    region_id: RegionId,
    /// Index into the region's heap.
    index: HeapIndex,
    /// Marker for the referenced type.
    ///
    /// Using `PhantomData<T>` ensures `RRef<T>` is:
    /// - Send when T: Send
    /// - Sync when T: Sync
    ///
    /// This is safe because RRef contains only indices (Copy types), not the
    /// actual data. Access to the data goes through the RegionHeap which has
    /// its own synchronization (RwLock).
    _marker: PhantomData<T>,
}

// Manual Clone impl to avoid requiring T: Clone (RRef is Copy regardless of T)
impl<T> Clone for RRef<T> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for RRef<T> {}

impl<T> fmt::Debug for RRef<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RRef")
            .field("region_id", &self.region_id)
            .field("index", &self.index)
            .finish()
    }
}

impl<T> PartialEq for RRef<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.region_id == other.region_id && self.index == other.index
    }
}

impl<T> Eq for RRef<T> {}

impl<T> Hash for RRef<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.region_id.hash(state);
        self.index.hash(state);
    }
}

// Send and Sync are automatically derived via PhantomData<T>:
// - RRef<T>: Send when T: Send (PhantomData<T>: Send when T: Send)
// - RRef<T>: Sync when T: Sync (PhantomData<T>: Sync when T: Sync)
//
// This is safe because:
// - RRef contains only indices (Copy types)
// - The actual data is in RegionHeap which has its own synchronization (RwLock)
// - Access requires going through the heap which has proper locking

// Accessor methods available for all RRef<T> regardless of bounds.
// These just return stored indices (Copy types) and don't access the underlying data.
impl<T> RRef<T> {
    /// Returns the region ID that owns this reference.
    #[inline]
    #[must_use]
    pub const fn region_id(&self) -> RegionId {
        self.region_id
    }

    /// Returns the underlying heap index.
    #[inline]
    #[must_use]
    pub const fn heap_index(&self) -> HeapIndex {
        self.index
    }
}

// Construction requires Send + Sync + 'static for soundness when used with Send tasks.
impl<T: Send + Sync + 'static> RRef<T> {
    /// Creates a new region reference from a region ID and heap index.
    ///
    /// # Arguments
    ///
    /// * `region_id` - The ID of the region that owns the allocation
    /// * `index` - The heap index returned from `heap_alloc`
    ///
    /// # Bounds
    ///
    /// The `Send + Sync + 'static` bounds on `T` ensure that:
    /// - The referenced data can be safely shared across threads
    /// - The `RRef` can be passed to Send tasks that may migrate
    ///
    /// # Example
    ///
    /// ```ignore
    /// let index = region.heap_alloc(42u32).expect("heap alloc");
    /// let rref = RRef::new(region_id, index);
    /// ```
    #[inline]
    #[must_use]
    pub const fn new(region_id: RegionId, index: HeapIndex) -> Self {
        Self {
            region_id,
            index,
            _marker: PhantomData,
        }
    }
}

/// Error returned when accessing an RRef fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RRefError {
    /// The region does not exist in the runtime state.
    RegionNotFound(RegionId),
    /// The heap allocation is no longer valid (deallocated or type mismatch).
    AllocationInvalid,
    /// The region ID in the RRef doesn't match the provided region.
    RegionMismatch {
        /// The region ID stored in the RRef.
        expected: RegionId,
        /// The region ID that was provided.
        actual: RegionId,
    },
    /// The region is closed and its heap has been reclaimed.
    RegionClosed,
    /// The access witness references a different region than expected.
    WrongRegion,
}

impl fmt::Display for RRefError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RegionNotFound(id) => write!(f, "region not found: {id:?}"),
            Self::AllocationInvalid => write!(f, "heap allocation is invalid"),
            Self::RegionMismatch { expected, actual } => {
                write!(f, "region mismatch: expected {expected:?}, got {actual:?}")
            }
            Self::RegionClosed => write!(f, "region is closed"),
            Self::WrongRegion => write!(f, "access witness references wrong region"),
        }
    }
}

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

/// Capability witness proving access rights to a specific region's heap.
///
/// Constructed exclusively by [`RegionRecord::access_witness`] when the region
/// is in a non-terminal state. External code cannot forge a witness because
/// the constructor is `pub(crate)`.
///
/// # Usage
///
/// ```ignore
/// let witness = region_record.access_witness()?;
/// let value = region_record.rref_get_with(&rref, witness)?;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RRefAccessWitness {
    region_id: RegionId,
}

impl RRefAccessWitness {
    /// Creates a new access witness for the given region.
    ///
    /// This is `pub(crate)` to prevent external forging. Use
    /// [`RegionRecord::access_witness`] to obtain a witness.
    #[must_use]
    pub(crate) const fn new(region_id: RegionId) -> Self {
        Self { region_id }
    }

    /// Returns the region this witness grants access to.
    #[must_use]
    pub const fn region(&self) -> RegionId {
        self.region_id
    }
}

impl<T> RRef<T> {
    /// Validates that a witness matches this RRef's region.
    ///
    /// Returns `Err(WrongRegion)` if the witness was obtained from a different
    /// region than the one this RRef belongs to.
    pub fn validate_witness(&self, witness: &RRefAccessWitness) -> Result<(), RRefError> {
        if witness.region() != self.region_id {
            return Err(RRefError::WrongRegion);
        }
        Ok(())
    }
}

/// Extension trait for accessing RRef values through a region.
///
/// This trait is implemented for types that can provide access to a region's heap.
/// Implementations must validate region ownership and state before returning data.
pub trait RRefAccess {
    /// Gets a clone of the value referenced by an RRef.
    ///
    /// Returns an error if the region doesn't match or the allocation is invalid.
    fn rref_get<T: Clone + 'static>(&self, rref: &RRef<T>) -> Result<T, RRefError>;

    /// Executes a closure with a reference to the value.
    ///
    /// This is more efficient than `rref_get` when you don't need to clone.
    fn rref_with<T: 'static, R, F: FnOnce(&T) -> R>(
        &self,
        rref: &RRef<T>,
        f: F,
    ) -> Result<R, RRefError>;

    /// Gets a clone of the value, requiring a pre-validated witness.
    ///
    /// The witness proves the caller has been granted access to the region.
    /// This is the preferred access path in capability-aware code.
    fn rref_get_with<T: Clone + 'static>(
        &self,
        rref: &RRef<T>,
        witness: RRefAccessWitness,
    ) -> Result<T, RRefError>;

    /// Executes a closure with a reference, requiring a pre-validated witness.
    ///
    /// The witness proves the caller has been granted access to the region.
    fn rref_with_witness<T: 'static, R, F: FnOnce(&T) -> R>(
        &self,
        rref: &RRef<T>,
        witness: RRefAccessWitness,
        f: F,
    ) -> Result<R, RRefError>;
}

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

    fn test_region_id() -> RegionId {
        RegionId::from_arena(ArenaIndex::new(0, 0))
    }

    #[test]
    fn rref_is_copy_and_clone() {
        let region_id = test_region_id();
        let record = RegionRecord::new(region_id, None, Budget::INFINITE);
        let index = record.heap_alloc(42u32).expect("heap alloc");
        let rref = RRef::<u32>::new(region_id, index);

        // Test Copy
        let rref2 = rref;
        assert_eq!(rref.region_id(), rref2.region_id());

        // Clone is implied by Copy, assert the trait bound explicitly.
        assert_clone::<RRef<u32>>();
    }

    #[test]
    fn rref_equality() {
        let region_id = test_region_id();
        let record = RegionRecord::new(region_id, None, Budget::INFINITE);

        let index1 = record.heap_alloc(1u32).expect("heap alloc");
        let index2 = record.heap_alloc(2u32).expect("heap alloc");

        let rref1a = RRef::<u32>::new(region_id, index1);
        let rref1_clone = RRef::<u32>::new(region_id, index1);
        let rref2 = RRef::<u32>::new(region_id, index2);

        assert_eq!(rref1a, rref1_clone);
        assert_ne!(rref1a, rref2);
    }

    #[test]
    fn rref_accessors() {
        let region_id = test_region_id();
        let record = RegionRecord::new(region_id, None, Budget::INFINITE);
        let index = record.heap_alloc("hello".to_string()).expect("heap alloc");
        let rref = RRef::<String>::new(region_id, index);

        assert_eq!(rref.region_id(), region_id);
        assert_eq!(rref.heap_index(), index);
    }

    #[test]
    fn rref_debug_format() {
        let region_id = test_region_id();
        let record = RegionRecord::new(region_id, None, Budget::INFINITE);
        let index = record.heap_alloc(42u32).expect("heap alloc");
        let rref = RRef::<u32>::new(region_id, index);

        let debug_str = format!("{rref:?}");
        assert!(debug_str.contains("RRef"));
        assert!(debug_str.contains("region_id"));
        assert!(debug_str.contains("index"));
    }

    #[test]
    fn rref_access_through_region_record() {
        let region_id = test_region_id();
        let record = RegionRecord::new(region_id, None, Budget::INFINITE);
        let index = record.heap_alloc("hello".to_string()).expect("heap alloc");
        let rref = RRef::<String>::new(region_id, index);

        let value = record.rref_get(&rref).expect("rref_get");
        assert_eq!(value, "hello");

        let len = record.rref_with(&rref, String::len).expect("rref_with");
        assert_eq!(len, 5);
    }

    #[test]
    fn rref_region_mismatch_is_error() {
        let region_a = test_region_id();
        let region_b = RegionId::from_arena(ArenaIndex::new(1, 0));
        let record_a = RegionRecord::new(region_a, None, Budget::INFINITE);
        let record_b = RegionRecord::new(region_b, None, Budget::INFINITE);

        let index = record_a.heap_alloc(7u32).expect("heap alloc");
        let rref = RRef::<u32>::new(region_a, index);

        let err = record_b.rref_get(&rref).expect_err("region mismatch");
        assert_eq!(
            err,
            RRefError::RegionMismatch {
                expected: region_a,
                actual: region_b,
            }
        );
    }

    // Compile-time test for Send/Sync bounds
    fn assert_clone<T: Clone>() {}
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    #[test]
    fn rref_send_sync_bounds() {
        // RRef<T> is Send when T: Send
        assert_send::<RRef<u32>>();
        assert_send::<RRef<String>>();
        assert_send::<RRef<Vec<i32>>>();

        // RRef<T> is Sync when T: Sync
        assert_sync::<RRef<u32>>();
        assert_sync::<RRef<String>>();
        assert_sync::<RRef<Vec<i32>>>();
    }

    // ================================================================
    // Witness validation tests (bd-27c7l)
    // ================================================================

    #[test]
    fn validate_witness_matching_region_succeeds() {
        let rid = test_region_id();
        let record = RegionRecord::new(rid, None, Budget::INFINITE);
        let index = record.heap_alloc(42u32).expect("heap alloc");
        let rref = RRef::<u32>::new(rid, index);

        let witness = RRefAccessWitness::new(rid);
        assert!(rref.validate_witness(&witness).is_ok());
    }

    #[test]
    fn validate_witness_wrong_region_fails() {
        let rid_a = test_region_id();
        let rid_b = RegionId::from_arena(ArenaIndex::new(77, 0));
        let record = RegionRecord::new(rid_a, None, Budget::INFINITE);
        let index = record.heap_alloc(42u32).expect("heap alloc");
        let rref = RRef::<u32>::new(rid_a, index);

        let wrong_witness = RRefAccessWitness::new(rid_b);
        let err = rref.validate_witness(&wrong_witness);
        assert_eq!(err.unwrap_err(), RRefError::WrongRegion);
    }

    #[test]
    fn access_witness_is_copy_and_eq() {
        let rid = test_region_id();
        let w1 = RRefAccessWitness::new(rid);
        let w2 = w1; // Copy
        assert_eq!(w1, w2);
        assert_eq!(w1.region(), rid);
    }

    #[test]
    fn rref_error_display_coverage() {
        let rid = test_region_id();
        let cases: Vec<(RRefError, &str)> = vec![
            (RRefError::RegionNotFound(rid), "region not found"),
            (RRefError::AllocationInvalid, "heap allocation is invalid"),
            (
                RRefError::RegionMismatch {
                    expected: rid,
                    actual: rid,
                },
                "region mismatch",
            ),
            (RRefError::RegionClosed, "region is closed"),
            (
                RRefError::WrongRegion,
                "access witness references wrong region",
            ),
        ];

        for (err, expected_substring) in cases {
            let msg = format!("{err}");
            assert!(
                msg.contains(expected_substring),
                "expected '{expected_substring}' in '{msg}'"
            );
        }
    }
}