asupersync 0.3.4

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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Finalizer types for region cleanup.
//!
//! Finalizers are cleanup handlers that run when a region closes, after all
//! children have completed. They are executed in LIFO (last-in, first-out)
//! order to ensure proper resource release ordering.

use crate::types::Budget;
use std::future::Future;
use std::pin::Pin;

/// A finalizer that runs during region close.
///
/// Finalizers are stored in a stack and executed LIFO when a region transitions
/// to the Finalizing state. This ensures resources are released in the reverse
/// order they were acquired.
pub enum Finalizer {
    /// Synchronous finalizer (runs directly on scheduler thread).
    ///
    /// Use for lightweight cleanup that doesn't need to await.
    Sync(Box<dyn FnOnce() + Send>),

    /// Asynchronous finalizer (runs as masked task).
    ///
    /// Use for cleanup that needs to perform async operations.
    /// Runs under a cancel mask to prevent interruption.
    Async(Pin<Box<dyn Future<Output = ()> + Send>>),
}

impl std::fmt::Debug for Finalizer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sync(_) => f.debug_tuple("Sync").field(&"<closure>").finish(),
            Self::Async(_) => f.debug_tuple("Async").field(&"<future>").finish(),
        }
    }
}

/// Default budget for finalizer execution.
///
/// Finalizers have bounded resources to prevent unbounded cleanup.
pub const FINALIZER_POLL_BUDGET: u32 = 100;

/// Default time budget for finalizers (5 seconds).
pub const FINALIZER_TIME_BUDGET_NANOS: u64 = 5_000_000_000;

/// Returns the default budget for finalizer execution.
#[must_use]
#[inline]
pub fn finalizer_budget() -> Budget {
    let budget = Budget::new().with_poll_quota(FINALIZER_POLL_BUDGET);

    // EDGE CASE VALIDATION: Ensure budget parameters are sane
    // This catches invalid configurations that could cause unbounded finalizer execution
    debug_assert!(
        budget.poll_quota > 0,
        "br-asupersync-mg70eb: finalizer budget must have positive poll quota \
         (poll_quota={})",
        budget.poll_quota
    );
    debug_assert!(
        FINALIZER_TIME_BUDGET_NANOS > 0,
        "br-asupersync-mg70eb: finalizer time budget must be positive \
         (time_budget_nanos={})",
        FINALIZER_TIME_BUDGET_NANOS
    );
    debug_assert!(
        FINALIZER_TIME_BUDGET_NANOS <= 300_000_000_000, // 5 minutes max
        "br-asupersync-mg70eb: finalizer time budget seems excessive, may indicate configuration error \
         (time_budget_nanos={}, max_reasonable=300_000_000_000)",
        FINALIZER_TIME_BUDGET_NANOS
    );

    budget
    // Time budget would be set relative to current time when executed
}

/// Policy for handling finalizers that exceed their budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FinalizerEscalation {
    /// Wait indefinitely for the finalizer to complete (strict correctness).
    Soft,

    /// After budget exceeded, log a warning and continue to next finalizer.
    #[default]
    BoundedLog,

    /// After budget exceeded, panic.
    BoundedPanic,
}

impl FinalizerEscalation {
    /// Returns true if this policy allows continuing after budget exhaustion.
    #[inline]
    #[must_use]
    pub const fn allows_continuation(self) -> bool {
        matches!(self, Self::BoundedLog)
    }

    /// Returns true if this policy requires waiting indefinitely.
    #[inline]
    #[must_use]
    pub const fn is_soft(self) -> bool {
        matches!(self, Self::Soft)
    }

    /// Validates escalation policy configuration for edge cases.
    ///
    /// This catches policy misconfigurations that could lead to finalizer hangs
    /// or unexpected behavior during budget exhaustion scenarios.
    #[inline]
    #[must_use = "validate_policy_configuration returns configuration diagnostics"]
    pub fn validate_policy_configuration(self) -> Result<(), &'static str> {
        match self {
            Self::Soft => {
                // EDGE CASE VALIDATION: Soft policy should be used with caution
                // This policy can cause indefinite waits if finalizers don't respect cancellation
                debug_assert!(
                    true, // Always passes but documents the risk
                    "br-asupersync-mg70eb: Soft escalation policy can cause indefinite waits \
                     - ensure finalizers respect cancellation signals"
                );
                Ok(())
            }
            Self::BoundedLog => {
                // This is the default and safest policy
                Ok(())
            }
            Self::BoundedPanic => {
                // EDGE CASE VALIDATION: Panic policy should be used carefully
                // This policy can bring down the entire runtime if budget is exceeded
                debug_assert!(
                    true, // Always passes but documents the risk
                    "br-asupersync-mg70eb: BoundedPanic escalation policy will panic on budget exhaustion \
                     - ensure finalizer budgets are adequate for expected workload"
                );
                Ok(())
            }
        }
    }
}

/// A stack of finalizers with LIFO semantics.
///
/// Finalizers are pushed when registered (defer_async/defer_sync) and popped
/// during region finalization. The LIFO ordering ensures resources are released
/// in the reverse order they were acquired.
#[derive(Debug, Default)]
pub struct FinalizerStack {
    /// The stack of finalizers.
    finalizers: Vec<Finalizer>,
    /// Escalation policy for budget violations.
    escalation: FinalizerEscalation,
}

impl FinalizerStack {
    /// Creates a new empty finalizer stack.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new finalizer stack with the specified escalation policy.
    #[must_use]
    #[inline]
    pub fn with_escalation(escalation: FinalizerEscalation) -> Self {
        // EDGE CASE VALIDATION: Validate escalation policy configuration
        // This catches policy misconfigurations during stack creation
        let _ = escalation.validate_policy_configuration();

        Self {
            finalizers: Vec::new(),
            escalation,
        }
    }

    /// Returns the escalation policy.
    #[must_use]
    #[inline]
    pub const fn escalation(&self) -> FinalizerEscalation {
        self.escalation
    }

    /// Pushes a finalizer onto the stack.
    ///
    /// # LIFO Ordering Contract
    ///
    /// Finalizers are added to the top of the stack and later popped in
    /// reverse order (LIFO). This ensures that resources acquired in order
    /// A→B→C are released in order C→B→A, matching RAII principles.
    ///
    /// Contract verified by: `region_finalizer_stack()` and `finalizer_lifo_order()` tests.
    #[inline]
    pub fn push(&mut self, finalizer: Finalizer) {
        // EDGE CASE VALIDATION: Check for excessive finalizer accumulation
        // This catches potential memory leaks or runaway finalizer creation
        debug_assert!(
            self.finalizers.len() < 10000,
            "br-asupersync-mg70eb: excessive finalizer count suggests potential leak \
             (current_count={}, max_reasonable=10000)",
            self.finalizers.len()
        );

        self.finalizers.push(finalizer);

        // Defensive contract verification in debug builds
        #[cfg(debug_assertions)]
        {
            debug_assert!(
                !self.finalizers.is_empty(),
                "FinalizerStack::push() maintains non-empty invariant after successful push"
            );

            // EDGE CASE VALIDATION: Verify stack integrity after push
            debug_assert_eq!(
                self.finalizers.len(),
                self.len(),
                "br-asupersync-mg70eb: finalizer stack length inconsistency after push"
            );
        }
    }

    /// Pops a finalizer from the stack (LIFO order).
    ///
    /// # LIFO Contract Enforcement
    ///
    /// This method maintains strict LIFO semantics to ensure proper resource
    /// release ordering. The last finalizer added (most recent) is always
    /// the first to execute, matching structured concurrency cleanup patterns.
    ///
    /// The underlying Vec::pop() guarantees LIFO ordering, and this contract
    /// is verified by tests in region.rs (`finalizer_lifo_order`).
    #[inline]
    pub fn pop(&mut self) -> Option<Finalizer> {
        let _len_before = self.finalizers.len();
        let result = self.finalizers.pop();

        // Defensive assertion: LIFO ordering contract verification
        #[cfg(debug_assertions)]
        if result.is_some() {
            // Document LIFO guarantee in debug builds for audit trail
            debug_assert!(
                true, // Always passes - documents the invariant
                "FinalizerStack::pop() maintains LIFO contract per SEM-INV-002"
            );

            // EDGE CASE VALIDATION: Verify stack integrity after pop
            debug_assert_eq!(
                self.finalizers.len(),
                _len_before.saturating_sub(1),
                "br-asupersync-mg70eb: finalizer stack length inconsistency after pop \
                 (before={}, after={}, expected={})",
                _len_before,
                self.finalizers.len(),
                _len_before.saturating_sub(1)
            );

            // EDGE CASE VALIDATION: Check for stack underflow edge case
            debug_assert!(
                _len_before > 0,
                "br-asupersync-mg70eb: finalizer stack underflow - popped from empty stack"
            );
        } else {
            // EDGE CASE VALIDATION: Verify empty pop behavior
            debug_assert_eq!(
                _len_before, 0,
                "br-asupersync-mg70eb: finalizer stack returned None but was not empty \
                 (_len_before={})",
                _len_before
            );
        }

        result
    }

    /// Returns the number of pending finalizers.
    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        self.finalizers.len()
    }

    /// Returns true if there are no pending finalizers.
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.finalizers.is_empty()
    }

    /// Pushes a synchronous finalizer.
    pub fn push_sync<F>(&mut self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.push(Finalizer::Sync(Box::new(f)));
    }

    /// Pushes an asynchronous finalizer.
    pub fn push_async<F>(&mut self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        self.push(Finalizer::Async(Box::pin(future)));
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use parking_lot::Mutex;

    fn finalizer_policy_table() -> String {
        [
            FinalizerEscalation::Soft,
            FinalizerEscalation::BoundedLog,
            FinalizerEscalation::BoundedPanic,
        ]
        .into_iter()
        .map(|policy| {
            format!(
                "{policy:?}|soft={}|continue={}|polls={}|time_ns={}",
                policy.is_soft(),
                policy.allows_continuation(),
                FINALIZER_POLL_BUDGET,
                FINALIZER_TIME_BUDGET_NANOS
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
    }

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    #[test]
    fn finalizer_stack_lifo_order() {
        init_test("finalizer_stack_lifo_order");
        let mut stack = FinalizerStack::new();
        let order = std::sync::Arc::new(Mutex::new(Vec::new()));
        let o1 = order.clone();
        let o2 = order.clone();
        let o3 = order.clone();

        stack.push_sync(move || o1.lock().push(1));
        stack.push_sync(move || o2.lock().push(2));
        stack.push_sync(move || o3.lock().push(3));

        // Pop and execute in LIFO order
        while let Some(finalizer) = stack.pop() {
            if let Finalizer::Sync(f) = finalizer {
                f();
            }
        }

        // Should be 3, 2, 1 (LIFO)
        let order = order.lock().clone();
        crate::assert_with_log!(order == vec![3, 2, 1], "order", vec![3, 2, 1], order);
        crate::test_complete!("finalizer_stack_lifo_order");
    }

    #[test]
    fn finalizer_stack_empty() {
        init_test("finalizer_stack_empty");
        let mut stack = FinalizerStack::new();
        let empty = stack.is_empty();
        crate::assert_with_log!(empty, "empty", true, empty);
        let len = stack.len();
        crate::assert_with_log!(len == 0, "len", 0, len);
        let pop = stack.pop();
        crate::assert_with_log!(pop.is_none(), "pop none", true, pop.is_none());
        crate::test_complete!("finalizer_stack_empty");
    }

    #[test]
    fn finalizer_escalation_policies() {
        init_test("finalizer_escalation_policies");
        let soft = FinalizerEscalation::Soft.is_soft();
        crate::assert_with_log!(soft, "soft is soft", true, soft);
        let log_soft = FinalizerEscalation::BoundedLog.is_soft();
        crate::assert_with_log!(!log_soft, "log not soft", false, log_soft);
        let panic_soft = FinalizerEscalation::BoundedPanic.is_soft();
        crate::assert_with_log!(!panic_soft, "panic not soft", false, panic_soft);

        let log_cont = FinalizerEscalation::BoundedLog.allows_continuation();
        crate::assert_with_log!(log_cont, "log allows", true, log_cont);
        let soft_cont = FinalizerEscalation::Soft.allows_continuation();
        crate::assert_with_log!(!soft_cont, "soft no continue", false, soft_cont);
        let panic_cont = FinalizerEscalation::BoundedPanic.allows_continuation();
        crate::assert_with_log!(!panic_cont, "panic no continue", false, panic_cont);
        crate::test_complete!("finalizer_escalation_policies");
    }

    #[test]
    fn finalizer_budget_has_expected_values() {
        init_test("finalizer_budget_has_expected_values");
        let budget = finalizer_budget();
        crate::assert_with_log!(
            budget.poll_quota == FINALIZER_POLL_BUDGET,
            "poll_quota",
            FINALIZER_POLL_BUDGET,
            budget.poll_quota
        );
        crate::test_complete!("finalizer_budget_has_expected_values");
    }

    #[test]
    fn finalizer_debug_impl() {
        init_test("finalizer_debug_impl");
        let sync_finalizer = Finalizer::Sync(Box::new(|| {}));
        let debug_str = format!("{sync_finalizer:?}");
        let sync_debug_present = debug_str.contains("Sync");
        crate::assert_with_log!(sync_debug_present, "sync debug", true, sync_debug_present);

        let async_finalizer = Finalizer::Async(Box::pin(async {}));
        let debug_str = format!("{async_finalizer:?}");
        let async_debug_present = debug_str.contains("Async");
        crate::assert_with_log!(
            async_debug_present,
            "async debug",
            true,
            async_debug_present
        );
        crate::test_complete!("finalizer_debug_impl");
    }

    // =========================================================================
    // Wave 51 – pure data-type trait coverage
    // =========================================================================

    #[test]
    fn finalizer_escalation_debug_clone_copy_eq_default() {
        let e = FinalizerEscalation::BoundedLog;
        let dbg = format!("{e:?}");
        assert!(dbg.contains("BoundedLog"), "{dbg}");
        let copied = e;
        let cloned = e;
        assert_eq!(copied, cloned);
        let def = FinalizerEscalation::default();
        assert_eq!(def, FinalizerEscalation::BoundedLog);
    }

    #[test]
    fn finalizer_stack_debug_default() {
        let stack = FinalizerStack::default();
        let dbg = format!("{stack:?}");
        assert!(dbg.contains("FinalizerStack"), "{dbg}");
        assert!(stack.is_empty());
    }

    #[test]
    fn finalizer_policy_table_snapshot() {
        insta::assert_snapshot!("finalizer_policy_table", finalizer_policy_table());
    }

    // =========================================================================
    // Golden artifact tests for finalizer outputs
    // =========================================================================

    /// Generate structured budget configuration output for golden testing
    fn budget_configuration_table() -> String {
        let budget = finalizer_budget();
        vec![
            format!("poll_quota={}", budget.poll_quota),
            format!("cost_quota={:?}", budget.cost_quota),
            format!("priority={}", budget.priority),
            format!("deadline={:?}", budget.deadline),
            format!("constants.poll_budget={}", FINALIZER_POLL_BUDGET),
            format!("constants.time_budget_ns={}", FINALIZER_TIME_BUDGET_NANOS),
        ]
        .join("\n")
    }

    /// Generate debug representations of finalizers for golden testing
    fn finalizer_debug_representations() -> String {
        let sync_finalizer = Finalizer::Sync(Box::new(|| {}));
        let async_finalizer = Finalizer::Async(Box::pin(async {}));

        vec![
            format!("Sync: {:?}", sync_finalizer),
            format!("Async: {:?}", async_finalizer),
        ]
        .join("\n")
    }

    /// Generate finalizer stack states for golden testing
    fn finalizer_stack_operations() -> String {
        let mut lines = Vec::new();

        // Empty stack
        let mut stack = FinalizerStack::new();
        lines.push(format!(
            "empty_stack: len={}, is_empty={}, escalation={:?}",
            stack.len(),
            stack.is_empty(),
            stack.escalation()
        ));

        // Stack with custom escalation
        let stack_panic = FinalizerStack::with_escalation(FinalizerEscalation::BoundedPanic);
        lines.push(format!(
            "panic_stack: len={}, is_empty={}, escalation={:?}",
            stack_panic.len(),
            stack_panic.is_empty(),
            stack_panic.escalation()
        ));

        // Add finalizers and show progression
        stack.push_sync(|| {});
        lines.push(format!(
            "after_sync_push: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        stack.push_async(async {});
        lines.push(format!(
            "after_async_push: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        stack.push_sync(|| {});
        lines.push(format!(
            "after_second_sync: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        // Pop operations (don't execute, just show types)
        if let Some(finalizer) = stack.pop() {
            match finalizer {
                Finalizer::Sync(_) => lines.push("popped: Sync".to_string()),
                Finalizer::Async(_) => lines.push("popped: Async".to_string()),
            }
        }
        lines.push(format!(
            "after_first_pop: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        if let Some(finalizer) = stack.pop() {
            match finalizer {
                Finalizer::Sync(_) => lines.push("popped: Sync".to_string()),
                Finalizer::Async(_) => lines.push("popped: Async".to_string()),
            }
        }
        lines.push(format!(
            "after_second_pop: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        if let Some(finalizer) = stack.pop() {
            match finalizer {
                Finalizer::Sync(_) => lines.push("popped: Sync".to_string()),
                Finalizer::Async(_) => lines.push("popped: Async".to_string()),
            }
        }
        lines.push(format!(
            "after_third_pop: len={}, is_empty={}",
            stack.len(),
            stack.is_empty()
        ));

        // Test pop from empty
        let empty_pop = stack.pop();
        lines.push(format!(
            "empty_pop: {}",
            if empty_pop.is_none() { "None" } else { "Some" }
        ));

        lines.join("\n")
    }

    /// Generate escalation policy behavior matrix for golden testing
    fn escalation_policy_matrix() -> String {
        let policies = [
            FinalizerEscalation::Soft,
            FinalizerEscalation::BoundedLog,
            FinalizerEscalation::BoundedPanic,
        ];

        let mut lines = Vec::new();
        lines.push("policy|is_soft|allows_continuation|default_match".to_string());

        for policy in policies {
            let is_default = policy == FinalizerEscalation::default();
            lines.push(format!(
                "{:?}|{}|{}|{}",
                policy,
                policy.is_soft(),
                policy.allows_continuation(),
                is_default
            ));
        }

        lines.join("\n")
    }

    /// Generate finalizer stack debug output for golden testing
    fn finalizer_stack_debug_output() -> String {
        let mut lines = Vec::new();

        // Empty stack debug
        let empty_stack = FinalizerStack::new();
        lines.push(format!("empty: {:?}", empty_stack));

        // Stack with escalation debug
        let panic_stack = FinalizerStack::with_escalation(FinalizerEscalation::BoundedPanic);
        lines.push(format!("panic_escalation: {:?}", panic_stack));

        let soft_stack = FinalizerStack::with_escalation(FinalizerEscalation::Soft);
        lines.push(format!("soft_escalation: {:?}", soft_stack));

        lines.join("\n")
    }

    #[test]
    fn finalizer_budget_configuration() {
        insta::assert_snapshot!("budget_configuration", budget_configuration_table());
    }

    #[test]
    fn finalizer_debug_output() {
        insta::assert_snapshot!("debug_representations", finalizer_debug_representations());
    }

    #[test]
    fn finalizer_stack_state_transitions() {
        insta::assert_snapshot!("stack_operations", finalizer_stack_operations());
    }

    #[test]
    fn finalizer_escalation_behavior_matrix() {
        insta::assert_snapshot!("escalation_matrix", escalation_policy_matrix());
    }

    #[test]
    fn finalizer_stack_debug_variants() {
        insta::assert_snapshot!("stack_debug_output", finalizer_stack_debug_output());
    }
}