saddle-runtime 0.3.12

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
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
//! Framework/Database composition only. No business-facing authority issuer.
use super::*;

pub(super) enum NextScope {
    Continuation(saddle_core::DbScopeContinuation),
    Pair(DbPhysicalRequestHalf, DbPhysicalExecutionHalf),
}

/// Same request and pinned cancellation source across all serial scopes.
/// No Clone, raw constructor, deadline reset or new request admission.
#[doc(hidden)]
pub struct ProfuseGwSerialScope<C> {
    lease: ProfuseGwConcreteDbRequestLease,
    cancel: Pin<Box<C>>,
    entry: ScopeEntry,
}

enum ScopeEntry {
    Entered,
    ResumedUnused,
}

/// DB retains this beside its owning phase, not inside the borrowed body.
/// Observability's consumer can spell the exact Core type without Runtime.
#[doc(hidden)]
pub type ProfuseGwTransactionObservation =
    saddle_core::DbScopeObservation<(Observer, CallContext, EventContext)>;

#[derive(Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum ProfuseGwTransactionObservationError {
    MissingContext,
    Unavailable,
}

/// ```compile_fail
/// use saddle_runtime::profusegw::ProfuseGwSerialScope;
/// fn duplicate<C>(owner: ProfuseGwSerialScope<C>) { let _ = owner.clone(); }
/// ```
/// ```compile_fail
/// use saddle_runtime::profusegw::ProfuseGwSerialScope;
/// fn forge<C>() -> ProfuseGwSerialScope<C> { ProfuseGwSerialScope {} }
/// ```
/// ```compile_fail
/// use saddle_runtime::profusegw::ProfuseGwSerialScope;
/// use std::future::Future;
/// fn replay<C: Future<Output=()>>(owner: ProfuseGwSerialScope<C>) {
///     let _ = owner.into_physical_finalization();
///     let _ = owner.into_physical_finalization();
/// }
/// ```
impl<C> ProfuseGwSerialScope<C> {}

impl ProfuseGwConcreteDbRequestLease {
    #[doc(hidden)]
    pub fn into_serial_scope<C: Future<Output = ()>>(self, cancel: C) -> ProfuseGwSerialScope<C> {
        ProfuseGwSerialScope {
            lease: self,
            cancel: Box::pin(cancel),
            entry: ScopeEntry::Entered,
        }
    }
}

struct Control<'a, C> {
    deadline: &'a mut ProfuseGwManagedDeadline,
    stop: &'a mut Option<ProfuseGwScopeStop>,
    cancel: Pin<&'a mut C>,
    supervising: bool,
}

impl<C: Future<Output = ()>> Control<'_, C> {
    fn check(&mut self, cx: &mut Context<'_>) -> Result<(), ProfuseGwScopeStop> {
        if let Some(stop) = *self.stop {
            return Err(stop);
        }
        let stop = if self.cancel.as_mut().poll(cx).is_ready() {
            Some(ProfuseGwScopeStop::Cancelled)
        } else if tokio::time::Instant::now() >= self.deadline.timer.deadline()
            || self.deadline.timer.as_mut().poll(cx).is_ready()
        {
            Some(ProfuseGwScopeStop::TimedOut)
        } else {
            None
        };
        *self.stop = stop;
        stop.map_or(Ok(()), Err)
    }
}

/// Borrowed supervisor and step checkpoint share one control, not a second
/// timer. A DB session may borrow this driver while its body is supervised.
#[doc(hidden)]
pub struct ProfuseGwScopeDriver<'a, C> {
    execution: &'a ProfuseGwLightweightExecutionOwner,
    control: Mutex<Control<'a, C>>,
}

#[derive(Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum ProfuseGwScopeFailure {
    Stopped(ProfuseGwScopeStop),
    Panicked,
    AlreadySupervised,
    ScopeAlreadyEntered,
}

impl<C: Future<Output = ()>> ProfuseGwSerialScope<C> {
    /// Scope entry only: clones safe log context, never request/physical
    /// authority. Failure does not alter the timer, credits or physical path.
    #[doc(hidden)]
    pub fn take_transaction_observation(
        &mut self,
    ) -> Result<ProfuseGwTransactionObservation, ProfuseGwTransactionObservationError> {
        let observation = self
            .lease
            .observation
            .as_ref()
            .ok_or(ProfuseGwTransactionObservationError::MissingContext)?;
        let context = (
            observation.observer.clone(),
            observation.context.clone(),
            observation.event_context.clone(),
        );
        let correlation = self
            .lease
            .db_request
            .take_scope_observation(&self.lease.db_execution, context)
            .map_err(|_| ProfuseGwTransactionObservationError::Unavailable)?;
        self.entry = ScopeEntry::Entered;
        Ok(correlation)
    }

    #[doc(hidden)]
    pub fn driver(&mut self) -> ProfuseGwScopeDriver<'_, C> {
        self.entry = ScopeEntry::Entered;
        self.borrow_driver()
    }

    fn borrow_driver(&mut self) -> ProfuseGwScopeDriver<'_, C> {
        ProfuseGwScopeDriver {
            execution: &self.lease.execution,
            control: Mutex::new(Control {
                deadline: &mut self.lease.deadline,
                stop: &mut self.lease.scope_stop,
                cancel: self.cancel.as_mut(),
                supervising: false,
            }),
        }
    }

    /// Between scopes, outbound/business awaits are still admitted and timed.
    /// This does not enter another DB scope or acquire a connection.
    #[doc(hidden)]
    pub async fn supervise_between<F: Future>(
        &mut self,
        future: F,
    ) -> Result<F::Output, ProfuseGwScopeFailure> {
        if matches!(self.entry, ScopeEntry::Entered) {
            return Err(ProfuseGwScopeFailure::ScopeAlreadyEntered);
        }
        self.borrow_driver().supervise(future).await
    }

    /// Final response after resuming but never entering another scope. The
    /// reserved NEXT scope is NotUsed; prior physical disposition/T is not
    /// replayed. Once driver() is requested, DB physical finalization is required.
    #[doc(hidden)]
    #[allow(
        clippy::result_large_err,
        reason = "return the exact linear whole and value without a new allocation"
    )]
    pub fn finish_unentered_response<T>(self, value: T) -> Result<T, (Self, T)> {
        if matches!(self.entry, ScopeEntry::Entered) {
            return Err((self, value));
        }
        let ProfuseGwConcreteDbRequestLease {
            execution,
            deadline,
            db_request,
            db_execution,
            observation,
            scope_stop,
        } = self.lease;
        match seal_db_request_not_used(db_request, db_execution, value) {
            Ok(receipt) => {
                record_terminal(observation, execution.cancel_observed());
                drop(deadline);
                Ok(receipt.into_value())
            }
            Err((db_request, db_execution, value)) => Err((
                Self {
                    lease: ProfuseGwConcreteDbRequestLease {
                        execution,
                        deadline,
                        db_request,
                        db_execution,
                        observation,
                        scope_stop,
                    },
                    cancel: self.cancel,
                    entry: self.entry,
                },
                value,
            )),
        }
    }

    /// Only after all borrowed futures/driver are destroyed may DB transfer
    /// its owning phase/connection into physical finalization.
    #[doc(hidden)]
    pub fn into_physical_finalization(
        self,
    ) -> (ProfuseGwSerialCompletion<C>, DbPhysicalExecutionHalf) {
        let (completion, execution) = self
            .lease
            .into_physical_finalization()
            .into_database_execution();
        (
            ProfuseGwSerialCompletion {
                completion,
                cancel: self.cancel,
            },
            execution,
        )
    }
}

impl<C: Future<Output = ()>> ProfuseGwScopeDriver<'_, C> {
    /// Required at business entry, SQL entry/exit and immediately before COMMIT.
    #[doc(hidden)]
    pub async fn checkpoint(&self) -> Result<(), ProfuseGwScopeStop> {
        let mut yielded = false;
        poll_fn(|cx| {
            let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
            if let Err(stop) = control.check(cx) {
                return Poll::Ready(Err(stop));
            }
            if !yielded {
                yielded = true;
                cx.waker().wake_by_ref();
                Poll::Pending
            } else {
                Poll::Ready(Ok(()))
            }
        })
        .await
    }

    /// Governs the ENTIRE body, including non-DB Pending awaits. Never hold
    /// the control lock while polling the body (steps borrow it recursively).
    /// Body is destroyed before returning stop/panic to the owning DB phase.
    #[doc(hidden)]
    pub async fn supervise<F: Future>(
        &self,
        future: F,
    ) -> Result<F::Output, ProfuseGwScopeFailure> {
        {
            let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
            if control.supervising {
                return Err(ProfuseGwScopeFailure::AlreadySupervised);
            }
            control.supervising = true;
        }
        let mut guard = SupervisionGuard {
            control: &self.control,
            completed: false,
        };
        let mut future = Box::pin(future);
        let outcome = poll_fn(|cx| {
            {
                let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
                if let Err(stop) = control.check(cx) {
                    return Poll::Ready(Err(ProfuseGwScopeFailure::Stopped(stop)));
                }
            }
            // Catch BUSINESS unwind inside the admitted poll boundary. Catching
            // outside would unwind the allocator TLS guard and permanently
            // poison the account before physical cleanup could run.
            let mut caught =
                poll_fn(
                    |cx| match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
                        Ok(Poll::Pending) => Poll::Pending,
                        Ok(Poll::Ready(value)) => Poll::Ready(Ok(value)),
                        Err(_) => Poll::Ready(Err(())),
                    },
                );
            match self
                .execution
                .poll_database_query(Pin::new(&mut caught), cx)
            {
                Poll::Pending => Poll::Pending,
                Poll::Ready(Ok(value)) => {
                    // Preserve acknowledgement/business T even if its poll
                    // crossed the deadline. Sticky stop bars the next step;
                    // DB still owns commit certainty (never rewrite it).
                    let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
                    let _ = control.check(cx);
                    Poll::Ready(Ok(value))
                }
                Poll::Ready(Err(())) => {
                    let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
                    control.stop.get_or_insert(ProfuseGwScopeStop::Cancelled);
                    Poll::Ready(Err(ProfuseGwScopeFailure::Panicked))
                }
            }
        })
        .await;
        drop(future);
        guard.completed = true;
        outcome
    }
}

struct SupervisionGuard<'a, 'b, C> {
    control: &'a Mutex<Control<'b, C>>,
    completed: bool,
}
impl<C> Drop for SupervisionGuard<'_, '_, C> {
    fn drop(&mut self) {
        let mut control = self.control.lock().unwrap_or_else(|p| p.into_inner());
        if !self.completed {
            control.stop.get_or_insert(ProfuseGwScopeStop::Cancelled);
        }
        control.supervising = false;
    }
}

/// Keeps the original cancellation source alongside physical completion.
#[doc(hidden)]
pub struct ProfuseGwSerialCompletion<C> {
    completion: ProfuseGwDatabaseFinalizationCompletion,
    cancel: Pin<Box<C>>,
}

impl<C: Future<Output = ()>> ProfuseGwSerialCompletion<C> {
    /// Ready means stop physical return and discard; it is NOT a disposition.
    #[doc(hidden)]
    pub fn poll_physical_stop(&mut self, cx: &mut Context<'_>) -> Poll<()> {
        let mut control = Control {
            deadline: &mut self.completion.deadline,
            stop: &mut self.completion.scope_stop,
            cancel: self.cancel.as_mut(),
            supervising: false,
        };
        if control.check(cx).is_err() {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }

    #[doc(hidden)]
    #[allow(
        clippy::result_large_err,
        reason = "foreign receipt must return both complete owners"
    )]
    pub fn complete<T>(
        self,
        physical: DbPhysicalDispositionOwner<T>,
    ) -> Result<ProfuseGwSuspendedScope<C, T>, (Self, DbPhysicalDispositionOwner<T>)> {
        match finish_profusegw_database_disposition(self.completion, physical) {
            Ok(owner) => Ok(ProfuseGwSuspendedScope {
                inner: Some((owner, self.cancel)),
            }),
            Err(failure) => Err((
                Self {
                    completion: failure.completion,
                    cancel: self.cancel,
                },
                failure.physical,
            )),
        }
    }
}

/// Inert whole: Pending/drop of resume retains every owner. No execution
/// capability is exposed until the same time/cancel checkpoint succeeds.
#[doc(hidden)]
pub struct ProfuseGwSuspendedScope<C, T> {
    inner: Option<(ProfuseGwPostDatabaseManagedOwner<T>, Pin<Box<C>>)>,
}

#[derive(Debug)]
#[doc(hidden)]
pub enum ProfuseGwScopeResumeError {
    Consumed,
    Stopped(ProfuseGwScopeStop),
    ScopeExhausted,
    Admission(AdmissionError),
}

impl<C: Future<Output = ()>, T> ProfuseGwSuspendedScope<C, T> {
    #[doc(hidden)]
    pub async fn resume(
        &mut self,
    ) -> Result<(ProfuseGwSerialScope<C>, T), ProfuseGwScopeResumeError> {
        let (owner, cancel) = self
            .inner
            .as_mut()
            .ok_or(ProfuseGwScopeResumeError::Consumed)?;
        scope_checkpoint(
            &mut owner.terminal.deadline,
            &mut owner.terminal.scope_stop,
            cancel.as_mut(),
        )
        .await
        .map_err(ProfuseGwScopeResumeError::Stopped)?;
        // No await/callback from here until owner transfer is complete.
        let Some((owner, cancel)) = self.inner.take() else {
            return Err(ProfuseGwScopeResumeError::Consumed);
        };
        let ProfuseGwPostDatabaseManagedOwner { terminal, value } = owner;
        let ProfuseGwPostDatabaseRequestTerminal {
            admission,
            deadline,
            observation,
            scope_stop,
            next_scope,
        } = terminal;
        let pair = match next_scope {
            NextScope::Pair(request, execution) => (request, execution),
            NextScope::Continuation(continuation) => match continuation.into_next_scope() {
                Ok(pair) => pair,
                Err(continuation) => {
                    self.inner = Some((
                        ProfuseGwPostDatabaseManagedOwner {
                            terminal: ProfuseGwPostDatabaseRequestTerminal {
                                admission,
                                deadline,
                                observation,
                                scope_stop,
                                next_scope: NextScope::Continuation(continuation),
                            },
                            value,
                        },
                        cancel,
                    ));
                    return Err(ProfuseGwScopeResumeError::ScopeExhausted);
                }
            },
        };
        match admission.resume_after_runtime_checkpoint() {
            Ok(execution) => Ok((
                ProfuseGwSerialScope {
                    lease: ProfuseGwConcreteDbRequestLease {
                        execution,
                        deadline,
                        db_request: pair.0,
                        db_execution: pair.1,
                        observation,
                        scope_stop,
                    },
                    cancel,
                    entry: ScopeEntry::ResumedUnused,
                },
                value,
            )),
            Err((admission, error)) => {
                self.inner = Some((
                    ProfuseGwPostDatabaseManagedOwner {
                        terminal: ProfuseGwPostDatabaseRequestTerminal {
                            admission,
                            deadline,
                            observation,
                            scope_stop,
                            next_scope: NextScope::Pair(pair.0, pair.1),
                        },
                        value,
                    },
                    cancel,
                ));
                Err(ProfuseGwScopeResumeError::Admission(error))
            }
        }
    }

    /// Business value may be used to construct the final response; the terminal
    /// still holds all Admission resources until writeback/disconnect finish.
    #[doc(hidden)]
    #[allow(
        clippy::result_large_err,
        reason = "preserve the inert whole on repeated consumption"
    )]
    pub fn into_response_parts(
        mut self,
    ) -> Result<(T, ProfuseGwPostDatabaseRequestTerminal), Self> {
        match self.inner.take() {
            Some((owner, _cancel)) => Ok(owner.into_response_parts()),
            None => Err(self),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    fn process() -> ProfuseGwRuntimeProcess {
        process_capacity(1)
    }

    fn process_capacity(capacity: u32) -> ProfuseGwRuntimeProcess {
        let pending = saddle_admission::freeze_deployment_resource_budget(
            capacity, 32, 5_000, capacity, capacity, 1_000_000, 1_000_000, 1_000_000, 1_000_000,
        )
        .unwrap();
        let (application, listener) = saddle_core::BootstrapRendezvousIssuer::issue()
            .freeze_application(saddle_core::GeneratedApplicationFreezeSource::new(
                "app",
                b"descriptor",
                &["route"],
            ))
            .unwrap();
        let listener = listener
            .freeze_listener(saddle_core::ListenerStartupFreezeSource::new(
                "app",
                "127.0.0.1:8000".parse().unwrap(),
                "127.0.0.1:9000".parse().unwrap(),
                Duration::from_millis(5_000),
            ))
            .ok()
            .unwrap();
        let (whole, receipt) = saddle_core::pair_bootstrap_rendezvous(application, listener)
            .ok()
            .unwrap();
        let budget =
            saddle_admission::bind_deployment_resource_budget_bootstrap(pending, whole, receipt)
                .ok()
                .unwrap();
        ProfuseGwRuntimeProcess::new(prepare_profusegw_lightweight_profile(budget).ok().unwrap())
    }

    fn admit(process: &ProfuseGwRuntimeProcess) -> ProfuseGwConcreteDbRequestLease {
        match process.try_admit() {
            ProfuseGwCoordinatorAdmissionOutcome::Ready(dispatch, _) => {
                dispatch.into_database_request()
            }
            _ => panic!("admission must succeed"),
        }
    }

    fn full(process: &ProfuseGwRuntimeProcess) {
        assert!(matches!(
            process.try_admit(),
            ProfuseGwCoordinatorAdmissionOutcome::CapacityRejected(_)
        ));
    }

    #[tokio::test]
    async fn scope_observation_original_context_serial_and_zero() {
        let mut process = process();
        let physical = process.db_startup.take().unwrap().into_process_capability();
        let mut lease = admit(&process);
        let original_deadline = lease.deadline.timer.deadline();
        let observer = Observer::with_writer(
            saddle_observability::ObserverConfig::default(),
            std::io::sink(),
        )
        .unwrap();
        let (call, _) = observer
            .start_external_call_checked("app", "module", "service", "route", Some("safe-trace"))
            .unwrap();
        let context = call.context().clone();
        let event = EventContext::new(
            saddle_observability::RequestIdentity::new("request").unwrap(),
            saddle_observability::RouteIdentity::new("route").unwrap(),
            1,
        )
        .unwrap();
        lease.observation = Some(ProfuseGwRequestObservation {
            observer: observer.clone(),
            context: context.clone(),
            event_context: event.clone(),
        });
        let mut scope = lease.into_serial_scope(std::future::pending());
        for expected in [0, 1] {
            let saved = scope.lease.observation.take().unwrap();
            assert!(matches!(
                scope.take_transaction_observation(),
                Err(ProfuseGwTransactionObservationError::MissingContext)
            ));
            scope.lease.observation = Some(saved);
            let token = scope.take_transaction_observation().unwrap();
            assert!(matches!(
                scope.take_transaction_observation(),
                Err(ProfuseGwTransactionObservationError::Unavailable)
            ));
            assert_eq!(scope.lease.deadline.timer.deadline(), original_deadline);
            let (completion, execution) = scope.into_physical_finalization();
            let checked = token.bind_terminal(&execution).ok().unwrap();
            let ((_observer, actual_context, actual_event), fields) = checked.into_log_parts();
            assert_eq!(actual_context, context);
            assert_eq!(actual_event, event);
            assert_eq!(
                serde_json::to_value(fields).unwrap(),
                serde_json::json!({"transaction_scope":expected})
            );
            let proof = physical.connection_returned(execution, ()).ok().unwrap();
            let mut suspended = completion.complete(proof).ok().unwrap();
            full(&process);
            scope = suspended.resume().await.unwrap().0;
        }
        scope.finish_unentered_response(()).ok().unwrap();
        process.finish().unwrap();
        call.succeed();
        observer.flush().await.unwrap();
    }

    struct Cancel {
        requested: Arc<AtomicBool>,
        completed: bool,
    }
    impl Future for Cancel {
        type Output = ();
        fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
            assert!(
                !self.completed,
                "completed cancellation future polled twice"
            );
            if self.requested.load(Ordering::SeqCst) {
                self.completed = true;
                Poll::Ready(())
            } else {
                Poll::Pending
            }
        }
    }
    struct BorrowedPending<'a>(&'a mut bool);
    impl Future for BorrowedPending<'_> {
        type Output = ();
        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<()> {
            Poll::Pending
        }
    }
    impl Drop for BorrowedPending<'_> {
        fn drop(&mut self) {
            *self.0 = true;
        }
    }

    // Borrowing-only adapter matching DB SessionKernel::run_body at 8aad0787.
    // Not a SQL/kernel replacement: it tests the two lifetimes and Drop order.
    struct BorrowingSession<'driver, 'request, C> {
        driver: &'driver ProfuseGwScopeDriver<'request, C>,
        dropped: bool,
    }
    impl<C: Future<Output = ()> + Send> BorrowingSession<'_, '_, C> {
        async fn run_body<T>(
            &mut self,
            body: impl for<'tx> FnOnce(&'tx mut Self) -> Pin<Box<dyn Future<Output = T> + Send + 'tx>>,
        ) -> T {
            body(self).await
        }
    }

    #[tokio::test]
    async fn serial_scope_same_request_keeps_credit_timer_and_value() {
        let mut process = process();
        let physical = process.db_startup.take().unwrap().into_process_capability();
        let lease = admit(&process);
        let deadline = lease.deadline.timer.deadline();
        let mut scope = lease.into_serial_scope(std::future::pending());
        for value in [11, 22, 33] {
            {
                let driver = scope.driver();
                let body = async {
                    driver.checkpoint().await.unwrap();
                    driver.checkpoint().await.unwrap();
                    value
                };
                assert_eq!(driver.supervise(body).await.unwrap(), value);
            }
            let (completion, execution) = scope.into_physical_finalization();
            let disposition = physical.connection_returned(execution, value).ok().unwrap();
            let mut suspended = completion.complete(disposition).ok().unwrap();
            full(&process);
            let (next, held_value) = suspended.resume().await.unwrap();
            assert_eq!(held_value, value);
            assert_eq!(next.lease.deadline.timer.deadline(), deadline);
            assert!(matches!(
                suspended.resume().await,
                Err(ProfuseGwScopeResumeError::Consumed)
            ));
            scope = next;
        }
        let (completion, execution) = scope.into_physical_finalization();
        let disposition = physical
            .connection_discarded(execution, "Unknown preserved")
            .ok()
            .unwrap();
        let suspended = completion.complete(disposition).ok().unwrap();
        let (value, terminal) = suspended.into_response_parts().ok().unwrap();
        assert_eq!(value, "Unknown preserved");
        full(&process);
        finish_profusegw_after_database(terminal);
        process.finish().unwrap();
    }

    #[tokio::test]
    async fn serial_scope_non_db_pending_stop_drops_before_finalization() {
        for cancelled in [false, true] {
            let mut process = process();
            let physical = process.db_startup.take().unwrap().into_process_capability();
            let lease = admit(&process);
            let requested = Arc::new(AtomicBool::new(false));
            let mut scope = lease.into_serial_scope(Cancel {
                requested: requested.clone(),
                completed: false,
            });
            let dropped;
            {
                let driver = scope.driver();
                let mut session = BorrowingSession {
                    driver: &driver,
                    dropped: false,
                };
                let supervised = driver.supervise(session.run_body(|session| {
                    Box::pin(async move {
                        session.driver.checkpoint().await.unwrap();
                        BorrowedPending(&mut session.dropped).await;
                    })
                }));
                // A generated boxed Send callback can borrow this same driver.
                fn require_send<T: Send>(_: &T) {}
                require_send(&supervised);
                {
                    tokio::pin!(supervised);
                    poll_fn(|cx| {
                        assert!(supervised.as_mut().poll(cx).is_pending());
                        Poll::Ready(())
                    })
                    .await;
                    // Second poll enters the non-DB pending body after checkpoint yield.
                    poll_fn(|cx| {
                        assert!(supervised.as_mut().poll(cx).is_pending());
                        Poll::Ready(())
                    })
                    .await;
                    if cancelled {
                        requested.store(true, Ordering::SeqCst);
                    } else {
                        // Deterministically expire the SAME timer only after
                        // observing the actual non-DB body Pending. Test-only.
                        driver
                            .control
                            .lock()
                            .unwrap()
                            .deadline
                            .timer
                            .as_mut()
                            .reset(tokio::time::Instant::now());
                    }
                    assert!(matches!(
                        supervised.await,
                        Err(ProfuseGwScopeFailure::Stopped(_))
                    ));
                }
                dropped = session.dropped;
            }
            assert!(
                dropped,
                "borrowed business future must die before phase finalizer"
            );
            let (mut completion, execution) = scope.into_physical_finalization();
            poll_fn(|cx| {
                assert!(completion.poll_physical_stop(cx).is_ready());
                Poll::Ready(())
            })
            .await;
            let disposition = physical.connection_discarded(execution, ()).ok().unwrap();
            let mut suspended = completion.complete(disposition).ok().unwrap();
            assert!(matches!(
                suspended.resume().await,
                Err(ProfuseGwScopeResumeError::Stopped(_))
            ));
            assert!(matches!(
                suspended.resume().await,
                Err(ProfuseGwScopeResumeError::Stopped(_))
            ));
            let (_, terminal) = suspended.into_response_parts().ok().unwrap();
            finish_profusegw_after_database(terminal);
            process.finish().unwrap();
        }
    }

    #[tokio::test]
    async fn serial_scope_dropped_supervision_is_sticky() {
        let mut process = process();
        let physical = process.db_startup.take().unwrap().into_process_capability();
        let mut scope = admit(&process).into_serial_scope(std::future::pending());
        let mut dropped = false;
        {
            let driver = scope.driver();
            let mut future = Box::pin(driver.supervise(BorrowedPending(&mut dropped)));
            poll_fn(|cx| {
                assert!(future.as_mut().poll(cx).is_pending());
                Poll::Ready(())
            })
            .await;
            drop(future);
            assert_eq!(
                driver.checkpoint().await,
                Err(ProfuseGwScopeStop::Cancelled)
            );
        }
        assert!(dropped);
        let (completion, execution) = scope.into_physical_finalization();
        let disposition = physical.connection_discarded(execution, ()).ok().unwrap();
        let mut suspended = completion.complete(disposition).ok().unwrap();
        assert!(matches!(
            suspended.resume().await,
            Err(ProfuseGwScopeResumeError::Stopped(_))
        ));
        let (_, terminal) = suspended.into_response_parts().ok().unwrap();
        finish_profusegw_after_database(terminal);
        process.finish().unwrap();
    }

    #[tokio::test]
    async fn serial_scope_resume_pending_drop_and_foreign_return_owners() {
        let mut a = process_capacity(2);
        let pa = a.db_startup.take().unwrap().into_process_capability();
        let (ca, ea) = admit(&a)
            .into_serial_scope(std::future::pending())
            .into_physical_finalization();
        let (cb, eb) = admit(&a)
            .into_serial_scope(std::future::pending())
            .into_physical_finalization();
        let ra = pa.connection_returned(ea, 1).ok().unwrap();
        let rb = pa.connection_discarded(eb, 2).ok().unwrap();
        let (ca, rb) = ca.complete(rb).err().unwrap();
        let (cb, ra) = cb.complete(ra).err().unwrap();
        full(&a);
        let mut suspended = ca.complete(ra).ok().unwrap();
        {
            let mut attempt = Box::pin(suspended.resume());
            poll_fn(|cx| {
                assert!(attempt.as_mut().poll(cx).is_pending());
                Poll::Ready(())
            })
            .await;
        }
        full(&a);
        let (mut scope, value) = suspended.resume().await.unwrap();
        assert_eq!(value, 1);
        assert_eq!(scope.supervise_between(async { 7 }).await.unwrap(), 7);
        full(&a);
        assert_eq!(scope.finish_unentered_response(value).ok().unwrap(), 1);
        let (_, terminal) = cb
            .complete(rb)
            .ok()
            .unwrap()
            .into_response_parts()
            .ok()
            .unwrap();
        finish_profusegw_after_database(terminal);
        a.finish().unwrap();
    }

    #[tokio::test]
    async fn serial_scope_ready_loop_and_panic_keep_terminal() {
        for panic_body in [false, true] {
            let mut process = process();
            let physical = process.db_startup.take().unwrap().into_process_capability();
            let mut lease = admit(&process);
            lease
                .deadline
                .timer
                .as_mut()
                .reset(tokio::time::Instant::now() + Duration::from_millis(5));
            let mut scope = lease.into_serial_scope(std::future::pending());
            {
                let driver = scope.driver();
                let result = driver
                    .supervise(async {
                        assert!(!panic_body, "injected business unwind");
                        loop {
                            driver.checkpoint().await?;
                        }
                        #[allow(unreachable_code)]
                        Ok::<(), ProfuseGwScopeStop>(())
                    })
                    .await;
                if panic_body {
                    assert!(matches!(result, Err(ProfuseGwScopeFailure::Panicked)));
                } else {
                    assert!(matches!(
                        result,
                        Err(ProfuseGwScopeFailure::Stopped(ProfuseGwScopeStop::TimedOut))
                            | Ok(Err(ProfuseGwScopeStop::TimedOut))
                    ));
                }
            }
            let (completion, execution) = scope.into_physical_finalization();
            let physical = physical.connection_discarded(execution, ()).ok().unwrap();
            let mut suspended = completion.complete(physical).ok().unwrap();
            assert!(matches!(
                suspended.resume().await,
                Err(ProfuseGwScopeResumeError::Stopped(_))
            ));
            let (_, terminal) = suspended.into_response_parts().ok().unwrap();
            finish_profusegw_after_database(terminal);
            process.finish().unwrap();
        }
    }

    #[tokio::test]
    async fn serial_scope_physical_expiry_and_restore_keep_stop() {
        let mut process = process();
        let physical = process.db_startup.take().unwrap().into_process_capability();
        let mut lease = admit(&process);
        let original_deadline = lease.deadline.timer.deadline();
        lease.scope_stop = Some(ProfuseGwScopeStop::Cancelled);
        let lease = lease.restore_dispatch().into_database_request();
        assert_eq!(lease.scope_stop, Some(ProfuseGwScopeStop::Cancelled));
        assert_eq!(lease.deadline.timer.deadline(), original_deadline);
        let scope = lease.into_serial_scope(std::future::poll_fn(|_| -> Poll<()> {
            panic!("sticky stop must not poll cancellation again")
        }));
        let (mut completion, execution) = scope.into_physical_finalization();
        poll_fn(|cx| {
            assert!(completion.poll_physical_stop(cx).is_ready());
            Poll::Ready(())
        })
        .await;
        let receipt = physical.connection_discarded(execution, ()).ok().unwrap();
        let mut suspended = completion.complete(receipt).ok().unwrap();
        assert!(matches!(
            suspended.resume().await,
            Err(ProfuseGwScopeResumeError::Stopped(
                ProfuseGwScopeStop::Cancelled
            ))
        ));
        let (_, terminal) = suspended.into_response_parts().ok().unwrap();
        finish_profusegw_after_database(terminal);
        process.finish().unwrap();

        let mut process = self::process();
        let physical = process.db_startup.take().unwrap().into_process_capability();
        let scope = admit(&process).into_serial_scope(std::future::pending());
        let (mut completion, execution) = scope.into_physical_finalization();
        completion
            .completion
            .deadline
            .timer
            .as_mut()
            .reset(tokio::time::Instant::now());
        poll_fn(|cx| {
            assert!(completion.poll_physical_stop(cx).is_ready());
            Poll::Ready(())
        })
        .await;
        let receipt = physical
            .connection_returned(execution, "committed fact remains")
            .ok()
            .unwrap();
        let mut suspended = completion.complete(receipt).ok().unwrap();
        assert!(matches!(
            suspended.resume().await,
            Err(ProfuseGwScopeResumeError::Stopped(
                ProfuseGwScopeStop::TimedOut
            ))
        ));
        let (value, terminal) = suspended.into_response_parts().ok().unwrap();
        assert_eq!(value, "committed fact remains");
        finish_profusegw_after_database(terminal);
        process.finish().unwrap();
    }
}