Skip to main content

khive_runtime/
resource_admission.rs

1//! Class admission and isolated execution for explicitly attributed background jobs.
2//! Interactive dispatch does not enter this module. A job's lease, not its awaiter,
3//! owns admission and tracking through the final actual blocking-child exit.
4
5use std::fmt;
6use std::future::Future;
7use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex, MutexGuard};
9use std::time::{Duration, Instant};
10use tokio::runtime::Handle;
11use tokio::sync::{watch, OwnedSemaphorePermit, Semaphore};
12use tokio::task::JoinHandle;
13
14mod priority;
15mod quiet;
16pub use quiet::{quiet_until, request_quiet, wait_until_not_quiet, MAX_QUIET_TTL_SECS};
17#[cfg(test)]
18mod tests;
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum WorkClass {
22    Warm,
23    Maintenance,
24}
25
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub struct WorkClassLimits {
28    warm: usize,
29    maintenance: usize,
30}
31impl WorkClassLimits {
32    pub fn validate(warm: usize, maintenance: usize) -> Result<Self, ResourceError> {
33        for (class, value) in [
34            (WorkClass::Warm, warm),
35            (WorkClass::Maintenance, maintenance),
36        ] {
37            if value == 0 || value > Semaphore::MAX_PERMITS {
38                return Err(ResourceError::InvalidLimit {
39                    class,
40                    value,
41                    max: Semaphore::MAX_PERMITS,
42                });
43            }
44        }
45        Ok(Self { warm, maintenance })
46    }
47    pub fn warm(self) -> usize {
48        self.warm
49    }
50    pub fn maintenance(self) -> usize {
51        self.maintenance
52    }
53}
54
55#[derive(Clone, Copy, Debug)]
56pub struct CleanupPolicy {
57    grace: Duration,
58}
59impl CleanupPolicy {
60    pub fn new(grace: Duration) -> Self {
61        Self { grace }
62    }
63    pub fn grace(self) -> Duration {
64        self.grace
65    }
66    pub fn deadline_from(self, now: Instant) -> Result<Instant, ResourceError> {
67        now.checked_add(self.grace)
68            .ok_or(ResourceError::DeadlineOverflow)
69    }
70}
71
72#[derive(Clone, Debug)]
73pub enum PriorityError {
74    Unsupported {
75        target: &'static str,
76    },
77    Os {
78        operation: &'static str,
79        code: Option<i32>,
80    },
81    Unexpected {
82        operation: &'static str,
83        value: i32,
84    },
85}
86#[derive(Clone, Debug)]
87pub enum ResourceError {
88    InvalidLimit {
89        class: WorkClass,
90        value: usize,
91        max: usize,
92    },
93    DeadlineOverflow,
94    Closed,
95    WrongDomain,
96    Priority(PriorityError),
97    ThreadStart(String),
98    RuntimeStart(String),
99    CoordinatorGone,
100    JoinFailed(String),
101}
102#[derive(Debug)]
103pub enum BackgroundJoinError {
104    Cancelled,
105    Panicked,
106    Other(String),
107}
108macro_rules! display_error {
109    ($($ty:ty),+ $(,)?) => {$ (
110        impl fmt::Display for $ty {
111            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{self:?}") }
112        }
113        impl std::error::Error for $ty {}
114    )+ };
115}
116display_error!(PriorityError, ResourceError, BackgroundJoinError);
117
118#[derive(Debug)]
119pub enum BodyOutcome<T> {
120    Finished(T),
121    Cancelled,
122}
123#[derive(Debug)]
124pub enum JobOutcome<T> {
125    Completed(T),
126    Cancelled,
127    Refused(PriorityError),
128    FinalizationTimedOut,
129}
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub enum FinalizationOutcome {
132    AttemptReturned,
133    AttemptTimedOut,
134    NoAttemptBeforeDeadline,
135    NoTelemetryToken,
136    AlreadyFinalized,
137    DeadlineOverflow,
138}
139#[derive(Clone, Debug)]
140pub struct ShutdownReport {
141    pub workers_exited: bool,
142    pub coordinator_joined: bool,
143    pub outstanding_jobs: usize,
144    pub incomplete_finalizations: usize,
145}
146
147fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
148    mutex
149        .lock()
150        .unwrap_or_else(std::sync::PoisonError::into_inner)
151}
152fn shorten(slot: &mut Option<Instant>, deadline: Instant) {
153    *slot = Some(slot.map_or(deadline, |old| old.min(deadline)));
154}
155struct StartGate {
156    closed: bool,
157    deadline: Option<Instant>,
158}
159struct JoinState {
160    coordinator: Option<std::thread::JoinHandle<()>>,
161    joining: bool,
162    joined: Option<Result<(), ResourceError>>,
163}
164struct Domain {
165    limits: WorkClassLimits,
166    cleanup: CleanupPolicy,
167    warm: Arc<Semaphore>,
168    maintenance: Arc<Semaphore>,
169    gate: Mutex<StartGate>,
170    changed: watch::Sender<()>,
171    supervisors: AtomicUsize,
172    jobs: AtomicUsize,
173    incomplete: AtomicUsize,
174    worker_exit: Mutex<Option<Result<(), ResourceError>>>,
175    join: Mutex<JoinState>,
176    posture_failure: Mutex<Option<PriorityError>>,
177    // Instance-local source-test seams at the real enqueue/publication boundary.
178    #[cfg(test)]
179    after_blocking_enqueue: Mutex<Option<Box<dyn FnOnce() + Send>>>,
180    #[cfg(test)]
181    blocking_dequeued: Mutex<Option<std::sync::mpsc::Sender<()>>>,
182}
183impl Domain {
184    fn new(limits: WorkClassLimits, cleanup: CleanupPolicy) -> Arc<Self> {
185        let (changed, _) = watch::channel(());
186        Arc::new(Self {
187            limits,
188            cleanup,
189            warm: Arc::new(Semaphore::new(limits.warm)),
190            maintenance: Arc::new(Semaphore::new(limits.maintenance)),
191            gate: Mutex::new(StartGate {
192                closed: false,
193                deadline: None,
194            }),
195            changed,
196            supervisors: AtomicUsize::new(0),
197            jobs: AtomicUsize::new(0),
198            incomplete: AtomicUsize::new(0),
199            worker_exit: Mutex::new(None),
200            join: Mutex::new(JoinState {
201                coordinator: None,
202                joining: false,
203                joined: None,
204            }),
205            posture_failure: Mutex::new(None),
206            #[cfg(test)]
207            after_blocking_enqueue: Mutex::new(None),
208            #[cfg(test)]
209            blocking_dequeued: Mutex::new(None),
210        })
211    }
212    fn notify(&self) {
213        let _ = self.changed.send(());
214    }
215    fn close(&self, deadline: Instant) {
216        {
217            let mut gate = lock(&self.gate);
218            gate.closed = true;
219            shorten(&mut gate.deadline, deadline);
220            self.warm.close();
221            self.maintenance.close();
222        }
223        self.notify();
224    }
225    fn close_with_policy(&self) -> Result<(), ResourceError> {
226        let now = Instant::now();
227        match self.cleanup.deadline_from(now) {
228            Ok(deadline) => {
229                self.close(deadline);
230                Ok(())
231            }
232            Err(error) => {
233                self.close(now);
234                Err(error)
235            }
236        }
237    }
238    fn closed_error(&self) -> ResourceError {
239        lock(&self.posture_failure)
240            .clone()
241            .map_or(ResourceError::Closed, ResourceError::Priority)
242    }
243    fn posture_failed(&self, error: PriorityError) {
244        tracing::error!(error = %error, "isolated background worker priority failed; closing domain");
245        let mut failure = lock(&self.posture_failure);
246        if failure.is_none() {
247            *failure = Some(error);
248        }
249        drop(failure);
250        let _ = self.close_with_policy();
251    }
252    fn report(&self) -> ShutdownReport {
253        ShutdownReport {
254            workers_exited: lock(&self.worker_exit).is_some(),
255            coordinator_joined: lock(&self.join).joined.as_ref().is_some_and(Result::is_ok),
256            outstanding_jobs: self.jobs.load(Ordering::SeqCst),
257            incomplete_finalizations: self.incomplete.load(Ordering::SeqCst),
258        }
259    }
260    async fn drive_until_closed(&self) {
261        let mut changed = self.changed.subscribe();
262        loop {
263            let (closed, deadline) = {
264                let gate = lock(&self.gate);
265                (gate.closed, gate.deadline)
266            };
267            if closed {
268                if self.supervisors.load(Ordering::SeqCst) == 0 {
269                    return;
270                }
271                let remaining = deadline
272                    .unwrap_or_else(Instant::now)
273                    .saturating_duration_since(Instant::now());
274                if remaining.is_zero() {
275                    return;
276                }
277                tokio::select! {
278                    _ = changed.changed() => {},
279                    _ = tokio::time::sleep(remaining) => {},
280                }
281            } else if changed.changed().await.is_err() {
282                return;
283            }
284        }
285    }
286}
287
288struct ExternalOwner {
289    domain: Arc<Domain>,
290    executor: Handle,
291}
292impl Drop for ExternalOwner {
293    fn drop(&mut self) {
294        let _ = self.domain.close_with_policy();
295    }
296}
297#[derive(Clone)]
298pub struct BackgroundRoot {
299    owner: Arc<ExternalOwner>,
300}
301pub type BackgroundDomainOwner = BackgroundRoot;
302#[derive(Clone)]
303pub struct BackgroundDomainHandle {
304    domain: Arc<Domain>,
305    executor: Handle,
306}
307#[derive(Clone)]
308pub struct BackgroundDomainControl {
309    domain: Arc<Domain>,
310}
311
312impl BackgroundRoot {
313    pub fn start(limits: WorkClassLimits, cleanup: CleanupPolicy) -> Result<Self, ResourceError> {
314        Self::start_inner(limits, cleanup, None)
315    }
316    fn start_inner(
317        limits: WorkClassLimits,
318        cleanup: CleanupPolicy,
319        blocking_threads: Option<usize>,
320    ) -> Result<Self, ResourceError> {
321        // Refuse a future deadline that cannot be represented before allocating workers.
322        cleanup.deadline_from(Instant::now())?;
323        let domain = Domain::new(limits, cleanup);
324        let worker_domain = domain.clone();
325        let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
326        let coordinator = std::thread::Builder::new()
327            .name("khive-background".into())
328            .spawn(move || {
329                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
330                    if let Err(error) = priority::lower_current_thread() {
331                        let error = ResourceError::Priority(error);
332                        let _ = ready_tx.send(Err(error.clone()));
333                        return Err(error);
334                    }
335                    let hook_domain = worker_domain.clone();
336                    let mut builder = tokio::runtime::Builder::new_current_thread();
337                    if let Some(count) = blocking_threads {
338                        builder.max_blocking_threads(count);
339                    }
340                    let runtime = match builder
341                        .enable_all()
342                        .on_thread_start(move || {
343                            if let Err(error) = priority::lower_current_thread() {
344                                hook_domain.posture_failed(error);
345                            }
346                        })
347                        .build()
348                    {
349                        Ok(runtime) => runtime,
350                        Err(error) => {
351                            let error = ResourceError::RuntimeStart(error.to_string());
352                            let _ = ready_tx.send(Err(error.clone()));
353                            return Err(error);
354                        }
355                    };
356                    if ready_tx.send(Ok(runtime.handle().clone())).is_err() {
357                        worker_domain.close(Instant::now());
358                    }
359                    runtime.block_on(worker_domain.drive_until_closed());
360                    // Deliberately on this standard thread. Async tasks are dropped, but
361                    // Runtime destruction still joins actual started blocking work.
362                    drop(runtime);
363                    Ok(())
364                }))
365                .unwrap_or_else(|_| Err(ResourceError::JoinFailed("coordinator panicked".into())));
366                *lock(&worker_domain.worker_exit) = Some(result);
367                worker_domain.notify();
368            })
369            .map_err(|error| ResourceError::ThreadStart(error.to_string()))?;
370        lock(&domain.join).coordinator = Some(coordinator);
371        let executor = ready_rx
372            .recv()
373            .map_err(|_| ResourceError::CoordinatorGone)??;
374        Ok(Self {
375            owner: Arc::new(ExternalOwner { domain, executor }),
376        })
377    }
378    pub fn handle(&self) -> BackgroundDomainHandle {
379        BackgroundDomainHandle {
380            domain: self.owner.domain.clone(),
381            executor: self.owner.executor.clone(),
382        }
383    }
384    pub fn control(&self) -> BackgroundDomainControl {
385        self.handle().control()
386    }
387    pub fn limits(&self) -> WorkClassLimits {
388        self.owner.domain.limits
389    }
390    pub fn cleanup_policy(&self) -> CleanupPolicy {
391        self.owner.domain.cleanup
392    }
393    pub fn same_domain(&self, other: &Self) -> bool {
394        Arc::ptr_eq(&self.owner.domain, &other.owner.domain)
395    }
396}
397
398impl BackgroundDomainControl {
399    /// Observe domain closure without retaining its external root owner.
400    /// Subscribe before the state read so a close between the read and await
401    /// cannot be lost. This wait never mutates admission or exposes a token.
402    pub async fn closed(&self) {
403        let mut changed = self.domain.changed.subscribe();
404        while !self.is_closed() {
405            // self retains the sender, so the channel cannot close while this
406            // wait is live. A version change triggers another state read.
407            let _ = changed.changed().await;
408        }
409    }
410    pub fn close(&self, deadline: Instant) {
411        self.domain.close(deadline);
412    }
413    pub fn close_with_policy(&self) -> Result<(), ResourceError> {
414        self.domain.close_with_policy()
415    }
416    pub fn is_closed(&self) -> bool {
417        lock(&self.domain.gate).closed
418    }
419    fn ensure_join_started(&self) -> Result<(), ResourceError> {
420        let mut join = lock(&self.domain.join);
421        if join.joining || join.joined.is_some() {
422            return Ok(());
423        }
424        let Some(coordinator) = join.coordinator.take() else {
425            return Err(ResourceError::CoordinatorGone);
426        };
427        // The envelope returns ownership on thread-creation failure. A detached
428        // reaper, not the requesting async future, owns completion publication.
429        let envelope = Arc::new(Mutex::new(Some(coordinator)));
430        let envelope_worker = envelope.clone();
431        let domain = self.domain.clone();
432        join.joining = true;
433        let spawned = std::thread::Builder::new()
434            .name("khive-background-join".into())
435            .spawn(move || {
436                let coordinator = lock(&envelope_worker)
437                    .take()
438                    .expect("single reaper owns coordinator");
439                let result = coordinator
440                    .join()
441                    .map_err(|_| ResourceError::JoinFailed("coordinator panicked".into()))
442                    .and_then(|()| {
443                        lock(&domain.worker_exit)
444                            .clone()
445                            .unwrap_or(Err(ResourceError::CoordinatorGone))
446                    });
447                let mut join = lock(&domain.join);
448                join.joined = Some(result);
449                join.joining = false;
450                drop(join);
451                domain.notify();
452            });
453        match spawned {
454            Ok(reaper) => {
455                drop(reaper);
456                Ok(())
457            }
458            Err(error) => {
459                join.coordinator = lock(&envelope).take();
460                join.joining = false;
461                Err(ResourceError::ThreadStart(error.to_string()))
462            }
463        }
464    }
465    /// Observe actual infrastructure exit using only this caller's budget.
466    /// May start the independently owned reaper, but never closes admission,
467    /// requests cancellation, or changes any domain/job cleanup deadline.
468    pub async fn observe_exit_until(
469        &self,
470        deadline: Instant,
471    ) -> Result<ShutdownReport, ResourceError> {
472        self.ensure_join_started()?;
473        let mut changed = self.domain.changed.subscribe();
474        loop {
475            let joined = { lock(&self.domain.join).joined.clone() };
476            if let Some(result) = joined {
477                result?;
478                return Ok(self.domain.report());
479            }
480            let remaining = deadline.saturating_duration_since(Instant::now());
481            if remaining.is_zero() {
482                return Ok(self.domain.report());
483            }
484            tokio::select! {
485                _ = changed.changed() => {},
486                _ = tokio::time::sleep(remaining) => {},
487            }
488        }
489    }
490    pub async fn shutdown(&self, deadline: Instant) -> Result<ShutdownReport, ResourceError> {
491        self.close(deadline);
492        self.ensure_join_started()?;
493        let mut changed = self.domain.changed.subscribe();
494        loop {
495            let joined = { lock(&self.domain.join).joined.clone() };
496            if let Some(result) = joined {
497                result?;
498                return Ok(self.domain.report());
499            }
500            // Every observer shares the first/shortest cleanup deadline. A
501            // notification must re-read it, never restart the caller's budget.
502            let effective = lock(&self.domain.gate).deadline.unwrap_or(deadline);
503            let remaining = effective.saturating_duration_since(Instant::now());
504            if remaining.is_zero() {
505                return Ok(self.domain.report());
506            }
507            tokio::select! {
508                _ = changed.changed() => {},
509                _ = tokio::time::sleep(remaining) => {},
510            }
511        }
512    }
513}
514
515#[derive(Clone)]
516pub struct TrackedJob {
517    _guard: Arc<crate::daemon::BackgroundTaskGuard>,
518}
519impl TrackedJob {
520    pub fn register(name: &'static str) -> Self {
521        Self {
522            _guard: Arc::new(crate::daemon::register_background_task(name)),
523        }
524    }
525}
526struct JobCancellation {
527    domain: Arc<Domain>,
528    requested: AtomicBool,
529    deadline: Mutex<Option<Instant>>,
530    deadline_overflow: AtomicBool,
531    // 0 unclaimed, 1 in progress, 2 returned/skipped, 3 incomplete.
532    finalization: AtomicU8,
533}
534impl JobCancellation {
535    fn request(&self) {
536        let gate = lock(&self.domain.gate);
537        if !self.requested.swap(true, Ordering::SeqCst) {
538            let now = Instant::now();
539            let deadline = self.domain.cleanup.deadline_from(now).unwrap_or_else(|_| {
540                self.deadline_overflow.store(true, Ordering::SeqCst);
541                now
542            });
543            shorten(&mut lock(&self.deadline), deadline);
544        }
545        drop(gate);
546        self.domain.notify();
547    }
548    fn is_cancelled(&self) -> bool {
549        lock(&self.domain.gate).closed || self.requested.load(Ordering::SeqCst)
550    }
551    fn effective_deadline(&self) -> Result<Instant, ResourceError> {
552        let gate = lock(&self.domain.gate);
553        let mut own = lock(&self.deadline);
554        if own.is_none() {
555            *own = Some(self.domain.cleanup.deadline_from(Instant::now())?);
556        }
557        Ok(gate
558            .deadline
559            .map_or(own.expect("deadline initialized"), |d| {
560                d.min(own.expect("deadline initialized"))
561            }))
562    }
563}
564struct Lease {
565    _permit: OwnedSemaphorePermit,
566    _tracking: TrackedJob,
567    cancel: Arc<JobCancellation>,
568    executor: Handle,
569    class: WorkClass,
570}
571impl Drop for Lease {
572    fn drop(&mut self) {
573        self.cancel.domain.jobs.fetch_sub(1, Ordering::SeqCst);
574        self.cancel.domain.notify();
575    }
576}
577#[derive(Clone)]
578pub struct AdmittedJob {
579    lease: Arc<Lease>,
580}
581
582struct SupervisorGuard {
583    cancel: Arc<JobCancellation>,
584    finished: bool,
585}
586impl Drop for SupervisorGuard {
587    fn drop(&mut self) {
588        let phase = self.cancel.finalization.load(Ordering::SeqCst);
589        if (!self.finished && phase < 2) || phase == 1 {
590            self.cancel.domain.incomplete.fetch_add(1, Ordering::SeqCst);
591        }
592        self.cancel
593            .domain
594            .supervisors
595            .fetch_sub(1, Ordering::SeqCst);
596        self.cancel.domain.notify();
597    }
598}
599fn start_decision(cancel: &JobCancellation) -> Result<(), JobOutcome<()>> {
600    let gate = lock(&cancel.domain.gate);
601    start_decision_locked(cancel, &gate)
602}
603fn start_decision_locked(cancel: &JobCancellation, gate: &StartGate) -> Result<(), JobOutcome<()>> {
604    if let Some(error) = lock(&cancel.domain.posture_failure).clone() {
605        return Err(JobOutcome::Refused(error));
606    }
607    if gate.closed || cancel.requested.load(Ordering::SeqCst) {
608        return Err(JobOutcome::Cancelled);
609    }
610    if let Err(error) = priority::check_current_thread() {
611        return Err(JobOutcome::Refused(error));
612    }
613    // Returning Ok linearizes Started before releasing the gate. A later cancel
614    // cannot revoke this body; its actual closure owns the lease until exit.
615    Ok(())
616}
617fn refusal<T>(outcome: JobOutcome<()>) -> JobOutcome<T> {
618    match outcome {
619        JobOutcome::Cancelled => JobOutcome::Cancelled,
620        JobOutcome::Refused(error) => JobOutcome::Refused(error),
621        _ => unreachable!("start decision only refuses cancellation or posture"),
622    }
623}
624impl BackgroundDomainHandle {
625    /// Read-only domain-close observation, including final root-owner drop.
626    pub async fn closed(&self) {
627        self.control().closed().await;
628    }
629    pub fn limits(&self) -> WorkClassLimits {
630        self.domain.limits
631    }
632    pub fn control(&self) -> BackgroundDomainControl {
633        BackgroundDomainControl {
634            domain: self.domain.clone(),
635        }
636    }
637    pub async fn admit(
638        &self,
639        class: WorkClass,
640        tracking: &TrackedJob,
641    ) -> Result<AdmittedJob, ResourceError> {
642        let semaphore = match class {
643            WorkClass::Warm => self.domain.warm.clone(),
644            WorkClass::Maintenance => self.domain.maintenance.clone(),
645        };
646        let permit = semaphore
647            .acquire_owned()
648            .await
649            .map_err(|_| self.domain.closed_error())?;
650        let gate = lock(&self.domain.gate);
651        if gate.closed {
652            return Err(self.domain.closed_error());
653        }
654        self.domain.jobs.fetch_add(1, Ordering::SeqCst);
655        let cancel = Arc::new(JobCancellation {
656            domain: self.domain.clone(),
657            requested: AtomicBool::new(false),
658            deadline: Mutex::new(None),
659            deadline_overflow: AtomicBool::new(false),
660            finalization: AtomicU8::new(0),
661        });
662        Ok(AdmittedJob {
663            lease: Arc::new(Lease {
664                _permit: permit,
665                _tracking: tracking.clone(),
666                cancel,
667                executor: self.executor.clone(),
668                class,
669            }),
670        })
671    }
672    pub fn spawn_supervised<F, Fut, T>(
673        &self,
674        job: AdmittedJob,
675        make: F,
676    ) -> Result<BackgroundJob<T>, ResourceError>
677    where
678        F: FnOnce(AdmittedJob) -> Fut + Send + 'static,
679        Fut: Future<Output = JobOutcome<T>> + Send + 'static,
680        T: Send + 'static,
681    {
682        if !Arc::ptr_eq(&self.domain, &job.lease.cancel.domain) {
683            return Err(ResourceError::WrongDomain);
684        }
685        let gate = lock(&self.domain.gate);
686        if gate.closed {
687            return Err(self.domain.closed_error());
688        }
689        let cancel = job.lease.cancel.clone();
690        self.domain.supervisors.fetch_add(1, Ordering::SeqCst);
691        let guard = SupervisorGuard {
692            cancel: cancel.clone(),
693            finished: false,
694        };
695        let task = self.executor.spawn(async move {
696            let mut guard = guard;
697            let execution_hold = job.clone();
698            let outcome = match start_decision(&job.lease.cancel) {
699                Ok(()) => {
700                    // Wait before entering a producer: it may acquire an ANN/model
701                    // guard that foreground work also needs. Cancellation and
702                    // posture refusal retain their normal start precedence.
703                    let _ = job.run_body(wait_until_not_quiet()).await;
704                    match start_decision(&job.lease.cancel) {
705                        Ok(()) => make(job).await,
706                        Err(outcome) => refusal(outcome),
707                    }
708                }
709                Err(outcome) => refusal(outcome),
710            };
711            guard.finished = true;
712            drop(execution_hold);
713            outcome
714        });
715        drop(gate);
716        Ok(BackgroundJob {
717            task: Some(task),
718            cancel,
719            cancel_on_drop: true,
720        })
721    }
722}
723impl AdmittedJob {
724    pub fn class(&self) -> WorkClass {
725        self.lease.class
726    }
727    pub fn is_cancelled(&self) -> bool {
728        self.lease.cancel.is_cancelled()
729    }
730    pub fn request_cancel(&self) {
731        self.lease.cancel.request();
732    }
733    pub async fn cancelled(&self) {
734        let mut changed = self.lease.cancel.domain.changed.subscribe();
735        while !self.is_cancelled() {
736            if changed.changed().await.is_err() {
737                return;
738            }
739        }
740    }
741    pub async fn run_body<F: Future>(&self, body: F) -> BodyOutcome<F::Output> {
742        if self.is_cancelled() {
743            return BodyOutcome::Cancelled;
744        }
745        tokio::select! {
746            biased;
747            result = body => BodyOutcome::Finished(result),
748            _ = self.cancelled() => BodyOutcome::Cancelled,
749        }
750    }
751    pub async fn finalize<F: Future<Output = ()>>(&self, append: F) -> FinalizationOutcome {
752        let cancel = &self.lease.cancel;
753        if cancel
754            .finalization
755            .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst)
756            .is_err()
757        {
758            return FinalizationOutcome::AlreadyFinalized;
759        }
760        let mut changed = cancel.domain.changed.subscribe();
761        let outcome = if cancel.deadline_overflow.load(Ordering::SeqCst) {
762            FinalizationOutcome::DeadlineOverflow
763        } else {
764            tokio::pin!(append);
765            let mut polled = false;
766            loop {
767                let deadline = match cancel.effective_deadline() {
768                    Ok(deadline) => deadline,
769                    Err(_) => break FinalizationOutcome::DeadlineOverflow,
770                };
771                let remaining = deadline.saturating_duration_since(Instant::now());
772                if remaining.is_zero() {
773                    break if polled {
774                        FinalizationOutcome::AttemptTimedOut
775                    } else {
776                        FinalizationOutcome::NoAttemptBeforeDeadline
777                    };
778                }
779                // Claiming the attempt precedes its first poll; deadline wakeups
780                // only shorten this same future, never construct a retry.
781                polled = true;
782                tokio::select! {
783                    biased;
784                    _ = &mut append => break FinalizationOutcome::AttemptReturned,
785                    _ = changed.changed() => {},
786                    _ = tokio::time::sleep(remaining) => {},
787                }
788            }
789        };
790        let incomplete = !matches!(outcome, FinalizationOutcome::AttemptReturned);
791        cancel
792            .finalization
793            .store(if incomplete { 3 } else { 2 }, Ordering::SeqCst);
794        if incomplete {
795            cancel.domain.incomplete.fetch_add(1, Ordering::SeqCst);
796        }
797        outcome
798    }
799    pub fn no_telemetry(&self) -> FinalizationOutcome {
800        if self
801            .lease
802            .cancel
803            .finalization
804            .compare_exchange(0, 2, Ordering::SeqCst, Ordering::SeqCst)
805            .is_ok()
806        {
807            FinalizationOutcome::NoTelemetryToken
808        } else {
809            FinalizationOutcome::AlreadyFinalized
810        }
811    }
812    pub fn spawn_blocking<F, T>(&self, body: F) -> Result<BackgroundJob<T>, ResourceError>
813    where
814        F: FnOnce() -> T + Send + 'static,
815        T: Send + 'static,
816    {
817        let domain = self.lease.cancel.domain.clone();
818        let gate = lock(&domain.gate);
819        if gate.closed {
820            return Err(domain.closed_error());
821        }
822        let cancel = self.lease.cancel.clone();
823        // Tokio can enqueue before panicking on worker creation. Only this
824        // recoverable escrow owns the user data and child lease. The inert
825        // queued wrapper owns neither after failed handoff reclamation.
826        let escrow = Arc::new(Mutex::new(BlockingEscrow {
827            published: false,
828            work: Some(BlockingWork {
829                body,
830                child: self.clone(),
831            }),
832        }));
833        let queued_escrow = escrow.clone();
834        let queued_domain = domain.clone();
835        // Catch *inside* the gate: a dequeued worker must not start user code
836        // between submission unwind and failed-publication/reclamation.
837        let submitted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
838            let task = self.lease.executor.spawn_blocking(move || {
839                #[cfg(test)]
840                if let Some(dequeued) = lock(&queued_domain.blocking_dequeued).take() {
841                    let _ = dequeued.send(());
842                }
843                let gate = lock(&queued_domain.gate);
844                let work = {
845                    let mut escrow = lock(&queued_escrow);
846                    if escrow.published {
847                        escrow.work.take()
848                    } else {
849                        None
850                    }
851                };
852                let Some(BlockingWork { body, child }) = work else {
853                    // Failed submit already reclaimed all user/lease ownership.
854                    return JobOutcome::Cancelled;
855                };
856                let decision = start_decision_locked(&child.lease.cancel, &gate);
857                drop(gate);
858                // Run AND drop user data outside the gate: destructors may
859                // reenter domain control. Started bodies keep the actual hold.
860                let outcome = match decision {
861                    Ok(()) => JobOutcome::Completed(body()),
862                    Err(outcome) => {
863                        drop(body);
864                        refusal(outcome)
865                    }
866                };
867                drop(child);
868                outcome
869            });
870            #[cfg(test)]
871            {
872                let fault = lock(&domain.after_blocking_enqueue).take();
873                if let Some(fault) = fault {
874                    fault();
875                }
876            }
877            task
878        }));
879        match submitted {
880            Ok(task) => {
881                lock(&escrow).published = true;
882                drop(gate);
883                Ok(BackgroundJob {
884                    task: Some(task),
885                    cancel,
886                    cancel_on_drop: true,
887                })
888            }
889            Err(payload) => {
890                let unstarted = lock(&escrow).work.take();
891                // published remains false while holding the start gate. The
892                // worker cannot take the reclaimed work after we unlock.
893                drop(gate);
894                drop(unstarted);
895                // Panic payloads may also have user-defined destructors.
896                drop(payload);
897                Err(ResourceError::ThreadStart(
898                    "blocking task submission panicked before handoff".into(),
899                ))
900            }
901        }
902    }
903}
904
905struct BlockingWork<F> {
906    // Field drop order keeps the child hold until captured user data is gone.
907    body: F,
908    child: AdmittedJob,
909}
910struct BlockingEscrow<F> {
911    // Accessed only under the domain start gate, then the escrow mutex.
912    published: bool,
913    work: Option<BlockingWork<F>>,
914}
915
916pub struct BackgroundJob<T> {
917    task: Option<JoinHandle<JobOutcome<T>>>,
918    cancel: Arc<JobCancellation>,
919    cancel_on_drop: bool,
920}
921impl<T> BackgroundJob<T> {
922    pub fn request_cancel(&self) {
923        self.cancel.request();
924    }
925    pub async fn join(mut self) -> Result<JobOutcome<T>, BackgroundJoinError> {
926        let result = self.task.as_mut().expect("join consumes one task").await;
927        self.cancel_on_drop = false;
928        result.map_err(|error| {
929            if error.is_cancelled() {
930                BackgroundJoinError::Cancelled
931            } else if error.is_panic() {
932                BackgroundJoinError::Panicked
933            } else {
934                BackgroundJoinError::Other(error.to_string())
935            }
936        })
937    }
938    pub fn detach(mut self) {
939        self.cancel_on_drop = false;
940    }
941}
942impl<T> Drop for BackgroundJob<T> {
943    fn drop(&mut self) {
944        if self.cancel_on_drop {
945            self.cancel.request();
946        }
947        // Dropping Tokio's JoinHandle detaches. It must not abort the phase
948        // supervisor that still owns the bounded terminal-emission attempt.
949    }
950}