saddle-runtime 0.3.23

Saddle managed asynchronous runtime and lifecycle
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
//! Framework composition only. Facade owns the ONE hook and emergency writer.
use saddle_core::{
    CaptureSite, Diagnostic, DiagnosticCategory, DiagnosticCause, DiagnosticCode, DiagnosticStage,
    SaddleError,
};
use saddle_observability::{CallContext, EmergencyDiagnosticHandle, EventContext, Observer};
use std::{
    cell::RefCell,
    future::Future,
    panic::{AssertUnwindSafe, PanicHookInfo, catch_unwind, resume_unwind},
    sync::OnceLock,
};

static OUTPUT: OnceLock<EmergencyDiagnosticHandle> = OnceLock::new();

/// Output observation, NOT a transaction/resource/durable-write receipt.
#[derive(Debug)]
pub struct RuntimeDiagnosticExit {
    pub shutdown: saddle_observability::DiagnosticShutdown,
    pub snapshot: saddle_observability::DiagnosticOutputSnapshot,
}

pub(crate) fn close_output(
    mut owner: saddle_observability::EmergencyDiagnostics,
    deadline: Option<std::time::Instant>,
) -> RuntimeDiagnosticExit {
    let shutdown = loop {
        let status = owner.shutdown();
        if status != saddle_observability::DiagnosticShutdown::Pending {
            break status;
        }
        let remaining = deadline
            .map(|d| d.saturating_duration_since(std::time::Instant::now()))
            .unwrap_or_default();
        if remaining.is_zero() {
            break status;
        }
        // Same absolute shutdown budget. No new async timer, writer join or
        // wait after expiration. Startup failure without a budget is immediate.
        std::thread::sleep(remaining.min(std::time::Duration::from_millis(1)));
    };
    RuntimeDiagnosticExit {
        shutdown,
        snapshot: owner.snapshot(),
    }
}
type RequestContext = (Observer, CallContext, EventContext);
struct Frame {
    stage: DiagnosticStage,
    task: &'static str,
    context: Option<RequestContext>,
    panic: Option<Diagnostic>,
    primary: Option<Diagnostic>,
    request_mode: bool,
    request_panic: Option<RequestCaptured>,
    request_primary: Option<RequestCaptured>,
    cleanup_occurrence: Option<saddle_core::DiagnosticOccurrence>,
    request_scope: Option<saddle_observability::RequestDiagnosticScope<'static>>,
    request_output: Option<EmergencyDiagnosticHandle>,
}

pub(crate) enum RequestCaptured {
    Established(saddle_observability::RequestBoundaryReference<Diagnostic>),
    MissingContext(Diagnostic),
}
impl RequestCaptured {
    pub(crate) fn diagnostic(&self) -> &Diagnostic {
        match self {
            Self::Established(reference) => reference.source_diagnostic(),
            Self::MissingContext(diagnostic) => diagnostic,
        }
    }
    pub(crate) fn occurrence(&self) -> saddle_core::DiagnosticOccurrence {
        self.diagnostic().occurrence()
    }
    pub(crate) fn record(&self, axes: &saddle_core::DiagnosticOutcomeAxes) {
        self.record_with_output(OUTPUT.get(), axes)
    }
    pub(crate) fn record_with_output(&self, output: Option<&EmergencyDiagnosticHandle>, axes: &saddle_core::DiagnosticOutcomeAxes) {
        match self {
            Self::Established(reference) => {
                let _ = reference.record_optional(output, axes);
            }
            Self::MissingContext(_) => boundary(Some(self.occurrence()), axes, None),
        }
    }
}

pub(crate) fn live_request_scope(
    projection: &saddle_core::DbScopeDiagnosticContext<(&CallContext, &EventContext)>,
) -> saddle_observability::RequestDiagnosticScope<'static> {
    saddle_observability::RequestDiagnosticScope::live_db_scope(OUTPUT.get(), projection)
}

fn capture_request(
    diagnostic: Diagnostic,
    context: Option<&RequestContext>,
    checked: Option<&saddle_observability::RequestDiagnosticScope<'static>>,
    output: Option<&EmergencyDiagnosticHandle>,
) -> RequestCaptured {
    if let Some(scope) = checked {
        return RequestCaptured::Established(
            scope.reborrow().with_output(output).capture_existing(diagnostic, context.map(|(observer, _, _)| observer)).into_reference(),
        );
    }
    if let Some((observer, call, event)) = context {
        if let Some(scope) = checked {
            return RequestCaptured::Established(
                scope
                    .capture_existing(diagnostic, Some(observer))
                    .into_reference(),
            );
        }
        let scope = match OUTPUT.get() {
            Some(output) => {
                saddle_observability::RequestDiagnosticScope::established(output, call, event)
            }
            None => saddle_observability::RequestDiagnosticScope::output_unavailable(call, event),
        };
        RequestCaptured::Established(
            scope
                .capture_existing(diagnostic, Some(observer))
                .into_reference(),
        )
    } else {
        // No fabricated context or receipt: this legacy degraded case remains
        // explicitly outside the established-context enforcement claim.
        emit(&diagnostic, None);
        RequestCaptured::MissingContext(diagnostic)
    }
}
pub(crate) fn capture_task_source(
    diagnostic: Diagnostic,
    scope: &saddle_observability::RequestDiagnosticScope<'static>,
    output: Option<&EmergencyDiagnosticHandle>,
) -> RequestCaptured {
    capture_request(diagnostic, None, Some(scope), output)
}
thread_local! { static CURRENT: RefCell<Option<Frame>> = const { RefCell::new(None) }; }

// Called only after the task context verifies the currently executing Tokio ID.
// Updates the same poll's hook frame, not a process-global context registry.
pub(crate) fn refresh_task_scope(scope: saddle_observability::RequestDiagnosticScope<'static>) {
    CURRENT.with(|slot| {
        if let Ok(mut slot) = slot.try_borrow_mut() {
            if let Some(frame) = slot.as_mut() {
                if frame.request_mode && frame.task == "runtime.formal_request_task" {
                    frame.request_scope = Some(scope);
                }
            }
        }
    });
}

/// Called once by Facade with its existing writer handle. No thread/hook is created.
pub fn install_output(handle: EmergencyDiagnosticHandle) -> Result<(), EmergencyDiagnosticHandle> {
    OUTPUT.set(handle)
}

/// Called by Facade's sole panic hook. False means no Runtime poll context;
/// the Facade must capture that unassociated panic itself. Never reads payload.
pub fn capture_current_panic(info: &PanicHookInfo<'_>) -> bool {
    CURRENT.with(|slot| {
        let Ok(mut slot) = slot.try_borrow_mut() else {
            return false;
        };
        let Some(frame) = slot.as_mut() else {
            return false;
        };
        let mut diagnostic =
            Diagnostic::capture_panic(info, frame.stage).with_task(code(frame.task));
        if let Some(primary) = frame.primary.as_ref() {
            diagnostic = diagnostic.during_cleanup_of(primary);
        }
        if let Some(primary) = frame.request_primary.as_ref() {
            diagnostic = diagnostic.during_cleanup_of(primary.diagnostic());
        }
        if let Some(primary) = frame.cleanup_occurrence.as_ref() {
            diagnostic = diagnostic.during_cleanup_of_occurrence(primary);
        }
        if frame.request_mode {
            frame.request_panic = Some(capture_request(
                diagnostic,
                frame.context.as_ref(),
                frame.request_scope.as_ref(),
                frame.request_output.as_ref(),
            ));
            return true;
        }
        emit(&diagnostic, frame.context.as_ref());
        frame.panic = Some(diagnostic);
        true
    })
}

fn code(value: &'static str) -> DiagnosticCode {
    DiagnosticCode::new(value).expect("Runtime diagnostic codes are static schema identifiers")
}

/// Fixed source detail, before a lossy conversion or fail-closed exit. It never
/// formats an error payload, allocates a stack, or changes the execution result.
#[track_caller]
pub(crate) fn bounded_source(
    stage: DiagnosticStage,
    name: &'static str,
    axes: &saddle_core::DiagnosticOutcomeAxes,
) -> (
    saddle_core::BoundedDiagnostic,
    Option<saddle_observability::DiagnosticSubmission>,
) {
    let diagnostic = saddle_core::BoundedDiagnostic::capture(
        DiagnosticCategory::UnexpectedError,
        CaptureSite::FirstObserved,
        saddle_core::BoundedDiagnosticCause::new(stage, code(name)),
    );
    let submission = OUTPUT
        .get()
        .map(|output| output.submit_bounded(Some(&diagnostic), axes, None));
    #[cfg(test)]
    if name == "runtime.driver_ledger_shutdown_failed"
        && std::env::var_os("RUNTIME_LEDGER_SOURCE_TEST").is_some()
    {
        // Fixed test-only observation of submission before the real abort.
        // NOT writer acknowledgement; never available in published builds.
        eprintln!("RUNTIME_LEDGER_SOURCE_SUBMISSION={submission:?}");
    }
    (diagnostic, submission)
}

#[track_caller]
pub(crate) fn request_stop_source(
    timed_out: bool,
    physical_return: bool,
    stage: DiagnosticStage,
    context: Option<(&CallContext, &EventContext)>,
) -> saddle_core::DiagnosticOccurrence {
    let diagnostic = saddle_core::BoundedDiagnostic::capture(
        DiagnosticCategory::ExpectedRejection,
        CaptureSite::FirstObserved,
        saddle_core::BoundedDiagnosticCause::new(
            stage,
            code(if physical_return && timed_out {
                "runtime.physical_return_deadline"
            } else if physical_return {
                "runtime.physical_return_cancelled"
            } else if timed_out {
                "runtime.scope_deadline"
            } else {
                "runtime.scope_cancelled"
            }),
        ),
    );
    if let Some(output) = OUTPUT.get() {
        let _submission = output.submit_bounded(
            Some(&diagnostic),
            &saddle_core::DiagnosticOutcomeAxes {
                operation: if physical_return {
                    saddle_core::OperationOutcome::Unknown
                } else if timed_out {
                    saddle_core::OperationOutcome::TimedOut
                } else {
                    saddle_core::OperationOutcome::Cancelled
                },
                ..Default::default()
            },
            context,
        );
    }
    diagnostic.occurrence()
}

pub(crate) fn boundary(
    occurrence: Option<saddle_core::DiagnosticOccurrence>,
    axes: &saddle_core::DiagnosticOutcomeAxes,
    context: Option<(&CallContext, &EventContext)>,
) {
    if let Some(output) = OUTPUT.get() {
        let _submission = output.submit_boundary(occurrence, axes, context);
    }
}

/// Abort is unchanged. A finite submission is not a written acknowledgement;
/// the existing sink records Full/Closed/encoding degradation when available.
#[track_caller]
pub(crate) fn finalizer_contract_abort(name: &'static str) -> ! {
    let _source = bounded_source(
        DiagnosticStage::FinalizerResource,
        name,
        &saddle_core::DiagnosticOutcomeAxes {
            cleanup: saddle_core::CleanupOutcome::Failed,
            ..Default::default()
        },
    );
    std::process::abort()
}

pub(crate) fn emit(diagnostic: &Diagnostic, context: Option<&RequestContext>) {
    if let Some(output) = OUTPUT.get() {
        if let Some((observer, call, event)) = context {
            let _ = observer.record_diagnostic(diagnostic, output, Some((call, event)));
        } else {
            let _ = output.submit(diagnostic);
        }
    }
    // Absence/Full/Closed is NOT a delivery acknowledgement. Facade retains
    // the writer owner and must inspect its snapshot at the ORIGINAL deadline.
}

#[track_caller]
pub(crate) fn failure(
    stage: DiagnosticStage,
    category: DiagnosticCategory,
    name: &'static str,
) -> Diagnostic {
    Diagnostic::capture(
        category,
        CaptureSite::FirstObserved,
        DiagnosticCause::new(stage, code(name)),
    )
}

/// Invoke at the existing catch boundary, INSIDE Admission's admitted poll.
/// CURRENT is replaced/restored per synchronous poll, never held across await.
pub(crate) fn catching<T>(
    stage: DiagnosticStage,
    task: &'static str,
    context: Option<RequestContext>,
    f: impl FnOnce() -> T,
) -> Result<T, Diagnostic> {
    catching_cleanup(stage, task, context, None, f)
}

/// Cleanup keeps its own origin and links the existing primary BEFORE source
/// submission. No recapture, cloned diagnostic, or change to the business result.
pub(crate) fn catching_cleanup<T>(
    stage: DiagnosticStage,
    task: &'static str,
    context: Option<RequestContext>,
    primary: Option<Diagnostic>,
    f: impl FnOnce() -> T,
) -> Result<T, Diagnostic> {
    let previous = CURRENT.with(|slot| {
        slot.replace(Some(Frame {
            stage,
            task,
            context,
            panic: None,
            primary,
            request_mode: false,
            request_panic: None,
            request_primary: None,
            cleanup_occurrence: None,
            request_scope: None,
            request_output: None,
        }))
    });
    let outcome = catch_unwind(AssertUnwindSafe(f));
    let frame = CURRENT
        .with(|slot| slot.replace(previous))
        .expect("matching synchronous diagnostic frame");
    match outcome {
        Ok(value) => Ok(value),
        Err(payload) => {
            // An inner managed poll has already captured and emitted this
            // occurrence. resume_unwind does not invoke the hook a second time.
            if let Ok(diagnostic) = payload.downcast::<Diagnostic>() {
                return Err(*diagnostic);
            }
            let diagnostic = frame.panic.unwrap_or_else(|| {
                let mut d = failure(
                    stage,
                    DiagnosticCategory::Panic,
                    "runtime.panic_without_hook",
                )
                .with_task(code(task));
                if let Some(primary) = frame.primary.as_ref() {
                    d = d.during_cleanup_of(primary);
                }
                emit(&d, frame.context.as_ref());
                d
            });
            Err(diagnostic)
        }
    }
}

pub(crate) fn catching_request<T>(
    stage: DiagnosticStage,
    task: &'static str,
    context: Option<RequestContext>,
    request_scope: Option<saddle_observability::RequestDiagnosticScope<'static>>,
    primary: Option<RequestCaptured>,
    f: impl FnOnce() -> T,
) -> (Result<T, RequestCaptured>, Option<RequestCaptured>) {
    catching_request_with_output(stage, task, context, request_scope, OUTPUT.get().cloned(), primary, f)
}

pub(crate) fn catching_request_with_output<T>(
    stage: DiagnosticStage,
    task: &'static str,
    context: Option<RequestContext>,
    request_scope: Option<saddle_observability::RequestDiagnosticScope<'static>>,
    request_output: Option<EmergencyDiagnosticHandle>,
    primary: Option<RequestCaptured>,
    f: impl FnOnce() -> T,
) -> (Result<T, RequestCaptured>, Option<RequestCaptured>) {
    let previous = CURRENT.with(|slot| {
        slot.replace(Some(Frame {
            stage,
            task,
            context,
            panic: None,
            primary: None,
            request_mode: true,
            request_panic: None,
            request_primary: primary,
            cleanup_occurrence: None,
            request_scope,
            request_output,
        }))
    });
    let outcome = catch_unwind(AssertUnwindSafe(f));
    let mut frame = CURRENT
        .with(|slot| slot.replace(previous))
        .expect("synchronous request frame");
    let outcome = match outcome {
        Ok(value) => Ok(value),
        Err(payload) => match payload.downcast::<RequestCaptured>() {
            Ok(captured) => Err(*captured),
            Err(payload) => match payload.downcast::<Diagnostic>() {
                // Legacy inner managed poll already emitted this object.
                // Retain it, but never manufacture a submission receipt later.
                Ok(diagnostic) => Err(RequestCaptured::MissingContext(*diagnostic)),
                Err(_) => Err(frame.request_panic.take().unwrap_or_else(|| {
                    let mut diagnostic = failure(
                        stage,
                        DiagnosticCategory::Panic,
                        "runtime.panic_without_hook",
                    )
                    .with_task(code(task));
                    if let Some(primary) = frame.request_primary.as_ref() {
                        diagnostic = diagnostic.during_cleanup_of(primary.diagnostic());
                    }
                    if let Some(primary) = frame.cleanup_occurrence.as_ref() {
                        diagnostic = diagnostic.during_cleanup_of_occurrence(primary);
                    }
                    capture_request(
                        diagnostic,
                        frame.context.as_ref(),
                        frame.request_scope.as_ref(),
                        frame.request_output.as_ref(),
                    )
                })),
            },
        },
    };
    (outcome, frame.request_primary)
}

pub(crate) fn link_task_cleanup(primary: Option<saddle_core::DiagnosticOccurrence>) {
    CURRENT.with(|slot| {
        if let Some(frame) = slot.borrow_mut().as_mut() {
            if frame.request_mode && frame.task == "runtime.formal_request_task_drop" {
                frame.cleanup_occurrence = primary;
            }
        }
    });
}

pub(crate) async fn task<F: Future>(
    future: F,
    stage: DiagnosticStage,
    name: &'static str,
) -> F::Output {
    let mut future = std::pin::pin!(future);
    std::future::poll_fn(|cx| {
        match catching(stage, name, None, || {
            let poll = future.as_mut().poll(cx);
            #[cfg(test)]
            if poll.is_ready()
                && name == "runtime.managed_request_task"
                && std::env::var_os("RUNTIME_DIAGNOSTIC_MANAGER_FAULT").is_some()
            {
                // Private fixed manager failure AFTER the envelope returned,
                // not a handler panic; compiled out of published artifacts.
                panic!("DIAGNOSTIC_PRIVATE_SENTINEL");
            }
            poll
        }) {
            Ok(poll) => poll,
            Err(diagnostic) => resume_unwind(Box::new(diagnostic)),
        }
    })
    .await
}

pub(crate) fn joined(error: tokio::task::JoinError) {
    if error.is_cancelled() {
        boundary(
            None,
            &saddle_core::DiagnosticOutcomeAxes {
                operation: saddle_core::OperationOutcome::Cancelled,
                ..Default::default()
            },
            None,
        );
        return;
    }
    if error.is_panic() {
        let payload = error.into_panic();
        if let Ok(diagnostic) = payload.downcast::<Diagnostic>() {
            boundary(
                Some(diagnostic.occurrence()),
                &saddle_core::DiagnosticOutcomeAxes {
                    operation: saddle_core::OperationOutcome::Panicked,
                    ..Default::default()
                },
                None,
            );
            return;
        } // already emitted at original poll
    }
    let d = failure(
        DiagnosticStage::BackgroundTask,
        DiagnosticCategory::UnexpectedError,
        "runtime.task_join_failed",
    );
    emit(&d, None);
    boundary(
        Some(d.occurrence()),
        &saddle_core::DiagnosticOutcomeAxes {
            operation: saddle_core::OperationOutcome::Panicked,
            ..Default::default()
        },
        None,
    );
}

#[track_caller]
pub(crate) fn attach(
    error: SaddleError,
    stage: DiagnosticStage,
    name: &'static str,
) -> SaddleError {
    if error.diagnostic().is_some() {
        error
    } else {
        error.with_diagnostic(failure(stage, DiagnosticCategory::UnexpectedError, name))
    }
}

pub(crate) fn report(error: &SaddleError) {
    if let Some(d) = error.diagnostic() {
        emit(d, None);
    }
}

pub(crate) fn cleanup(
    error: SaddleError,
    primary: Option<&SaddleError>,
    stage: DiagnosticStage,
) -> SaddleError {
    let mut error = attach(error, stage, "runtime.cleanup_failed");
    if let Some(primary) = primary {
        error = error.during_cleanup_of(primary);
    }
    report(&error);
    error
}