subc-daemon 0.47.0

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
//! Owned tasks isolate each module's outbound delivery and acknowledgment deadlines.

use super::*;
use crate::config_gate::runtime::{
    delivery::CONFIG_LIVE_ACK_TIMEOUT, AppliedDisposition, DeliveryObserver,
};
use std::collections::{HashMap, HashSet};
use tokio::sync::Notify;
use tokio::task::{JoinHandle, JoinSet};
use tokio::time::{sleep_until, timeout_at, Instant};

#[derive(Default)]
struct AuthorityExitRetry {
    generation: Option<u64>,
    next: Option<Instant>,
    delay: Duration,
}

impl AuthorityExitRetry {
    fn observe_pending(&mut self, generation: Option<u64>, now: Instant) {
        if generation.is_none() {
            *self = Self::default();
        } else if self.generation != generation {
            self.generation = generation;
            self.delay = Duration::from_secs(1);
            self.next = Some(now + self.delay);
        } else if self.next.is_some_and(|deadline| deadline <= now) {
            self.delay = (self.delay * 2).min(Duration::from_secs(60));
            self.next = Some(now + self.delay);
        }
        // Configuration-state notifications can retry immediately, but do not
        // move an outstanding deadline or postpone timed retries.
    }
}

impl ControlHandler {
    #[cfg(all(test, unix))]
    pub(crate) fn with_delivery_wakes_for_test(
        mut self,
        wakes: tokio::sync::mpsc::UnboundedSender<(&'static str, Instant)>,
    ) -> Self {
        self.config_delivery_test_wakes = Some(wakes);
        self
    }
    /// Pause after the owner checks and all coordinator tasks finish. Use only
    /// without registered config-review workers, whose tasks intentionally stay live.
    #[cfg(all(test, unix))]
    pub(crate) fn with_delivery_idle_for_test(
        mut self,
        idle: tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>,
    ) -> Self {
        self.config_delivery_test_idle = Some(idle);
        self
    }
    #[cfg(all(test, unix))]
    pub(crate) async fn record_config_exit_for_test(
        self: &Arc<Self>,
        exited: crate::config_gate::runtime::delivery::ExitedDelivery,
    ) -> bool {
        record_exit(Arc::downgrade(self), exited).await
    }

    /// The bootstrap task owns this handle and aborts it at daemon teardown.
    /// The configuration delivery coordinator and its idle module tasks hold
    /// weak control-handler references, so they cannot retain the config store's
    /// writer lock held for the configuration store after the daemon is dropped.
    pub(crate) fn spawn_config_delivery_worker(self: &Arc<Self>) -> Option<JoinHandle<()>> {
        let owner = self.config_runtime.as_ref()?;
        let changed = owner.delivery_notifications();
        let handler = Arc::downgrade(self);
        Some(tokio::spawn(async move {
            let mut tasks = JoinSet::new();
            let mut wakes = HashMap::<ConnectionId, Arc<Notify>>::new();
            let recording = Arc::new(std::sync::Mutex::new(HashSet::<String>::new()));
            let mut restarting = HashSet::<(String, u64)>::new();
            let mut recovery_holds = HashSet::<String>::new();
            let mut exit_retry = AuthorityExitRetry::default();
            #[cfg(test)]
            let mut quiet_after_retry_pause = false;
            loop {
                let (next_anchor, listen_for_changes) = {
                    let Some(control) = handler.upgrade() else {
                        break;
                    };
                    let Some(owner) = &control.config_runtime else {
                        break;
                    };
                    let Ok((next, withdrawals, exits, pending, recoveries, holds, mut releases)) =
                        owner
                            .on_blocking(|owner| {
                                let _ = owner.check_recovery();
                                let next = owner.retry_anchor().ok().flatten();
                                let withdrawals = owner.take_phone_withdrawals();
                                let exits = owner.delivery_exits().unwrap_or_default();
                                let pending = owner
                                    .pending_config_restarts()
                                    .unwrap_or_default()
                                    .into_iter()
                                    .filter(|(module, _)| {
                                        owner.delivery_exit_fence(module).ok().flatten().is_none()
                                    })
                                    .collect::<Vec<_>>();
                                let recoveries =
                                    owner.delivery_take_recoveries().unwrap_or_default();
                                let (holds, releases) = owner.take_admission_transitions()?;
                                Ok((
                                    next,
                                    withdrawals,
                                    exits,
                                    pending,
                                    recoveries,
                                    holds,
                                    releases,
                                ))
                            })
                            .await
                    else {
                        break;
                    };
                    let (ready_exit, mut retained_exit) = owner
                        .on_blocking(|owner| {
                            Ok((
                                owner.pending_authority_exit()?,
                                owner.authority_exit_retry_generation()?,
                            ))
                        })
                        .await
                        .unwrap_or((None, exit_retry.generation));
                    if let Some(generation) = ready_exit {
                        #[cfg(test)]
                        if let Some(path) = control
                            .recovery_exit_test_retry_pause
                            .and_then(|pause| pause(generation))
                        {
                            quiet_after_retry_pause = true;
                            while path.exists() {
                                tokio::time::sleep(Duration::from_millis(10)).await;
                            }
                        }
                        if let Err(error) = control
                            .reconcile_authority_exit(owner.clone(), generation)
                            .await
                        {
                            warn!(%error, "approved configuration exit could not be reconciled");
                        }
                        // A stale generation reconciles as a no-op. Only the
                        // current marker, not that return value, can disarm retries.
                        retained_exit = owner
                            .on_blocking(|owner| owner.authority_exit_retry_generation())
                            .await
                            .unwrap_or(retained_exit);
                    }
                    exit_retry.observe_pending(retained_exit, Instant::now());
                    if owner.is_recovering() {
                        for module in control.supervisor.list() {
                            if recovery_holds.insert(module.module_id().to_owned()) {
                                tasks.spawn(async move {
                                    let _ = module.config_exit_hold().await;
                                });
                            }
                        }
                    } else {
                        releases.extend(recovery_holds.drain());
                    }
                    for module in holds {
                        if let Some(supervised) = control
                            .supervisor
                            .get(&module)
                            .filter(|_| owner.check_module_hold(&module).is_err())
                        {
                            tasks.spawn(async move {
                                let _ = supervised.config_exit_hold().await;
                            });
                        }
                    }
                    for module in releases.into_iter().collect::<HashSet<_>>() {
                        if owner.check_module_hold(&module).is_err() {
                            continue;
                        }
                        if let Some(supervised) =
                            control.supervisor.get(&module).filter(|supervised| {
                                supervised
                                    .status()
                                    .is_ok_and(|status| status.enabled && !status.process_alive)
                            })
                        {
                            tasks.spawn(async move {
                                let _ = supervised.release_config_hold().await;
                            });
                        }
                    }
                    for withdrawal in withdrawals {
                        let owner = Arc::downgrade(owner);
                        tasks.spawn(async move {
                            let _ = withdrawal.sink.send_flushed(withdrawal.frame).await;
                            if let Some(owner) = owner.upgrade() {
                                owner.phone_withdrawn(withdrawal.connection);
                            }
                        });
                    }
                    for exited in exits {
                        let module = exited.module.clone();
                        if recording
                            .lock()
                            .unwrap_or_else(|p| p.into_inner())
                            .insert(module.clone())
                        {
                            let handler = handler.clone();
                            let recording = recording.clone();
                            tasks.spawn(async move {
                                if record_exit(handler, exited).await {
                                    recording
                                        .lock()
                                        .unwrap_or_else(|p| p.into_inner())
                                        .remove(&module);
                                }
                            });
                        }
                    }
                    {
                        restarting.retain(|entry| pending.contains(entry));
                        for (module, generation) in pending {
                            if let Some(supervised) = control.supervisor.get(&module) {
                                if restarting.insert((module.clone(), generation)) {
                                    tasks.spawn(async move {
                                        if let Err(error) = supervised.config_apply_restart(generation).await {
                                            warn!(module_id=%module, %error, "approved configuration restart could not be queued");
                                        }
                                    });
                                }
                            }
                        }
                    }
                    let registrations = control
                        .registry
                        .list_registered_modules()
                        .unwrap_or_default();
                    wakes.retain(|connection, wake| {
                        let current = registrations
                            .iter()
                            .any(|registration| registration.connection_id == *connection);
                        if !current {
                            wake.notify_one();
                        }
                        current
                    });
                    for registration in registrations.into_iter().filter(|registration| {
                        registration
                            .control_ops
                            .iter()
                            .any(|op| op == "config.review")
                    }) {
                        let connection = registration.connection_id;
                        if let Some(wake) = wakes.get(&connection) {
                            wake.notify_one();
                        } else {
                            let wake = Arc::new(Notify::new());
                            wakes.insert(connection, wake.clone());
                            tasks.spawn(module_worker(handler.clone(), registration, wake));
                        }
                    }
                    for (connection, module, disposition) in recoveries {
                        if matches!(
                            disposition,
                            AppliedDisposition::Failed {
                                keep_running: true,
                                ..
                            }
                        ) {
                            continue;
                        }
                        if let Some(supervised) = control.supervisor.get(&module) {
                            let hold = matches!(
                                disposition,
                                AppliedDisposition::Failed { restore: None, .. }
                            );
                            tasks.spawn(async move {
                                // Restarting after a rejected configuration
                                // spends one crash-budget entry: the module
                                // failed. An approved restart spends none.
                                if let Err(error) = supervised.config_delivery_failed(connection, hold).await {
                                    warn!(module_id=%module, %error, "configuration delivery recovery request failed");
                                }
                            });
                        }
                    }
                    while let Some(result) = tasks.try_join_next() {
                        if let Err(error) = result {
                            warn!(%error, "configuration delivery task stopped");
                        }
                    }
                    #[cfg(test)]
                    let listen_for_changes = !((retained_exit.is_some()
                        || quiet_after_retry_pause)
                        && control.recovery_exit_test_quiet_retry);
                    #[cfg(not(test))]
                    let listen_for_changes = true;
                    let next = next.into_iter().chain(exit_retry.next).min();
                    (next, listen_for_changes)
                };
                #[cfg(all(test, unix))]
                if let Some(idle) = handler
                    .upgrade()
                    .and_then(|control| control.config_delivery_test_idle.clone())
                {
                    // Unlike a wake notification, this acknowledges completion
                    // of owner I/O and the supervisor's recovery-hold replies.
                    while let Some(result) = tasks.join_next().await {
                        if let Err(error) = result {
                            warn!(%error, "configuration delivery task stopped");
                        }
                    }
                    let (resume, released) = tokio::sync::oneshot::channel();
                    if idle.send(resume).is_ok() {
                        let _ = released.await;
                    }
                }
                tokio::select! {
                    _ = changed.notified(), if listen_for_changes => {
                        #[cfg(test)]
                        report_delivery_wake(&handler, "notification");
                    },
                    _ = async { match next_anchor { Some(at) => sleep_until(at).await, None => std::future::pending().await } } => {
                        #[cfg(test)]
                        report_delivery_wake(&handler, "timer");
                    },
                }
            }
        }))
    }
}

#[cfg(test)]
fn report_delivery_wake(handler: &std::sync::Weak<ControlHandler>, cause: &'static str) {
    if let Some(control) = handler.upgrade() {
        if let Some(wakes) = &control.config_delivery_test_wakes {
            let _ = wakes.send((cause, Instant::now()));
        }
    }
}

#[cfg(all(test, unix))]
#[tokio::test(start_paused = true)]
async fn config_recovery_exit_failed_snapshot_read_wakes_only_for_timers_and_state_changes() {
    use std::future::Future;
    use std::task::Poll;

    let (_rig, owner, _supervisor, handler, _spec) =
        crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test();
    assert_eq!(owner.pending_authority_exit().unwrap(), Some(1));
    assert!(handler.rescan.is_none());
    let error = handler
        .reconcile_authority_exit(owner.clone(), 1)
        .await
        .unwrap_err();
    assert_eq!(error.code, "supervisor_reconcile_unavailable");

    // Discard setup notifications so every observed wake belongs to the worker.
    let changed = owner.delivery_notifications();
    {
        let mut notification = std::pin::pin!(changed.notified());
        let _ = std::future::poll_fn(|cx| Poll::Ready(notification.as_mut().poll(cx))).await;
    }
    let (sender, mut wakes) = tokio::sync::mpsc::unbounded_channel();
    let mut handler = (*handler).clone();
    handler.config_delivery_test_wakes = Some(sender);
    let handler = Arc::new(handler);
    let worker = handler.spawn_config_delivery_worker().unwrap();
    let start = Instant::now();

    let first = wakes.recv().await.unwrap();
    assert_eq!(first.0, "timer");
    assert!(first.1 >= start + Duration::from_secs(1));
    owner.notify_delivery_changed();
    let second = wakes.recv().await.unwrap();
    assert_eq!(second, ("notification", first.1));
    let third = wakes.recv().await.unwrap();
    assert_eq!(third.0, "timer");
    assert!(third.1 >= first.1 + Duration::from_secs(2));
    assert!(
        wakes.try_recv().is_err(),
        "exactly three wakes were requested"
    );
    assert_eq!(owner.pending_authority_exit().unwrap(), Some(1));
    worker.abort();
    let _ = worker.await;
}

#[cfg(test)]
#[tokio::test(start_paused = true)]
async fn config_recovery_exit_retry_backoff_caps_and_does_not_postpone_on_owner_wakes() {
    let start = Instant::now();
    let mut retry = AuthorityExitRetry::default();
    retry.observe_pending(Some(7), start);
    for seconds in [1, 3, 7, 15, 31, 63, 123, 183] {
        let deadline = start + Duration::from_secs(seconds);
        assert_eq!(retry.next, Some(deadline));
        retry.observe_pending(Some(7), deadline - Duration::from_nanos(1));
        assert_eq!(
            retry.next,
            Some(deadline),
            "owner wakes must not defer a retry"
        );
        retry.observe_pending(Some(7), deadline);
    }
    assert_eq!(retry.next, Some(start + Duration::from_secs(243)));
    retry.observe_pending(None, start + Duration::from_secs(184));
    assert!(retry.next.is_none());
    retry.observe_pending(Some(8), start + Duration::from_secs(184));
    assert_eq!(retry.next, Some(start + Duration::from_secs(185)));
}

async fn module_worker(
    handler: std::sync::Weak<ControlHandler>,
    registration: crate::registry::ModuleRegistration,
    wake: Arc<Notify>,
) {
    let mut user_file_watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
    loop {
        let next = {
            let Some(control) = handler.upgrade() else {
                break;
            };
            let Some(owner) = &control.config_runtime else {
                break;
            };
            let module = &registration.manifest.module_id;
            let connection = registration.connection_id;
            let watched_module = module.clone();
            let (watch, unstamped) = owner
                .on_blocking(move |owner| {
                    let mut watch = user_file_watch;
                    let unstamped = owner
                        .poll_unstamped_user_file(connection, &watched_module, &mut watch)
                        .unwrap_or(true);
                    Ok((watch, unstamped))
                })
                .await
                .unwrap_or_default();
            user_file_watch = watch;
            let next_poll = unstamped.then(|| {
                Instant::now() + crate::config_gate::runtime::unstamped::USER_FILE_POLL_INTERVAL
            });
            let Ok(gate) = owner.module_gate(module) else {
                break;
            };
            let mut _guard = gate.lock().await;
            if module_work(owner, module, |owner, module| {
                owner.delivery_exit_fence(&module)
            })
            .await
            .ok()
            .flatten()
            .is_some()
            {
                drop(_guard);
                drop(control);
                wake.notified().await;
                continue;
            }
            let active = control
                .registry
                .get_module(module)
                .ok()
                .flatten()
                .is_some_and(|target| target.connection_id == registration.connection_id);
            let Some(sink) = control
                .forwarding
                .config_delivery_sink(module, registration.connection_id)
                .ok()
                .flatten()
                .filter(|_| active)
            else {
                break;
            };
            let anchor_hint = owner
                .on_blocking(move |owner| owner.take_anchor_hint(connection))
                .await
                .unwrap_or(None);
            let unstamp_hint = owner
                .on_blocking(move |owner| owner.take_unstamp_hint(connection))
                .await
                .unwrap_or(false);
            if anchor_hint.is_some() || unstamp_hint {
                let hint =
                    subc_protocol::config::ConfigChanged::new(anchor_hint.unwrap_or(0), vec![]);
                if let Ok(frame) = serde_json::to_vec(&hint)
                    .ok()
                    .and_then(|body| {
                        Frame::build_with_version(
                            registration.negotiated_ver,
                            FrameType::Push,
                            control_flags(),
                            0,
                            0,
                            0,
                            body,
                        )
                        .ok()
                    })
                    .ok_or(())
                {
                    drop(_guard);
                    let _ = timeout_at(
                        Instant::now() + CONFIG_LIVE_ACK_TIMEOUT,
                        sink.send_flushed(frame),
                    )
                    .await;
                    _guard = gate.lock().await;
                }
            }
            let view = if unstamped {
                Ok(subc_protocol::config::ConfigGetReply::new(None, None))
            } else {
                module_work(owner, module, move |owner, module| {
                    owner.module_get(
                        connection,
                        &module,
                        subc_protocol::config::ConfigGetRequest::new(),
                    )
                })
                .await
            };
            if let Ok(view) = view {
                if let Some(pending) = view.pending {
                    if let Some(attempt) = pending.attempt {
                        let generation = pending.generation;
                        if module_work(owner, module, move |owner, module| {
                            owner.route_policy_needed(&module, generation)
                        })
                        .await
                        .unwrap_or(true)
                        {
                            if let Err(error) = owner
                                .install_approved_route_policy(module, pending.generation)
                                .await
                            {
                                warn!(module_id=%module, %error, "approved route policy could not be installed");
                                drop(_guard);
                                drop(control);
                                wake.notified().await;
                                continue;
                            }
                        }
                        if let Ok(Some((generation, attempt))) = owner
                            .on_blocking(move |owner| owner.policy_probe_due(connection))
                            .await
                        {
                            let supervised = control.supervisor.get(module);
                            drop(_guard);
                            drop(control);
                            if let Some(supervised) = supervised {
                                if let Err(error) = supervised
                                    .config_policy_probe(
                                        registration.connection_id,
                                        generation,
                                        attempt,
                                    )
                                    .await
                                {
                                    warn!(%error, "post-policy configuration health probe could not be queued");
                                }
                            }
                            continue;
                        }
                        let window = owner
                            .on_blocking(move |owner| owner.delivery_window(connection))
                            .await
                            .ok()
                            .flatten();
                        if window.is_some_and(|window| !window.delivered) {
                            let hint = subc_protocol::config::ConfigChanged::new(
                                pending.generation,
                                vec![],
                            );
                            let frame = serde_json::to_vec(&hint).ok().and_then(|body| {
                                Frame::build_with_version(
                                    registration.negotiated_ver,
                                    FrameType::Push,
                                    control_flags(),
                                    0,
                                    0,
                                    0,
                                    body,
                                )
                                .ok()
                            });
                            if let Some(frame) = frame {
                                let _ = owner
                                    .on_blocking(move |owner| {
                                        owner.delivery_write_started(
                                            connection,
                                            generation,
                                            attempt,
                                            Instant::now(),
                                        )
                                    })
                                    .await;
                                let flush_deadline = window
                                    .and_then(|window| window.deadline)
                                    .map_or(Instant::now() + CONFIG_LIVE_ACK_TIMEOUT, |at| {
                                        at.min(Instant::now() + CONFIG_LIVE_ACK_TIMEOUT)
                                    });
                                drop(_guard);
                                let flushed =
                                    timeout_at(flush_deadline, sink.send_flushed(frame)).await;
                                let flushed_at = Instant::now();
                                _guard = gate.lock().await;
                                let current = control
                                    .config_delivery_target_current(
                                        module,
                                        registration.connection_id,
                                        true,
                                        0,
                                    )
                                    .unwrap_or(false)
                                    && owner
                                        .on_blocking(move |owner| owner.delivery_window(connection))
                                        .await
                                        .ok()
                                        .flatten()
                                        .is_some_and(|window| {
                                            (window.generation, window.attempt)
                                                == (pending.generation, attempt)
                                        });
                                if !current {
                                    continue;
                                }
                                match flushed {
                                    Ok(Ok(())) => {
                                        if owner
                                            .on_blocking(move |owner| {
                                                owner.delivery_written(
                                                    connection, generation, attempt, flushed_at,
                                                )
                                            })
                                            .await
                                            .is_err()
                                        {
                                            let _ =
                                                module_work(owner, module, move |owner, module| {
                                                    owner.delivery_timeout(
                                                        connection, &module, generation, attempt,
                                                    )
                                                })
                                                .await;
                                        }
                                    }
                                    _ => {
                                        let _ = module_work(owner, module, move |owner, module| {
                                            owner.delivery_timeout(
                                                connection, &module, generation, attempt,
                                            )
                                        })
                                        .await;
                                    }
                                }
                                owner.notify_delivery_changed();
                            }
                        }
                    }
                }
            }
            let window = owner
                .on_blocking(move |owner| owner.delivery_window(connection))
                .await
                .ok()
                .flatten();
            match window {
                Some(window) if window.deadline.is_some_and(|at| Instant::now() >= at) => {
                    let _ = module_work(owner, module, move |owner, module| {
                        owner.delivery_timeout(
                            connection,
                            &module,
                            window.generation,
                            window.attempt,
                        )
                    })
                    .await;
                    owner.notify_delivery_changed();
                    None
                }
                Some(window) => window.deadline,
                None => next_poll,
            }
        };
        #[cfg(test)]
        {
            let idle = handler.upgrade().and_then(|control| {
                control
                    .config_runtime
                    .as_ref()
                    .and_then(|owner| owner.user_file_test_idle.lock().unwrap().clone())
            });
            if let Some(idle) = idle {
                // Tests hold the worker at its timer boundary while editing files.
                let (resume, released) = tokio::sync::oneshot::channel();
                if idle.send((registration.connection_id, resume)).is_ok() {
                    let _ = released.await;
                }
            }
        }
        tokio::select! {
            _ = wake.notified() => {},
            _ = async { match next { Some(at) => sleep_until(at).await, None => std::future::pending().await } } => {},
        }
    }
}

async fn record_exit(
    handler: std::sync::Weak<ControlHandler>,
    exited: crate::config_gate::runtime::delivery::ExitedDelivery,
) -> bool {
    let Some(control) = handler.upgrade() else {
        return true;
    };
    let Some(owner) = &control.config_runtime else {
        return true;
    };
    let mut failure = None;
    // Reconciliation is idempotent. Three attempts, with 50/100 ms backoff,
    // cover transient record/hold errors without an endless hidden retry loop.
    for delay in [
        Duration::ZERO,
        Duration::from_millis(50),
        Duration::from_millis(100),
    ] {
        if !delay.is_zero() {
            tokio::time::sleep(delay).await;
        }
        match reconcile_exit(&control, owner, &exited).await {
            Ok(()) => return true,
            Err(reason) => {
                failure.get_or_insert(reason);
            }
        }
    }
    let reason = failure.expect("each unsuccessful attempt records a reason");
    if let Some(module) = control.supervisor.get(&exited.module) {
        // The exit fence still prevents respawn. Never wait for this command
        // under the module gate: an earlier restart may need that same gate.
        if reason.code != "config_exit_hold_failed" {
            let _ = hold_exited_module(&module).await;
        }
        let approval = owner
            .on_blocking(|owner| owner.terminal_exit_approval_identity())
            .await
            .ok()
            .flatten();
        if let Err(error) = module.config_exit_failed(reason.clone(), approval) {
            warn!(module_id=%exited.module, %error, "configuration exit stopped-state diagnostic could not be retained");
        }
    }
    if let Some(ledger) = &control.activity {
        ledger.config_exit_failed(&exited.module, &reason);
    }
    warn!(module_id=%exited.module, reason=%reason.code, error_kind=%reason.error_kind,
        "configuration exit reconciliation exhausted its retries; module remains stopped behind its exit fence");
    // Retain the coordinator's per-module entry. Future notifications must not
    // silently restart this bounded retry cycle while the terminal fence stays.
    false
}

async fn reconcile_exit(
    control: &ControlHandler,
    owner: &Arc<crate::config_gate::runtime::RuntimeOwner>,
    exited: &crate::config_gate::runtime::delivery::ExitedDelivery,
) -> Result<(), crate::supervise::ModuleStopReason> {
    let reason = |code: &str, error_kind: String| crate::supervise::ModuleStopReason {
        code: code.into(),
        error_kind,
    };
    let gate = owner
        .module_gate(&exited.module)
        .map_err(|error| reason("config_exit_record_failed", error.code))?;
    let hold = {
        let _guard = gate.lock().await;
        let exited = exited.clone();
        owner
            .on_blocking(move |owner| owner.delivery_record_exit(&exited))
            .await
            .map_err(|error| reason("config_exit_record_failed", error.code))?
    };
    if hold {
        if let Some(module) = control.supervisor.get(&exited.module) {
            hold_exited_module(&module)
                .await
                .map_err(|kind| reason("config_exit_hold_failed", kind.into()))?;
        }
    }
    let _guard = gate.lock().await;
    let exited = exited.clone();
    owner
        .on_blocking(move |owner| owner.delivery_release_exit(&exited))
        .await
        .map_err(|error| reason("config_exit_release_failed", error.code))
}

// A stuck supervisor cannot leave reconciliation parked forever. A timed-out
// hold may still finish later; it can only stop this already-exited child.
const CONFIG_EXIT_HOLD_TIMEOUT: Duration = Duration::from_secs(5);

async fn hold_exited_module(
    module: &crate::supervise::SupervisedModule,
) -> Result<(), &'static str> {
    match tokio::time::timeout(CONFIG_EXIT_HOLD_TIMEOUT, module.config_exit_hold()).await {
        Ok(Ok(())) => Ok(()),
        Err(_) => Err("supervisor_hold_timeout"),
        Ok(Err(crate::supervise::SuperviseError::CommandClosed { .. })) => {
            Err("supervisor_command_closed")
        }
        Ok(Err(crate::supervise::SuperviseError::StatePoisoned { .. })) => {
            Err("supervisor_state_poisoned")
        }
        Ok(Err(_)) => Err("supervisor_error"),
    }
}

async fn module_work<T: Send + 'static>(
    owner: &Arc<crate::config_gate::runtime::RuntimeOwner>,
    module: &str,
    work: impl FnOnce(Arc<crate::config_gate::runtime::RuntimeOwner>, String) -> Result<T, GateError>
        + Send
        + 'static,
) -> Result<T, GateError> {
    let module = module.to_owned();
    owner.on_blocking(move |owner| work(owner, module)).await
}