snip-sync 0.2.0

gRPC sync server for snp snippet manager
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
//! Server shutdown orchestration.
//!
//! Provides the single production implementation of service-lifetime
//! coordination used by both `serve_inner` and deterministic tests.

use std::time::Duration;

/// Supervise Tonic and EggServe while preserving EggServe's typed terminal result.
pub async fn run_eggserve_services_until_shutdown<F>(
    mut shutdown_future: std::pin::Pin<&mut F>,
    mut grpc_handle: tokio::task::JoinHandle<Result<(), tonic::transport::Error>>,
    http_control: eggserve_server::ServerControl,
    mut http_completion: eggserve_server::ServerCompletion,
    shutdown_sender: tokio::sync::broadcast::Sender<()>,
    drain_timeout: Duration,
) -> ServiceShutdownOutcome
where
    F: std::future::Future<Output = ()>,
{
    let mut requested = false;
    let mut grpc_result = None;
    let mut http_result = None;

    tokio::select! {
        biased;
        _ = &mut shutdown_future => requested = true,
        result = &mut grpc_handle => grpc_result = Some(classify_result(result)),
        result = http_completion.wait() => {
            http_result = Some(match result {
                Ok(_) => ServiceResult::Clean,
                Err(error) => ServiceResult::ServiceError(error.to_string()),
            });
        }
    }

    let _ = shutdown_sender.send(());
    http_control.shutdown();

    let drain_result = tokio::time::timeout(drain_timeout, async {
        while grpc_result.is_none() || http_result.is_none() {
            tokio::select! {
                result = &mut grpc_handle, if grpc_result.is_none() => {
                    grpc_result = Some(classify_result(result));
                }
                result = http_completion.wait(), if http_result.is_none() => {
                    http_result = Some(match result {
                        Ok(_) => ServiceResult::Clean,
                        Err(error) => ServiceResult::ServiceError(error.to_string()),
                    });
                }
            }
        }
    })
    .await;

    let forced = drain_result.is_err();
    if forced {
        grpc_handle.abort();
        if grpc_result.is_none() {
            grpc_result = Some(classify_result(grpc_handle.await));
        }
        if http_result.is_none() {
            // EggServe owns its bounded connection drain. Await its typed
            // completion so no runtime task is detached from the process.
            http_result = Some(match http_completion.wait().await {
                Ok(_) => ServiceResult::Clean,
                Err(error) => ServiceResult::ServiceError(error.to_string()),
            });
        }
    }

    ServiceShutdownOutcome {
        requested,
        forced,
        grpc_result: grpc_result.unwrap_or_else(|| ServiceResult::Cancelled("not observed".into())),
        http_result: http_result.unwrap_or_else(|| ServiceResult::Cancelled("not observed".into())),
    }
}

/// Terminal classification of a service task result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServiceResult {
    /// Task returned `Ok(())`.
    Clean,
    /// Task returned `Ok(Err(e))` — a service-level error.
    ServiceError(String),
    /// Task returned `Err(JoinError)` where `is_panic()` is true.
    Panic(String),
    /// Task was cancelled (explicitly aborted).
    Cancelled(String),
}

/// Result of the shutdown orchestration.
#[derive(Debug)]
pub struct ServiceShutdownOutcome {
    /// `true` when the shutdown was triggered by a process signal
    /// (Ctrl-C / SIGTERM). `false` when an unexpected service completion
    /// triggered shutdown.
    pub requested: bool,
    /// `true` when the drain timed out and unfinished tasks were forcibly
    /// aborted.
    pub forced: bool,
    /// Terminal result of the gRPC service.
    pub grpc_result: ServiceResult,
    /// Terminal result of the HTTP service.
    pub http_result: ServiceResult,
}

impl ServiceShutdownOutcome {
    /// A requested shutdown succeeds only when both services returned
    /// cleanly without forced abort.
    pub fn is_clean_requested_shutdown(&self) -> bool {
        self.requested
            && !self.forced
            && self.grpc_result == ServiceResult::Clean
            && self.http_result == ServiceResult::Clean
    }

    /// Production decision method used by `serve_inner`. Returns `Ok(())`
    /// only for a requested, unforced, dual-clean shutdown. Returns an
    /// `Err` containing both service classifications and the original
    /// detail for every other case: forced abort, unexpected clean exit,
    /// or any service error/panic.
    pub fn ensure_clean_requested_shutdown(&self) -> Result<(), String> {
        if self.is_clean_requested_shutdown() {
            return Ok(());
        }

        Err(format!(
            "service shutdown was not clean: requested={}, forced={}, grpc={:?}, http={:?}",
            self.requested, self.forced, self.grpc_result, self.http_result,
        ))
    }
}

/// Classify a `JoinHandle` output into a `ServiceResult`.
fn classify_result(
    result: Result<Result<(), impl std::fmt::Display>, tokio::task::JoinError>,
) -> ServiceResult {
    match result {
        Ok(Ok(())) => ServiceResult::Clean,
        Ok(Err(e)) => ServiceResult::ServiceError(e.to_string()),
        Err(e) if e.is_panic() => ServiceResult::Panic(format!("{e}")),
        Err(e) => ServiceResult::Cancelled(format!("{e}")),
    }
}

/// Run two service task handles until a shutdown signal or unexpected
/// service completion, then drain with a bounded timeout.
///
/// This is the single production orchestration implementation used by
/// both `serve_inner` and deterministic orchestration tests.
///
/// # Arguments
/// * `shutdown_future` — a future that completes when a process signal
///   is received.
/// * `grpc_handle` — the gRPC service JoinHandle.
/// * `http_handle` — the HTTP service JoinHandle.
/// * `shutdown_sender` — broadcast sender to notify services of shutdown.
/// * `drain_timeout` — maximum time to wait for services to drain after
///   shutdown.
#[cfg(test)]
pub async fn run_services_until_shutdown<F>(
    mut shutdown_future: std::pin::Pin<&mut F>,
    grpc_handle: tokio::task::JoinHandle<Result<(), tonic::transport::Error>>,
    http_handle: tokio::task::JoinHandle<Result<(), std::io::Error>>,
    shutdown_sender: tokio::sync::broadcast::Sender<()>,
    drain_timeout: Duration,
) -> ServiceShutdownOutcome
where
    F: std::future::Future<Output = ()>,
{
    let mut requested = false;

    let mut grpc_result: Option<ServiceResult> = None;
    let mut http_result: Option<ServiceResult> = None;

    // Keep abort handles for the original service tasks. The JoinSet below
    // owns wrapper tasks that classify those handles; aborting only the
    // wrappers would detach the actual service tasks on a forced drain.
    let grpc_abort = grpc_handle.abort_handle();
    let http_abort = http_handle.abort_handle();

    #[derive(Clone, Copy)]
    enum ServiceKind {
        Grpc,
        Http,
    }

    struct ServiceCompletion {
        kind: ServiceKind,
        result: ServiceResult,
    }

    let mut tasks = tokio::task::JoinSet::<ServiceCompletion>::new();
    tasks.spawn(async move {
        ServiceCompletion {
            kind: ServiceKind::Grpc,
            result: classify_result(grpc_handle.await),
        }
    });
    tasks.spawn(async move {
        ServiceCompletion {
            kind: ServiceKind::Http,
            result: classify_result(http_handle.await),
        }
    });

    let record = |completion: ServiceCompletion,
                  grpc_result: &mut Option<ServiceResult>,
                  http_result: &mut Option<ServiceResult>,
                  phase: &str| {
        if completion.result != ServiceResult::Clean {
            let name = match completion.kind {
                ServiceKind::Grpc => "gRPC",
                ServiceKind::Http => "HTTP",
            };
            tracing::error!("{name} service {phase}: {:?}", completion.result);
        }
        match completion.kind {
            ServiceKind::Grpc => *grpc_result = Some(completion.result),
            ServiceKind::Http => *http_result = Some(completion.result),
        }
    };

    // Phase 1: Wait for the first terminal event — a shutdown signal,
    // gRPC completion, or HTTP completion. No pre-signal lifetime
    // timeout; the server runs indefinitely until a signal or failure.
    tokio::select! {
        biased;
        _ = &mut shutdown_future => {
            tracing::info!("Shutdown signal received");
            requested = true;
        }
        completion = tasks.join_next() => {
            if let Some(Ok(completion)) = completion {
                record(completion, &mut grpc_result, &mut http_result, "completed");
            }
        }
    }

    // Broadcast shutdown to both services.
    let _ = shutdown_sender.send(());

    // Phase 2: drain every remaining task under one bounded timeout.
    let drain_result = tokio::time::timeout(drain_timeout, async {
        while let Some(joined) = tasks.join_next().await {
            if let Ok(completion) = joined {
                record(
                    completion,
                    &mut grpc_result,
                    &mut http_result,
                    "during drain",
                );
            }
        }
    })
    .await;

    // Phase 3: abort the original service tasks and drain the wrapper join
    // records so cancellation is observed through the original handles.
    let forced = drain_result.is_err();
    if forced {
        tracing::warn!(
            "Graceful shutdown timed out after {}s, aborting remaining tasks",
            drain_timeout.as_secs()
        );

        grpc_abort.abort();
        http_abort.abort();
        while let Some(joined) = tasks.join_next().await {
            if let Ok(completion) = joined {
                record(
                    completion,
                    &mut grpc_result,
                    &mut http_result,
                    "after abort",
                );
            }
        }
    }

    ServiceShutdownOutcome {
        requested,
        forced,
        grpc_result: grpc_result
            .unwrap_or_else(|| ServiceResult::Cancelled("not observed".to_owned())),
        http_result: http_result
            .unwrap_or_else(|| ServiceResult::Cancelled("not observed".to_owned())),
    }
}

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

    type GrpcHandle = tokio::task::JoinHandle<Result<(), tonic::transport::Error>>;
    type HttpHandle = tokio::task::JoinHandle<Result<(), std::io::Error>>;

    // ── Section 7.1: Requested clean shutdown ──────────────────────

    #[tokio::test]
    async fn requested_clean_shutdown() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = tokio::spawn({
            let mut rx = tx.subscribe();
            async move {
                let _ = rx.recv().await;
                Ok(())
            }
        });
        let http: HttpHandle = tokio::spawn({
            let mut rx = tx.subscribe();
            async move {
                let _ = rx.recv().await;
                Ok(())
            }
        });

        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal completes immediately so the helper itself must be the
        // sole sender on the broadcast shutdown channel. Services cannot
        // wake from any test-side send.
        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(outcome.requested);
        assert!(!outcome.forced);
        assert!(outcome.is_clean_requested_shutdown());
        assert!(
            outcome.ensure_clean_requested_shutdown().is_ok(),
            "production decision method must return Ok for clean requested shutdown"
        );
        assert_eq!(outcome.grpc_result, ServiceResult::Clean);
        assert_eq!(outcome.http_result, ServiceResult::Clean);
    }

    // ── Section 7.2: One service completes during drain, sibling times out ──

    #[tokio::test]
    async fn one_service_completes_sibling_times_out() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);
        let grpc_await_count = Arc::new(AtomicUsize::new(0));
        let http_drop_count = Arc::new(AtomicUsize::new(0));

        let grpc: GrpcHandle = {
            let count = grpc_await_count.clone();
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                count.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        };
        // HTTP never completes — it ignores the shutdown signal.
        let http: HttpHandle = {
            let drop_count = http_drop_count.clone();
            tokio::spawn(async move {
                struct DropProbe(Arc<AtomicUsize>);
                impl Drop for DropProbe {
                    fn drop(&mut self) {
                        self.0.fetch_add(1, Ordering::SeqCst);
                    }
                }

                let _probe = DropProbe(drop_count);
                std::future::pending::<Result<(), std::io::Error>>().await
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_millis(100)).await;

        assert!(outcome.requested);
        assert!(outcome.forced);
        assert_eq!(outcome.grpc_result, ServiceResult::Clean);
        assert_eq!(
            grpc_await_count.load(Ordering::SeqCst),
            1,
            "gRPC future should have completed exactly once"
        );
        assert!(matches!(outcome.http_result, ServiceResult::Cancelled(_)));
        assert_eq!(
            http_drop_count.load(Ordering::SeqCst),
            1,
            "the underlying HTTP future must be dropped before the helper returns"
        );
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("forced shutdown must fail production check");
        assert!(
            err.contains("forced=true"),
            "diagnostic should mention forced: {err}"
        );
    }

    // ── Section 7.4: Drain-time service panic ──────────────────────

    #[tokio::test]
    async fn drain_time_service_panic() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                panic!("grpc drain panic");
            })
        };
        let http: HttpHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(outcome.requested);
        assert!(!outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        assert!(matches!(outcome.grpc_result, ServiceResult::Panic(_)));
        assert_eq!(outcome.http_result, ServiceResult::Clean);
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("panic must fail production check");
        assert!(
            err.contains("grpc"),
            "diagnostic should mention grpc: {err}"
        );
        assert!(
            err.contains("grpc drain panic"),
            "diagnostic should retain original panic detail: {err}"
        );
    }

    // ── Section 7.3: Drain-time service error ─────────────────────

    #[tokio::test]
    async fn drain_time_service_error() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        // gRPC returns cleanly after receiving shutdown.
        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };
        // HTTP returns an error after receiving shutdown.
        let http: HttpHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Err(std::io::Error::other("http service error"))
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(outcome.requested);
        assert!(!outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        assert_eq!(outcome.grpc_result, ServiceResult::Clean);
        assert!(matches!(
            outcome.http_result,
            ServiceResult::ServiceError(_)
        ));
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("drain-time error must fail production check");
        assert!(
            err.contains("http"),
            "diagnostic should mention http: {err}"
        );
        assert!(
            err.contains("http service error"),
            "diagnostic should retain original error detail: {err}"
        );
    }

    // ── Section 7.5: Unexpected service completion ─────────────────

    #[tokio::test]
    async fn unexpected_grpc_exit() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = tokio::spawn(async { Ok(()) });
        let http: HttpHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        // Signal held pending via oneshot — helper must wake from gRPC
        // completion, not from a test-side broadcast send.
        let (_signal_tx, signal_rx) = tokio::sync::oneshot::channel::<()>();
        let signal = async move {
            let _ = signal_rx.await;
        };
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(!outcome.requested);
        assert!(!outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("unexpected clean service exit must fail production check");
        assert!(
            err.contains("requested=false"),
            "diagnostic should mention requested=false: {err}"
        );
    }

    #[tokio::test]
    async fn unexpected_http_error() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };
        let http: HttpHandle = tokio::spawn(async { Err(std::io::Error::other("http boom")) });

        tokio::time::sleep(Duration::from_millis(50)).await;

        let (_signal_tx, signal_rx) = tokio::sync::oneshot::channel::<()>();
        let signal = async move {
            let _ = signal_rx.await;
        };
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(!outcome.requested);
        assert!(!outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("unexpected service error must fail production check");
        assert!(
            err.contains("http"),
            "diagnostic should mention http: {err}"
        );
    }

    // ── Section 7.6: Both services refuse to drain ─────────────────

    #[tokio::test]
    async fn both_refuse_to_drain() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = tokio::spawn(async {
            std::future::pending::<Result<(), tonic::transport::Error>>().await
        });
        let http: HttpHandle =
            tokio::spawn(async { std::future::pending::<Result<(), std::io::Error>>().await });

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let start = std::time::Instant::now();
        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_millis(100)).await;
        let elapsed = start.elapsed();

        assert!(outcome.requested);
        assert!(outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        assert!(
            elapsed < Duration::from_secs(2),
            "test should complete quickly, took {elapsed:?}"
        );
        let err = outcome
            .ensure_clean_requested_shutdown()
            .expect_err("forced abort must fail production check");
        assert!(
            err.contains("forced=true"),
            "diagnostic should mention forced: {err}"
        );
    }

    // ── Section 7.7: No pre-signal lifetime timeout ────────────────

    #[tokio::test]
    async fn no_pre_signal_lifetime_timeout() {
        let drain_timeout = Duration::from_millis(100);

        // ── Phase A: helper remains pending while no terminal event ──
        // The helper must not start the drain timeout until a terminal
        // event has occurred. We construct the helper with a held-pending
        // oneshot signal and no pre-completing services, then assert that
        // it does not complete within 2× the drain timeout.
        {
            let (tx, _) = tokio::sync::broadcast::channel::<()>(1);
            let (_signal_tx, signal_rx) = tokio::sync::oneshot::channel::<()>();
            let grpc: GrpcHandle = {
                let mut rx = tx.subscribe();
                tokio::spawn(async move {
                    let _ = rx.recv().await;
                    Ok(())
                })
            };
            let http: HttpHandle = {
                let mut rx = tx.subscribe();
                tokio::spawn(async move {
                    let _ = rx.recv().await;
                    Ok(())
                })
            };
            let mut signal = Box::pin(async move {
                let _ = signal_rx.await;
            });
            let helper_fut =
                run_services_until_shutdown(signal.as_mut(), grpc, http, tx, drain_timeout);
            let phase_a_result = tokio::time::timeout(drain_timeout * 2, helper_fut).await;
            assert!(
                phase_a_result.is_err(),
                "helper must remain pending for at least 2× drain timeout when no terminal event has occurred"
            );
        }

        // ── Phase B: signal triggers and helper completes cleanly ──
        // Trigger the oneshot BEFORE polling the helper so the first
        // poll sees the signal ready, then verify a clean requested
        // shutdown.
        {
            let (tx, _) = tokio::sync::broadcast::channel::<()>(1);
            let (signal_tx, signal_rx) = tokio::sync::oneshot::channel::<()>();
            let grpc: GrpcHandle = {
                let mut rx = tx.subscribe();
                tokio::spawn(async move {
                    let _ = rx.recv().await;
                    Ok(())
                })
            };
            let http: HttpHandle = {
                let mut rx = tx.subscribe();
                tokio::spawn(async move {
                    let _ = rx.recv().await;
                    Ok(())
                })
            };
            let mut signal = Box::pin(async move {
                let _ = signal_rx.await;
            });
            let _ = signal_tx.send(());
            let helper_fut =
                run_services_until_shutdown(signal.as_mut(), grpc, http, tx, drain_timeout);
            let outcome = tokio::time::timeout(Duration::from_secs(5), helper_fut)
                .await
                .expect("helper should complete within 5s after signal trigger");
            assert!(outcome.requested);
            assert!(!outcome.forced);
            assert!(outcome.is_clean_requested_shutdown());
            assert!(
                outcome.ensure_clean_requested_shutdown().is_ok(),
                "production decision method must return Ok for clean requested shutdown"
            );
        }
    }

    // ── Regression: completed gRPC service is observed once ───────

    #[tokio::test]
    async fn grpc_service_completion_is_observed_once() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);
        let poll_count = Arc::new(AtomicUsize::new(0));

        let grpc: GrpcHandle = {
            let count = poll_count.clone();
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                count.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        };
        let http: HttpHandle =
            tokio::spawn(async { std::future::pending::<Result<(), std::io::Error>>().await });

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_millis(100)).await;

        assert!(outcome.forced);
        assert_eq!(
            poll_count.load(Ordering::SeqCst),
            1,
            "gRPC future should have been polled exactly once"
        );
    }

    // ── Section 7.4 regression: drain-time panic preserves detail ──

    #[tokio::test]
    async fn drain_panic_preserved_in_outcome() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                panic!("deliberate grpc panic");
            })
        };
        let http: HttpHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(outcome.requested);
        assert!(!outcome.forced);
        assert!(!outcome.is_clean_requested_shutdown());
        match &outcome.grpc_result {
            ServiceResult::Panic(msg) => {
                assert!(
                    msg.contains("deliberate grpc panic"),
                    "panic message should be preserved"
                );
            }
            other => panic!("expected Panic, got {other:?}"),
        }
    }

    // ── Section 7.6 regression: HTTP aborted while gRPC clean ──────

    #[tokio::test]
    async fn http_aborted_while_grpc_clean() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                Ok(())
            })
        };
        let http: HttpHandle =
            tokio::spawn(async { std::future::pending::<Result<(), std::io::Error>>().await });

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_millis(100)).await;

        assert!(outcome.requested);
        assert!(outcome.forced);
        assert_eq!(outcome.grpc_result, ServiceResult::Clean);
        assert!(matches!(
            outcome.http_result,
            ServiceResult::Cancelled(_) | ServiceResult::Panic(_)
        ));
    }

    // ── Section 7.1 regression: both complete during drain ──────────

    #[tokio::test]
    async fn both_complete_during_drain() {
        let (tx, _) = tokio::sync::broadcast::channel::<()>(1);

        let grpc: GrpcHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                tokio::time::sleep(Duration::from_millis(10)).await;
                Ok(())
            })
        };
        let http: HttpHandle = {
            let mut rx = tx.subscribe();
            tokio::spawn(async move {
                let _ = rx.recv().await;
                tokio::time::sleep(Duration::from_millis(20)).await;
                Ok(())
            })
        };

        tokio::time::sleep(Duration::from_millis(50)).await;

        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome =
            run_services_until_shutdown(signal, grpc, http, tx, Duration::from_secs(2)).await;

        assert!(outcome.requested);
        assert!(!outcome.forced);
        assert!(outcome.is_clean_requested_shutdown());
    }
}

#[cfg(test)]
mod eggserve_tests {
    use super::*;

    #[tokio::test]
    async fn eggserve_runtime_drains_after_requested_shutdown() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let server = eggserve_server::Server::builder()
            .from_listener(listener)
            .build()
            .unwrap();
        let handle = server
            .start_with_service(eggserve_server::service_fn(|_request| async {
                Ok(eggserve_primitives::Response::builder()
                    .status(eggserve_primitives::StatusCode::OK)
                    .body(eggserve_primitives::ResponseBody::Empty)
                    .unwrap())
            }))
            .await
            .unwrap();
        let (control, completion) = handle.into_parts();
        let (shutdown_tx, _) = tokio::sync::broadcast::channel(1);
        let grpc = tokio::spawn({
            let mut shutdown_rx = shutdown_tx.subscribe();
            async move {
                let _ = shutdown_rx.recv().await;
                Ok::<(), tonic::transport::Error>(())
            }
        });
        let signal = std::future::ready(());
        tokio::pin!(signal);

        let outcome = run_eggserve_services_until_shutdown(
            signal,
            grpc,
            control,
            completion,
            shutdown_tx,
            Duration::from_secs(2),
        )
        .await;

        assert!(outcome.is_clean_requested_shutdown(), "{outcome:?}");
    }
}