hf2q 0.1.32

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! Mode-neutral fail-closed health lease for the one model worker owned by an
//! [`Engine`](super::engine::Engine). A Metal call may never return, so
//! receiver closure is not a sufficient readiness signal: the worker still
//! owns the receiver while blocked inside Objective-C. The supervisor lives
//! outside that worker and makes transaction expiry one-way and observable.

use std::any::Any;
use std::cell::RefCell;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Once, Weak};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use anyhow::Result;
use tokio::sync::{mpsc, watch};

use super::sse::GenerationEvent;

#[path = "engine_supervisor/pool_census.rs"]
mod pool_census;
#[cfg(test)]
#[path = "engine_supervisor/worker_teardown_tests.rs"]
mod worker_teardown_tests;

const HEALTHY: u8 = 0;
const POISONED: u8 = 1;
const MONITOR_INTERVAL: Duration = Duration::from_millis(10);

#[derive(Clone)]
pub(super) struct EngineSupervisor {
    inner: Arc<EngineSupervisorInner>,
}

struct EngineSupervisorInner {
    pool_census: Mutex<pool_census::Store>,
    /// Requests an HTTP handler is preparing for this engine (template
    /// render, tokenization) that have not been handed to the worker yet.
    /// The DeepSeek-V4 worker's admission barrier reads it.
    admissions_in_flight: AtomicUsize,
    health: AtomicU8,
    next_epoch: AtomicU64,
    armed: Mutex<Option<ArmedTransaction>>,
    reason: Mutex<Option<String>>,
    /// Short operator-facing cause (panic message, expired transaction)
    /// reported by `/readyz` as `engine failed: <summary>`.
    summary: Mutex<Option<String>>,
    health_tx: watch::Sender<bool>,
}

/// What must be flushed once a worker thread is gone: returned by the
/// thread's own cache release ([`WorkerTeardown::new`]) and run after the
/// thread has terminated.
pub(super) type DeferredFlush = Box<dyn FnOnce() -> Result<()> + Send>;

/// How a worker thread gives back what its model held, and the memory
/// reservation that stands for it.
///
/// The worker thread owns the model's buffers, so the reservation is
/// released by the worker's teardown and by nothing else. The teardown is,
/// in this order:
///
/// 1. the worker body returns or unwinds, which drops the model;
/// 2. on the worker thread, `release_thread_caches` drops the GPU caches the
///    thread built for the model (uploaded weight copies, staged planes) and
///    returns the flush they need;
/// 3. the worker thread terminates, which destroys every other thread-local
///    it had; the teardown thread waits for that with a join;
/// 4. the teardown thread runs the flush, which settles every queue the
///    model's threads encoded on (`inference::device_settle`): buffers
///    dropped in steps 1 to 3 only staged their removal from the Metal
///    residency set, and commands the worker committed without waiting may
///    still hold them;
/// 5. the reservation is released.
///
/// From step 2 until step 5 the teardown is in progress, and new admissions
/// wait for it (`resident_memory::Ledger::admit`).
///
/// A step that fails, panics or never returns leaves the reservation
/// counted: a wedged worker and a failed flush keep their memory charged for
/// the life of the process ([`Reservation::strand`]).
///
/// [`Reservation::strand`]: crate::serve::resident_memory::Reservation::strand
pub(super) struct WorkerTeardown {
    memory: Option<crate::serve::resident_memory::Reservation>,
    release_thread_caches: Box<dyn FnOnce() -> Result<DeferredFlush> + Send>,
}

impl WorkerTeardown {
    /// `memory` is the reservation of the model the worker body owns, if it
    /// has one. `release_thread_caches` runs on the worker thread after the
    /// body; the flush it returns runs once that thread has terminated.
    pub(super) fn new(
        memory: Option<crate::serve::resident_memory::Reservation>,
        release_thread_caches: impl FnOnce() -> Result<DeferredFlush> + Send + 'static,
    ) -> Self {
        Self {
            memory,
            release_thread_caches: Box::new(release_thread_caches),
        }
    }

    /// A worker that owns no model: nothing to release and nothing reserved.
    #[cfg(test)]
    pub(super) fn nothing() -> Self {
        Self::new(None, || Ok(Box::new(|| Ok(())) as DeferredFlush))
    }
}

/// RAII count of one request being prepared for the worker
/// ([`EngineSupervisor::begin_admission`]). Nominally `pub` so engine entry
/// points can take it; the module is private to the API.
pub struct AdmissionGuard {
    supervisor: EngineSupervisor,
}

impl Drop for AdmissionGuard {
    fn drop(&mut self) {
        self.supervisor
            .inner
            .admissions_in_flight
            .fetch_sub(1, Ordering::AcqRel);
    }
}

#[derive(Clone, Debug)]
struct ArmedTransaction {
    epoch: u64,
    kind: &'static str,
    deadline: Instant,
}

pub(super) struct WorkerTransactionLease {
    supervisor: EngineSupervisor,
    epoch: u64,
    finished: bool,
}

impl EngineSupervisor {
    pub(super) fn new() -> Self {
        Self::new_with_monitor_start(Self::spawn_monitor)
    }

    fn new_with_monitor_start(
        start: impl FnOnce(Weak<EngineSupervisorInner>) -> std::io::Result<()>,
    ) -> Self {
        let (health_tx, _health_rx) = watch::channel(true);
        let inner = Arc::new(EngineSupervisorInner {
            pool_census: Mutex::new(pool_census::Store::default()),
            admissions_in_flight: AtomicUsize::new(0),
            health: AtomicU8::new(HEALTHY),
            next_epoch: AtomicU64::new(1),
            armed: Mutex::new(None),
            reason: Mutex::new(None),
            summary: Mutex::new(None),
            health_tx,
        });
        if let Err(error) = start(Arc::downgrade(&inner)) {
            tracing::error!(error = %error, "failed to start engine supervisor monitor");
            inner.poison_transaction(ArmedTransaction {
                epoch: 0,
                kind: "supervisor-monitor-spawn",
                deadline: Instant::now(),
            });
        }
        Self { inner }
    }

    fn spawn_monitor(inner: Weak<EngineSupervisorInner>) -> std::io::Result<()> {
        std::thread::Builder::new()
            .name("hf2q-engine-supervisor".into())
            .spawn(move || loop {
                let Some(inner) = inner.upgrade() else {
                    return;
                };
                inner.expire_if_due(Instant::now());
                drop(inner);
                std::thread::sleep(MONITOR_INTERVAL);
            })
            .map(|_| ())
    }

    /// HTTP reads immutable numeric publication only, never native/TLS state.
    /// Count one request as in flight to this engine until the returned
    /// guard drops: right before it is handed to the worker, or on any
    /// early return, client disconnect or panic of the preparing handler.
    pub(super) fn begin_admission(&self) -> AdmissionGuard {
        self.inner.admissions_in_flight.fetch_add(1, Ordering::AcqRel);
        AdmissionGuard {
            supervisor: self.clone(),
        }
    }

    /// Requests counted by live [`AdmissionGuard`]s.
    pub(super) fn admissions_in_flight(&self) -> usize {
        self.inner.admissions_in_flight.load(Ordering::Acquire)
    }

    pub(super) fn pool_census_json(&self, supported: bool) -> serde_json::Value {
        if !crate::debug::INVESTIGATION_ENV.worker_pool_census {
            return pool_census::unavailable("Disabled");
        }
        if !supported { return pool_census::unavailable("UnsupportedFamily"); }
        match self.inner.pool_census.lock() {
            Ok(store) => store.view(Instant::now(), self.is_healthy()),
            Err(_) => pool_census::unavailable("PublicationLockUnavailable"),
        }
    }

    pub(super) fn is_healthy(&self) -> bool {
        self.inner.expire_if_due(Instant::now());
        self.inner.health.load(Ordering::Acquire) == HEALTHY
    }

    pub(super) fn unhealthy_message(&self) -> String {
        self.inner
            .reason
            .lock()
            .ok()
            .and_then(|reason| reason.clone())
            .unwrap_or_else(|| super::engine::ENGINE_UNHEALTHY_MESSAGE.to_string())
    }

    /// Short cause of a poisoned engine, if one was recorded.
    pub(super) fn failure_summary(&self) -> Option<String> {
        self.inner
            .summary
            .lock()
            .ok()
            .and_then(|summary| summary.clone())
    }

    /// Mark the engine permanently failed because its worker thread
    /// panicked. One-way, like transaction expiry; the first recorded cause
    /// wins. (A worker that exits without panicking closes its request
    /// receiver, which `Engine::failure_detail` reports on its own.)
    pub(super) fn fail_worker(&self, summary: &str) {
        self.inner.fail(summary.to_string());
    }

    pub(super) async fn wait_unhealthy(&self) {
        if !self.is_healthy() {
            return;
        }
        let mut health = self.inner.health_tx.subscribe();
        while *health.borrow_and_update() {
            if health.changed().await.is_err() {
                return;
            }
        }
    }

    /// Forward one worker event stream while the engine stays healthy. A
    /// poisoned transaction wins a simultaneous race, emits exactly one
    /// terminal Error event, then drops the worker receiver so late Metal
    /// returns cannot emit a second terminal or keep a cancelled slot alive.
    pub(super) fn guard_generation_events(
        &self,
        mut source: mpsc::Receiver<GenerationEvent>,
    ) -> mpsc::Receiver<GenerationEvent> {
        let supervisor = self.clone();
        let (guarded_tx, guarded_rx) = mpsc::channel(64);
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    biased;
                    _ = supervisor.wait_unhealthy() => {
                        let _ = guarded_tx
                            .send(GenerationEvent::Error(supervisor.unhealthy_message()))
                            .await;
                        return;
                    }
                    _ = guarded_tx.closed() => {
                        // Propagate the HTTP/SSE consumer's disconnect to the
                        // raw worker channel.  Keeping `source` alive here
                        // would hide cancellation from `events.is_closed()`
                        // and let a bounded prefill/decode continue after the
                        // client had already gone away.
                        return;
                    }
                    event = source.recv() => {
                        let Some(event) = event else {
                            // The worker dropped this stream without a
                            // terminal event. If that happened because the
                            // engine died, say so instead of letting the
                            // SSE layer report an anonymous closed channel.
                            if !supervisor.is_healthy() {
                                let _ = guarded_tx
                                    .send(GenerationEvent::Error(supervisor.unhealthy_message()))
                                    .await;
                            }
                            return;
                        };
                        let terminal = matches!(
                            event,
                            GenerationEvent::Done { .. } | GenerationEvent::Error(_)
                        );
                        match guarded_tx.try_send(event) {
                            Ok(()) if terminal => return,
                            Ok(()) => {}
                            Err(mpsc::error::TrySendError::Closed(_)) => return,
                            Err(mpsc::error::TrySendError::Full(_)) => {
                                // The HTTP consumer is not keeping up. Never
                                // let its bounded response queue backpressure
                                // the sole model worker: dropping `source`
                                // wakes any raw blocking send with an error,
                                // which the worker treats as request-local
                                // cancellation while other slots continue.
                                return;
                            }
                        }
                    }
                }
            }
        });
        guarded_rx
    }

    pub(super) fn arm(
        &self,
        kind: &'static str,
        timeout: Duration,
    ) -> Result<WorkerTransactionLease> {
        anyhow::ensure!(self.is_healthy(), "{}", self.unhealthy_message());
        anyhow::ensure!(!timeout.is_zero(), "worker transaction timeout is zero");
        let epoch = self.inner.next_epoch.fetch_add(1, Ordering::Relaxed);
        let mut armed = self
            .inner
            .armed
            .lock()
            .map_err(|_| anyhow::anyhow!("engine supervisor transaction lock poisoned"))?;
        anyhow::ensure!(
            self.inner.health.load(Ordering::Acquire) == HEALTHY,
            "{}",
            self.unhealthy_message()
        );
        anyhow::ensure!(
            armed.is_none(),
            "engine supervisor already has an armed worker transaction"
        );
        *armed = Some(ArmedTransaction {
            epoch,
            kind,
            deadline: Instant::now() + timeout,
        });
        Ok(WorkerTransactionLease {
            supervisor: self.clone(),
            epoch,
            finished: false,
        })
    }

    pub(super) fn run<T>(
        &self,
        kind: &'static str,
        timeout: Duration,
        call: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let lease = self.arm(kind, timeout)?;
        let result = call();
        lease.finish()?;
        result
    }

    #[cfg(test)]
    pub(super) fn force_expire_for_test(&self) {
        let mut armed = self.inner.armed.lock().expect("supervisor lock");
        if let Some(transaction) = armed.as_mut() {
            transaction.deadline = Instant::now();
        }
        drop(armed);
        self.inner.expire_if_due(Instant::now());
    }

    #[cfg(test)]
    pub(super) fn backdate_without_monitor_for_test(&self) {
        let mut armed = self.inner.armed.lock().expect("supervisor lock");
        if let Some(transaction) = armed.as_mut() {
            transaction.deadline = Instant::now();
        }
    }

    pub(super) fn poison_now(&self, kind: &'static str) {
        let now = Instant::now();
        self.inner.poison_transaction(ArmedTransaction {
            epoch: self.inner.next_epoch.fetch_add(1, Ordering::Relaxed),
            kind,
            deadline: now,
        });
    }
}

impl WorkerTransactionLease {
    pub(super) fn finish(mut self) -> Result<()> {
        self.complete();
        anyhow::ensure!(
            self.supervisor.is_healthy(),
            "{}",
            self.supervisor.unhealthy_message()
        );
        Ok(())
    }

    fn complete(&mut self) {
        if self.finished {
            return;
        }
        self.supervisor
            .inner
            .complete_epoch(self.epoch, Instant::now());
        self.finished = true;
    }
}

impl Drop for WorkerTransactionLease {
    fn drop(&mut self) {
        self.complete();
    }
}

impl EngineSupervisorInner {
    fn complete_epoch(&self, epoch: u64, now: Instant) {
        let Ok(mut armed) = self.armed.lock() else {
            self.poison_transaction(ArmedTransaction {
                epoch,
                kind: "supervisor-lock",
                deadline: now,
            });
            return;
        };
        let Some(transaction) = armed
            .as_ref()
            .filter(|transaction| transaction.epoch == epoch)
            .cloned()
        else {
            return;
        };
        if now >= transaction.deadline {
            // Linearize readiness failure before clearing the lease. Otherwise
            // a concurrent readiness check could observe HEALTHY + no armed
            // transaction in the gap between disarm and poison.
            self.poison_transaction(transaction);
        }
        *armed = None;
    }

    fn expire_if_due(&self, now: Instant) {
        if self.health.load(Ordering::Acquire) != HEALTHY {
            return;
        }
        let expired = self
            .armed
            .lock()
            .ok()
            .and_then(|armed| armed.clone())
            .filter(|transaction| now >= transaction.deadline);
        let Some(expired) = expired else {
            return;
        };
        self.poison_transaction(expired);
    }

    fn poison_transaction(&self, expired: ArmedTransaction) {
        if self
            .health
            .compare_exchange(HEALTHY, POISONED, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            let message = format!(
                "{}: worker transaction {} (epoch {}) exceeded its continuously-awake deadline; process restart required",
                super::engine::ENGINE_UNHEALTHY_SENTINEL,
                expired.kind,
                expired.epoch
            );
            if let Ok(mut reason) = self.reason.lock() {
                *reason = Some(message.clone());
            }
            if let Ok(mut summary) = self.summary.lock() {
                *summary = Some(format!(
                    "worker transaction {} (epoch {}) exceeded its deadline",
                    expired.kind, expired.epoch
                ));
            }
            crate::serve::operator_ui::engine_unhealthy(message.clone());
            tracing::error!(
                transaction = expired.kind,
                epoch = expired.epoch,
                "engine worker transaction deadline expired"
            );
            self.health_tx.send_replace(false);
        }
    }

    fn fail(&self, summary: String) {
        if self
            .health
            .compare_exchange(HEALTHY, POISONED, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            let message = super::engine::engine_failed_message(&summary);
            if let Ok(mut reason) = self.reason.lock() {
                *reason = Some(message.clone());
            }
            if let Ok(mut slot) = self.summary.lock() {
                *slot = Some(summary.clone());
            }
            crate::serve::operator_ui::engine_unhealthy(message);
            tracing::error!(cause = %summary, "inference engine thread failed; restart hf2q serve");
            self.health_tx.send_replace(false);
        }
    }
}

thread_local! {
    /// Supervisor of the engine worker running on this thread, consulted by
    /// the process panic hook.
    static WORKER_SUPERVISOR: RefCell<Option<EngineSupervisor>> = const { RefCell::new(None) };
}

/// Called only at actual Qwen SlotAware request terminal paths on the owning worker.
/// Success follows synchronous target/verifier terminal wait + CPU readback; this
/// records pool owners, not global quiescence/no-future-use or physical residency.
pub(super) fn qwen_pool_request_observation(slot: usize, generation: u64, outcome: &'static str) {
    if !crate::debug::INVESTIGATION_ENV.worker_pool_census { return; }
    let supervisor = WORKER_SUPERVISOR.try_with(|cell| cell.try_borrow().ok().and_then(|s| s.clone()))
        .ok().flatten();
    let Some(supervisor) = supervisor else { return; };
    let owner = std::thread::current().id();
    let registered = supervisor.inner.pool_census.lock().map(|store| store.owns(owner)).unwrap_or(false);
    if !registered { return; }
    if outcome != "completed_post_drain" || !supervisor.is_healthy() {
        if let Ok(mut store) = supervisor.inner.pool_census.lock() {
            store.invalidate(if outcome == "cancelled" { "RequestCancelledLastObservationNotCurrent" }
                             else { "RequestFailedLastObservationNotCurrent" });
        }
        return;
    }
    // Capture on worker, outside publication mutex. Temporary metadata only.
    let observed = crate::inference::models::qwen35::decode_pool::worker_memory_snapshot()
        .map(|(mode, snapshot)| (mode, pool_census::project(snapshot)));
    if let Ok(mut store) = supervisor.inner.pool_census.lock() {
        store.record_result(owner, Instant::now(), slot, generation, observed);
    };
}

static PANIC_HOOK: Once = Once::new();

/// Chain a process panic hook that poisons the panicking engine worker's
/// supervisor *before* unwinding drops its channels. Pending streams then
/// observe the failure (not an anonymous closed channel) and readiness flips
/// to an explicit failure state. Panics on other threads are untouched.
fn install_worker_panic_hook() {
    PANIC_HOOK.call_once(|| {
        let previous = panic::take_hook();
        panic::set_hook(Box::new(move |info| {
            let supervisor = WORKER_SUPERVISOR
                .try_with(|slot| slot.try_borrow().ok().and_then(|slot| slot.clone()))
                .ok()
                .flatten();
            if let Some(supervisor) = supervisor {
                let location = info
                    .location()
                    .map(|location| format!(" at {}:{}", location.file(), location.line()))
                    .unwrap_or_default();
                supervisor.fail_worker(&format!(
                    "engine thread panicked{location}: {}",
                    panic_payload_message(info.payload())
                ));
            }
            previous(info);
        }));
    });
}

fn panic_payload_message(payload: &(dyn Any + Send)) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "non-string panic payload".to_string()
    }
}

/// Spawn the one model worker thread under `supervisor`. A panic anywhere in
/// `body` permanently fails the engine with the panic message; the panic is
/// contained to this thread so shutdown joins never re-raise it.
///
/// `body` owns the model. `teardown` says how the thread gives the model's
/// memory back ([`WorkerTeardown`]); a second thread waits for the worker to
/// terminate and completes it. The returned handle is that thread's: it is
/// finished when the worker is gone and its teardown has ended, released or
/// not.
pub(super) fn spawn_supervised_worker(
    name: &str,
    supervisor: EngineSupervisor,
    teardown: WorkerTeardown,
    body: impl FnOnce(EngineSupervisor) + Send + 'static,
) -> std::io::Result<JoinHandle<()>> {
    install_worker_panic_hook();
    let WorkerTeardown {
        memory,
        release_thread_caches,
    } = teardown;
    // The worker says when its teardown begins: from then until the
    // reservation is released or stranded, new admissions wait.
    let teardown_begins = memory
        .as_ref()
        .map(crate::serve::resident_memory::Reservation::teardown_marker);
    let worker_name = name.to_string();
    let (started, worker_started) =
        std::sync::mpsc::channel::<JoinHandle<std::result::Result<DeferredFlush, String>>>();
    let teardown_thread = std::thread::Builder::new()
        .name(format!("{name}-teardown"))
        .spawn(move || {
            let Ok(worker) = worker_started.recv() else {
                // The worker thread could not be started: its body, and the
                // model in it, were dropped by the failed spawn.
                drop(memory);
                return;
            };
            // Joining waits for the thread itself, not for its closure: the
            // worker's thread-locals are destroyed before this returns.
            let torn_down = match worker.join() {
                Ok(Ok(flush)) => {
                    match panic::catch_unwind(AssertUnwindSafe(flush)) {
                        Ok(flushed) => flushed.map_err(|error| format!("{error:#}")),
                        Err(payload) => Err(format!(
                            "the flush panicked: {}",
                            panic_payload_message(payload.as_ref())
                        )),
                    }
                }
                Ok(Err(reason)) => Err(reason),
                Err(payload) => Err(format!(
                    "the worker thread panicked outside its body: {}",
                    panic_payload_message(payload.as_ref())
                )),
            };
            match (torn_down, memory) {
                (Ok(()), memory) => drop(memory),
                (Err(reason), Some(memory)) => memory.strand(&format!(
                    "teardown of engine worker {worker_name} failed: {reason}"
                )),
                (Err(reason), None) => tracing::error!(
                    worker = %worker_name,
                    reason = %reason,
                    "engine worker teardown failed"
                ),
            }
        })?;
    let worker = std::thread::Builder::new()
        .name(name.to_string())
        .spawn(move || {
            WORKER_SUPERVISOR.with(|slot| *slot.borrow_mut() = Some(supervisor.clone()));
            if crate::debug::INVESTIGATION_ENV.worker_pool_census {
                if let Ok(mut store) = supervisor.inner.pool_census.lock() {
                    store.bind(std::thread::current().id());
                }
            }
            let outcome = panic::catch_unwind(AssertUnwindSafe(|| body(supervisor.clone())));
            WORKER_SUPERVISOR.with(|slot| slot.borrow_mut().take());
            if let Err(payload) = outcome {
                // Normally already recorded by the hook; this covers a hook
                // replaced by another component after installation.
                supervisor.fail_worker(&format!(
                    "engine thread panicked: {}",
                    panic_payload_message(payload.as_ref())
                ));
            }
            // The body has returned or unwound: the model is dropped. The
            // caches this thread built for it go next, here, where they live.
            if let Some(teardown) = teardown_begins {
                teardown.begin();
            }
            match panic::catch_unwind(AssertUnwindSafe(release_thread_caches)) {
                Ok(released) => released.map_err(|error| format!("{error:#}")),
                Err(payload) => Err(format!(
                    "releasing the worker's thread caches panicked: {}",
                    panic_payload_message(payload.as_ref())
                )),
            }
        })?;
    // Had the worker not started, the `?` above dropped `started` and the
    // teardown thread ended, releasing the reservation of a model that was
    // dropped with the worker's closure.
    let _ = started.send(worker);
    Ok(teardown_thread)
}

#[cfg(test)]
mod tests {
    #[test]
    fn admission_guards_count_until_dropped_on_every_path() {
        let supervisor = super::EngineSupervisor::new_with_monitor_start(|_| Ok(()));
        assert_eq!(supervisor.admissions_in_flight(), 0);
        let first = supervisor.begin_admission();
        let second = supervisor.clone().begin_admission();
        assert_eq!(supervisor.admissions_in_flight(), 2);
        drop(first);
        assert_eq!(supervisor.admissions_in_flight(), 1);
        // A preparing handler that panics still releases its count.
        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = supervisor.begin_admission();
            panic!("handler failed while preparing");
        }));
        assert!(panicked.is_err());
        assert_eq!(supervisor.admissions_in_flight(), 1);
        // A dropped (disconnected) handler future releases its count too.
        let future = {
            let guard = supervisor.begin_admission();
            async move {
                let _guard = guard;
                std::future::pending::<()>().await;
            }
        };
        assert_eq!(supervisor.admissions_in_flight(), 2);
        drop(future);
        drop(second);
        assert_eq!(supervisor.admissions_in_flight(), 0);
    }

    use super::*;

    #[tokio::test]
    async fn expired_transaction_poison_is_one_way_and_not_receiver_closure() {
        let supervisor = EngineSupervisor::new();
        let lease = supervisor
            .arm("synthetic-gpu", Duration::from_secs(60))
            .unwrap();
        supervisor.force_expire_for_test();
        supervisor.wait_unhealthy().await;
        assert!(!supervisor.is_healthy());
        assert!(supervisor.unhealthy_message().contains("synthetic-gpu"));
        assert!(lease.finish().is_err(), "late success must not heal poison");
        assert!(supervisor
            .arm("later-gpu", Duration::from_secs(60))
            .is_err());
    }

    #[test]
    fn timely_completion_disarms_without_poisoning() {
        let supervisor = EngineSupervisor::new();
        supervisor
            .arm("synthetic-gpu", Duration::from_secs(60))
            .unwrap()
            .finish()
            .unwrap();
        assert!(supervisor.is_healthy());
        supervisor
            .arm("second-gpu", Duration::from_secs(60))
            .unwrap()
            .finish()
            .unwrap();
    }

    #[test]
    fn finish_observes_its_own_deadline_before_monitor_poll() {
        let supervisor = EngineSupervisor::new();
        let lease = supervisor
            .arm("deadline-race", Duration::from_secs(60))
            .unwrap();
        supervisor.backdate_without_monitor_for_test();
        assert!(lease.finish().is_err());
        assert!(!supervisor.is_healthy());
        assert!(supervisor.unhealthy_message().contains("deadline-race"));
    }

    #[tokio::test]
    async fn poisoned_stream_emits_one_error_and_ignores_late_done() {
        let supervisor = EngineSupervisor::new();
        let lease = supervisor
            .arm("synthetic-stream-gpu", Duration::from_secs(60))
            .unwrap();
        let (source_tx, source_rx) = mpsc::channel(4);
        let mut guarded = supervisor.guard_generation_events(source_rx);
        source_tx
            .send(GenerationEvent::Delta {
                kind: super::super::sse::DeltaKind::Content,
                text: "partial".into(),
            })
            .await
            .unwrap();
        assert!(matches!(
            guarded.recv().await,
            Some(GenerationEvent::Delta { .. })
        ));

        supervisor.force_expire_for_test();
        assert!(matches!(
            guarded.recv().await,
            Some(GenerationEvent::Error(message)) if message.contains("synthetic-stream-gpu")
        ));
        assert!(guarded.recv().await.is_none());
        assert!(lease.finish().is_err());
        assert!(source_tx
            .send(GenerationEvent::Done {
                finish_reason: "stop".into(),
                prompt_tokens: 1,
                completion_tokens: 1,
                stats: Default::default(),
            })
            .await
            .is_err());
    }

    #[tokio::test]
    async fn poison_wins_over_an_already_buffered_done_event() {
        let supervisor = EngineSupervisor::new();
        let lease = supervisor
            .arm("buffered-done-race", Duration::from_secs(60))
            .unwrap();
        let (source_tx, source_rx) = mpsc::channel(1);
        source_tx
            .send(GenerationEvent::Done {
                finish_reason: "stop".into(),
                prompt_tokens: 1,
                completion_tokens: 1,
                stats: Default::default(),
            })
            .await
            .unwrap();
        supervisor.backdate_without_monitor_for_test();
        assert!(lease.finish().is_err());

        let mut guarded = supervisor.guard_generation_events(source_rx);
        assert!(matches!(
            guarded.recv().await,
            Some(GenerationEvent::Error(message)) if message.contains("buffered-done-race")
        ));
        assert!(guarded.recv().await.is_none());
    }

    #[tokio::test]
    async fn guarded_receiver_drop_closes_the_worker_source() {
        let supervisor = EngineSupervisor::new();
        let (source_tx, source_rx) = mpsc::channel(1);
        let guarded = supervisor.guard_generation_events(source_rx);

        drop(guarded);
        tokio::time::timeout(Duration::from_secs(1), source_tx.closed())
            .await
            .expect("guard task must drop the raw worker receiver promptly");
        assert!(source_tx
            .send(GenerationEvent::Delta {
                kind: super::super::sse::DeltaKind::Content,
                text: "late".into(),
            })
            .await
            .is_err());
    }

    #[tokio::test]
    async fn guarded_backpressure_closes_the_worker_source() {
        let supervisor = EngineSupervisor::new();
        let (source_tx, source_rx) = mpsc::channel(128);
        let _guarded = supervisor.guard_generation_events(source_rx);

        for index in 0..65 {
            source_tx
                .send(GenerationEvent::Delta {
                    kind: super::super::sse::DeltaKind::Content,
                    text: index.to_string(),
                })
                .await
                .expect("raw bridge accepts events until guarded capacity is exceeded");
        }
        tokio::time::timeout(Duration::from_secs(1), source_tx.closed())
            .await
            .expect("guard task must drop the raw receiver on slow-client backpressure");
        assert!(supervisor.is_healthy(), "slow clients are request-local");
    }

    #[tokio::test]
    async fn monitor_spawn_failure_poison_is_immediate_and_observable() {
        let supervisor = EngineSupervisor::new_with_monitor_start(|_| {
            Err(std::io::Error::other("injected monitor spawn failure"))
        });
        assert!(!supervisor.is_healthy());
        supervisor.wait_unhealthy().await;
        assert!(supervisor
            .unhealthy_message()
            .contains("supervisor-monitor-spawn"));
        assert!(supervisor
            .arm("unobservable-gpu", Duration::from_secs(60))
            .is_err());
    }
}