Skip to main content

hawdb_qos/
lib.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![deny(unsafe_code)]
16
17mod device;
18mod process_memory;
19mod refusal;
20mod resource;
21mod runtime;
22
23use hawdb_core::time::Instant;
24use std::fmt::Debug;
25use std::str::FromStr;
26use std::sync::atomic::{AtomicU8, Ordering};
27use std::sync::{Arc, Mutex, RwLock};
28
29pub use device::{StorageDeviceDiscoverySource, StorageDeviceProfile, StorageMediaKind};
30pub use hawdb_core::{
31    RuntimeCancellationReason, RuntimeCancellationToken, RuntimeIoWaveController,
32    RuntimeIoWaveError, RuntimeIoWavePermit, RuntimeIoWaveTryAcquire, RuntimeTaskContext,
33};
34pub use process_memory::{
35    ProcessMemoryCapabilities, ProcessMemoryPolicy, ProcessMemoryPolicyConfig,
36    ProcessMemoryPolicySnapshot, ProcessMemoryProfile, ProcessMemorySnapshot,
37};
38pub use resource::{
39    IoConcurrencyBudget, RuntimeMemoryPressure, RuntimeMemorySnapshot, RuntimeResourceBudget,
40    RuntimeResourceSnapshot,
41};
42pub use runtime::{
43    RuntimeAdmissionCode, RuntimeAdmissionError, RuntimeAdmissionWaitError, RuntimeAdmissionWaiter,
44    RuntimeGovernor, RuntimeGovernorConfig, RuntimeGovernorLimits, RuntimeGovernorSnapshot,
45    RuntimeIoReservationScope, RuntimeMaintenanceMemoryReport, RuntimeMaintenanceWork,
46    RuntimePermit, RuntimeRetainedMemory, RuntimeRetainedResult, RuntimeRetainedResultError,
47    RuntimeRetainedResultResource, RuntimeRetainedResultSnapshot, RuntimeTelemetryEvent,
48    RuntimeTelemetryEventKind, RuntimeTelemetrySink, RuntimeWorkKind, RuntimeWorkPriority,
49    RuntimeWorkRequest,
50};
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum WorkPriority {
54    Foreground,
55    Background,
56}
57
58// Keep every class-indexed array exhaustive by generating it with the enum.
59macro_rules! define_work_classes {
60    ($($class:ident => $name:literal),+ $(,)?) => {
61        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
62        pub enum WorkClass {
63            $($class),+
64        }
65
66        impl WorkClass {
67            pub const ALL: [Self; [$($name),+].len()] = [$(Self::$class),+];
68
69            pub const fn as_index(self) -> usize {
70                self as usize
71            }
72
73            pub const fn as_str(self) -> &'static str {
74                match self {
75                    $(Self::$class => $name),+
76                }
77            }
78        }
79
80        impl FromStr for WorkClass {
81            type Err = &'static str;
82
83            fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
84                match value {
85                    $($name => Ok(Self::$class)),+,
86                    _ => Err("unknown work class"),
87                }
88            }
89        }
90    };
91}
92
93define_work_classes! {
94    Query => "query",
95    Mutation => "mutation",
96    Projection => "projection",
97    Import => "import",
98    Analytics => "analytics",
99    Shadow => "shadow",
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum QosTelemetryPhase {
104    Admission,
105    Completion,
106}
107
108impl QosTelemetryPhase {
109    pub const fn as_str(self) -> &'static str {
110        match self {
111            Self::Admission => "admission",
112            Self::Completion => "completion",
113        }
114    }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum QosTelemetryOutcome {
119    Admitted,
120    Deferred,
121    Rejected,
122    Completed,
123    Failed,
124}
125
126impl QosTelemetryOutcome {
127    pub const fn as_str(self) -> &'static str {
128        match self {
129            Self::Admitted => "admitted",
130            Self::Deferred => "deferred",
131            Self::Rejected => "rejected",
132            Self::Completed => "completed",
133            Self::Failed => "failed",
134        }
135    }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct QosTelemetryEvent {
140    pub phase: QosTelemetryPhase,
141    pub outcome: QosTelemetryOutcome,
142    pub class: WorkClass,
143    pub estimated_operations: usize,
144    pub elapsed_micros: u64,
145    pub admission_code: Option<QosAdmissionCode>,
146}
147
148pub trait QosTelemetrySink: Debug + Send + Sync {
149    fn record_qos(&self, event: QosTelemetryEvent);
150
151    /// Opt in to per-unit events from batched admissions. A batched owner
152    /// samples this once per admission; sinks that return `false` (the
153    /// default) receive only the per-batch admission/completion events.
154    fn observes_units(&self) -> bool {
155        false
156    }
157
158    /// One bounded unit inside an admitted batch started or ended. Called
159    /// only when [`Self::observes_units`] returned `true` at admission.
160    fn record_qos_unit(&self, _event: QosUnitEvent) {}
161}
162
163/// A unit of work charged to an already admitted batch permit.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum QosUnitPhase {
166    Started,
167    Finished,
168    Abandoned,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub struct QosUnitEvent {
173    pub phase: QosUnitPhase,
174    pub class: WorkClass,
175    /// One-based position of the unit inside its admitted batch.
176    pub unit_in_batch: usize,
177}
178
179impl WorkPriority {
180    pub fn as_str(self) -> &'static str {
181        match self {
182            WorkPriority::Foreground => "foreground",
183            WorkPriority::Background => "background",
184        }
185    }
186}
187
188impl FromStr for WorkPriority {
189    type Err = &'static str;
190
191    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
192        match value {
193            "foreground" => Ok(WorkPriority::Foreground),
194            "background" => Ok(WorkPriority::Background),
195            _ => Err("unknown work priority"),
196        }
197    }
198}
199
200pub const WORK_CLASS_COUNT: usize = WorkClass::ALL.len();
201
202const _: () = {
203    let mut index = 0;
204    while index < WORK_CLASS_COUNT {
205        assert!(WorkClass::ALL[index].as_index() == index);
206        index += 1;
207    }
208};
209
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct WorkRequest {
212    pub class: WorkClass,
213    pub priority: WorkPriority,
214    pub estimated_operations: usize,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Default)]
218pub struct BackgroundWorkHint {
219    pub active_topic: bool,
220    pub recent_delta_operations: usize,
221    pub source_graph_commit_lag: u64,
222    pub query_probability_per_million: u32,
223    pub staleness_millis: u64,
224    pub staleness_ttl_millis: Option<u64>,
225    pub freshness_slo_millis: Option<u64>,
226    pub tenant_budget_remaining_operations: Option<usize>,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct BackgroundWorkPlan {
231    pub request: WorkRequest,
232    pub hint: BackgroundWorkHint,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct BackgroundWorkDecision {
237    pub admission: QosAdmission,
238    pub score: u64,
239    pub reason_codes: Vec<BackgroundWorkReasonCode>,
240    pub reasons: Vec<String>,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct RankedBackgroundWork {
245    pub index: usize,
246    pub decision: BackgroundWorkDecision,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct LocalQosSnapshot {
251    pub ready: bool,
252    pub foreground_admitted: bool,
253    pub background_enabled: bool,
254    pub background_bounded: bool,
255    pub running_background_operations: usize,
256    pub max_total_background_operations: Option<usize>,
257    pub remaining_total_background_operations: Option<usize>,
258    pub total_background_over_budget: bool,
259    pub class_snapshots: [LocalQosClassSnapshot; WORK_CLASS_COUNT],
260    pub blocker_codes: Vec<QosSnapshotBlockerCode>,
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct LocalQosClassSnapshot {
265    pub class: WorkClass,
266    pub running_background_operations: usize,
267    pub max_background_operations: Option<usize>,
268    pub remaining_background_operations: Option<usize>,
269    pub over_budget: bool,
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum QosSnapshotBlockerCode {
274    ForegroundAdmissionBlocked,
275    BackgroundDisabled,
276    BackgroundUnbounded,
277    TotalBackgroundOverBudget,
278    ClassBackgroundOverBudget,
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub enum BackgroundWorkReasonCode {
283    ForegroundNotRanked,
284    TenantBudgetBelowEstimate,
285    ActiveTopic,
286    QueryProbability,
287    RecentDeltaOperations,
288    SourceGraphCommitLag,
289    StalenessTtl,
290    FreshnessSlo,
291    AdmissionDeferred,
292    AdmissionRejected,
293}
294
295impl BackgroundWorkReasonCode {
296    pub fn as_str(self) -> &'static str {
297        match self {
298            BackgroundWorkReasonCode::ForegroundNotRanked => "foreground_not_ranked",
299            BackgroundWorkReasonCode::TenantBudgetBelowEstimate => "tenant_budget_below_estimate",
300            BackgroundWorkReasonCode::ActiveTopic => "active_topic",
301            BackgroundWorkReasonCode::QueryProbability => "query_probability",
302            BackgroundWorkReasonCode::RecentDeltaOperations => "recent_delta_operations",
303            BackgroundWorkReasonCode::SourceGraphCommitLag => "source_graph_commit_lag",
304            BackgroundWorkReasonCode::StalenessTtl => "staleness_ttl",
305            BackgroundWorkReasonCode::FreshnessSlo => "freshness_slo",
306            BackgroundWorkReasonCode::AdmissionDeferred => "admission_deferred",
307            BackgroundWorkReasonCode::AdmissionRejected => "admission_rejected",
308        }
309    }
310}
311
312impl QosSnapshotBlockerCode {
313    pub fn as_str(self) -> &'static str {
314        match self {
315            QosSnapshotBlockerCode::ForegroundAdmissionBlocked => "foreground_admission_blocked",
316            QosSnapshotBlockerCode::BackgroundDisabled => "background_disabled",
317            QosSnapshotBlockerCode::BackgroundUnbounded => "background_unbounded",
318            QosSnapshotBlockerCode::TotalBackgroundOverBudget => "total_background_over_budget",
319            QosSnapshotBlockerCode::ClassBackgroundOverBudget => "class_background_over_budget",
320        }
321    }
322}
323
324impl FromStr for BackgroundWorkReasonCode {
325    type Err = &'static str;
326
327    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
328        match value {
329            "foreground_not_ranked" => Ok(BackgroundWorkReasonCode::ForegroundNotRanked),
330            "tenant_budget_below_estimate" => {
331                Ok(BackgroundWorkReasonCode::TenantBudgetBelowEstimate)
332            }
333            "active_topic" => Ok(BackgroundWorkReasonCode::ActiveTopic),
334            "query_probability" => Ok(BackgroundWorkReasonCode::QueryProbability),
335            "recent_delta_operations" => Ok(BackgroundWorkReasonCode::RecentDeltaOperations),
336            "source_graph_commit_lag" => Ok(BackgroundWorkReasonCode::SourceGraphCommitLag),
337            "staleness_ttl" => Ok(BackgroundWorkReasonCode::StalenessTtl),
338            "freshness_slo" => Ok(BackgroundWorkReasonCode::FreshnessSlo),
339            "admission_deferred" => Ok(BackgroundWorkReasonCode::AdmissionDeferred),
340            "admission_rejected" => Ok(BackgroundWorkReasonCode::AdmissionRejected),
341            _ => Err("unknown background work reason code"),
342        }
343    }
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub struct LocalQosPolicy {
348    pub max_background_operations: Option<usize>,
349    pub max_total_background_operations: Option<usize>,
350    pub max_background_operations_by_class: [Option<usize>; WORK_CLASS_COUNT],
351    pub background_enabled: bool,
352}
353
354#[derive(Debug, Clone, Default, PartialEq, Eq)]
355pub struct LocalQosState {
356    pub running_background_operations: usize,
357    pub running_background_operations_by_class: [usize; WORK_CLASS_COUNT],
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub enum QosAdmission {
362    Admit,
363    Defer {
364        code: QosAdmissionCode,
365        reason: String,
366    },
367    Reject {
368        code: QosAdmissionCode,
369        reason: String,
370    },
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum QosAdmissionCode {
375    BackgroundDisabled,
376    PerWorkLimitExceeded,
377    TotalBackgroundLimitExceeded,
378    ClassBackgroundLimitExceeded,
379    TenantBudgetExceeded,
380}
381
382impl QosAdmissionCode {
383    pub fn as_str(self) -> &'static str {
384        match self {
385            QosAdmissionCode::BackgroundDisabled => "background_disabled",
386            QosAdmissionCode::PerWorkLimitExceeded => "per_work_limit_exceeded",
387            QosAdmissionCode::TotalBackgroundLimitExceeded => "total_background_limit_exceeded",
388            QosAdmissionCode::ClassBackgroundLimitExceeded => "class_background_limit_exceeded",
389            QosAdmissionCode::TenantBudgetExceeded => "tenant_budget_exceeded",
390        }
391    }
392}
393
394impl FromStr for QosAdmissionCode {
395    type Err = &'static str;
396
397    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
398        match value {
399            "background_disabled" => Ok(QosAdmissionCode::BackgroundDisabled),
400            "per_work_limit_exceeded" => Ok(QosAdmissionCode::PerWorkLimitExceeded),
401            "total_background_limit_exceeded" => Ok(QosAdmissionCode::TotalBackgroundLimitExceeded),
402            "class_background_limit_exceeded" => Ok(QosAdmissionCode::ClassBackgroundLimitExceeded),
403            "tenant_budget_exceeded" => Ok(QosAdmissionCode::TenantBudgetExceeded),
404            _ => Err("unknown qos admission code"),
405        }
406    }
407}
408
409#[derive(Debug)]
410pub struct LocalQosPermit {
411    scheduler: Arc<LocalQosSchedulerInner>,
412    request: WorkRequest,
413    started_at: Instant,
414    released: bool,
415}
416
417#[derive(Debug, Clone)]
418pub struct LocalQosScheduler {
419    inner: Arc<LocalQosSchedulerInner>,
420}
421
422#[derive(Debug)]
423struct LocalQosSchedulerInner {
424    policy: LocalQosPolicy,
425    state: Mutex<SchedulerState>,
426    telemetry: RwLock<Option<Arc<dyn QosTelemetrySink>>>,
427}
428
429/// Charged operations, including batch permits that are currently idle.
430/// Idle batches are excluded from every observable state and are reclaimed
431/// when they would otherwise refuse another background admission.
432#[derive(Debug, Default)]
433struct SchedulerState {
434    charged: LocalQosState,
435    batches: Vec<Arc<BatchSlot>>,
436}
437
438const BATCH_ACTIVE: u8 = 0;
439const BATCH_IDLE: u8 = 1;
440const BATCH_RECLAIMED: u8 = 2;
441const BATCH_FINISHED: u8 = 3;
442
443#[derive(Debug)]
444struct BatchSlot {
445    state: AtomicU8,
446    request: WorkRequest,
447    started_at: Instant,
448}
449
450/// A background permit that covers a bounded sequence of short units
451/// without one scheduler round trip per unit (#1616).
452///
453/// The batch charges its operations only while a unit runs. Between units
454/// the owner marks it idle with [`Self::idle`]. An idle batch is not visible
455/// in [`LocalQosScheduler::state`] and any background admission that its
456/// charge would refuse reclaims it first; [`Self::resume`] then returns
457/// `false` and the owner must admit a new batch. The owner must still bound
458/// the number of units per batch: that bound is where competing background
459/// work, the deadline and the scheduler policy are observed again.
460#[derive(Debug)]
461pub struct LocalQosBatchPermit {
462    scheduler: Arc<LocalQosSchedulerInner>,
463    slot: Arc<BatchSlot>,
464    finished: bool,
465}
466
467impl SchedulerState {
468    fn charge(&mut self, request: &WorkRequest) {
469        let state = &mut self.charged;
470        state.running_background_operations = state
471            .running_background_operations
472            .saturating_add(request.estimated_operations);
473        let class_index = request.class.as_index();
474        state.running_background_operations_by_class[class_index] = state
475            .running_background_operations_by_class[class_index]
476            .saturating_add(request.estimated_operations);
477    }
478
479    fn refund(state: &mut LocalQosState, request: &WorkRequest) {
480        state.running_background_operations = state
481            .running_background_operations
482            .saturating_sub(request.estimated_operations);
483        let class_index = request.class.as_index();
484        state.running_background_operations_by_class[class_index] = state
485            .running_background_operations_by_class[class_index]
486            .saturating_sub(request.estimated_operations);
487    }
488
489    /// Operations of work that is actually running.
490    fn view(&self) -> LocalQosState {
491        let mut view = self.charged.clone();
492        for slot in &self.batches {
493            if slot.state.load(Ordering::Acquire) == BATCH_IDLE {
494                Self::refund(&mut view, &slot.request);
495            }
496        }
497        view
498    }
499
500    /// Reclaim every idle batch. Each reclaimed owner observes it on resume.
501    fn reclaim_idle(&mut self) -> Vec<Arc<BatchSlot>> {
502        let mut reclaimed = Vec::new();
503        let charged = &mut self.charged;
504        self.batches.retain(|slot| {
505            let idle = slot
506                .state
507                .compare_exchange(
508                    BATCH_IDLE,
509                    BATCH_RECLAIMED,
510                    Ordering::AcqRel,
511                    Ordering::Acquire,
512                )
513                .is_ok();
514            if idle {
515                Self::refund(charged, &slot.request);
516                reclaimed.push(slot.clone());
517            }
518            !idle
519        });
520        reclaimed
521    }
522}
523
524impl LocalQosBatchPermit {
525    pub fn request(&self) -> &WorkRequest {
526        &self.slot.request
527    }
528
529    /// Mark the batch running before its next unit. Returns `false` when the
530    /// scheduler reclaimed it while idle; the owner then admits a new batch.
531    pub fn resume(&self) -> bool {
532        match self.slot.state.compare_exchange(
533            BATCH_IDLE,
534            BATCH_ACTIVE,
535            Ordering::AcqRel,
536            Ordering::Acquire,
537        ) {
538            Ok(_) => true,
539            Err(state) => state == BATCH_ACTIVE,
540        }
541    }
542
543    /// No unit of this batch is running; its charge may be reclaimed.
544    pub fn idle(&self) {
545        let _ = self.slot.state.compare_exchange(
546            BATCH_ACTIVE,
547            BATCH_IDLE,
548            Ordering::AcqRel,
549            Ordering::Acquire,
550        );
551    }
552
553    /// The scheduler reclaimed this batch while it was idle.
554    pub fn is_reclaimed(&self) -> bool {
555        self.slot.state.load(Ordering::Acquire) == BATCH_RECLAIMED
556    }
557
558    pub fn finish_with_outcome(mut self, success: bool) {
559        self.release(success, None);
560    }
561
562    pub fn finish_with_outcome_at(mut self, success: bool, finished_at: Instant) {
563        self.release(success, Some(finished_at));
564    }
565
566    /// Reads the clock only when this batch still owns its completion.
567    fn release(&mut self, success: bool, finished_at: Option<Instant>) {
568        if self.finished {
569            return;
570        }
571        self.finished = true;
572        let owned = {
573            let mut state = self.scheduler.lock();
574            let owned = self.slot.state.swap(BATCH_FINISHED, Ordering::AcqRel) != BATCH_RECLAIMED;
575            if owned {
576                SchedulerState::refund(&mut state.charged, &self.slot.request);
577                state.batches.retain(|slot| !Arc::ptr_eq(slot, &self.slot));
578            }
579            owned
580        };
581        // A reclaimed batch already reported its completion.
582        if owned {
583            self.scheduler.record_completion(
584                &self.slot.request,
585                self.slot.started_at,
586                finished_at.unwrap_or_else(Instant::now),
587                success,
588            );
589        }
590    }
591}
592
593impl Drop for LocalQosBatchPermit {
594    fn drop(&mut self) {
595        self.release(false, None);
596    }
597}
598
599impl PartialEq for LocalQosPermit {
600    fn eq(&self, other: &Self) -> bool {
601        self.request == other.request
602    }
603}
604
605impl Eq for LocalQosPermit {}
606
607impl PartialEq for LocalQosScheduler {
608    fn eq(&self, other: &Self) -> bool {
609        Arc::ptr_eq(&self.inner, &other.inner)
610            || (self.policy() == other.policy() && self.state() == other.state())
611    }
612}
613
614impl Eq for LocalQosScheduler {}
615
616impl Default for LocalQosPolicy {
617    fn default() -> Self {
618        Self {
619            max_background_operations: Some(1024),
620            max_total_background_operations: Some(4096),
621            max_background_operations_by_class: [None; WORK_CLASS_COUNT],
622            background_enabled: true,
623        }
624    }
625}
626
627impl WorkRequest {
628    pub fn foreground(class: WorkClass, estimated_operations: usize) -> Self {
629        Self {
630            class,
631            priority: WorkPriority::Foreground,
632            estimated_operations,
633        }
634    }
635
636    pub fn background(class: WorkClass, estimated_operations: usize) -> Self {
637        Self {
638            class,
639            priority: WorkPriority::Background,
640            estimated_operations,
641        }
642    }
643}
644
645impl BackgroundWorkHint {
646    /// Score this hint for the same estimate used by background admission.
647    /// A tenant budget below the estimate produces zero, even for active topics.
648    pub fn expected_value_score(&self, estimated_operations: usize) -> u64 {
649        self.score_with_reasons(estimated_operations).0
650    }
651
652    fn score_with_reasons(
653        &self,
654        estimated_operations: usize,
655    ) -> (u64, Vec<BackgroundWorkReasonCode>, Vec<String>) {
656        let mut score = 0u64;
657        let mut reason_codes = Vec::new();
658        let mut reasons = Vec::new();
659
660        if let Some(remaining) = self.tenant_budget_remaining_operations
661            && remaining < estimated_operations
662        {
663            reason_codes.push(BackgroundWorkReasonCode::TenantBudgetBelowEstimate);
664            reasons.push(format!(
665                "tenant budget remaining {remaining} below estimated operations {estimated_operations}"
666            ));
667            return (0, reason_codes, reasons);
668        }
669
670        if self.active_topic {
671            score = score.saturating_add(1_000_000);
672            reason_codes.push(BackgroundWorkReasonCode::ActiveTopic);
673            reasons.push("active topic".to_string());
674        }
675
676        let query_probability = u64::from(self.query_probability_per_million).min(1_000_000);
677        if query_probability > 0 {
678            score = score.saturating_add(query_probability);
679            reason_codes.push(BackgroundWorkReasonCode::QueryProbability);
680            reasons.push(format!("query probability {query_probability} per million"));
681        }
682
683        let recent_delta_score = (self.recent_delta_operations as u64).min(1_000_000);
684        if recent_delta_score > 0 {
685            score = score.saturating_add(recent_delta_score);
686            reason_codes.push(BackgroundWorkReasonCode::RecentDeltaOperations);
687            reasons.push(format!(
688                "recent delta operations {}",
689                self.recent_delta_operations
690            ));
691        }
692
693        let source_graph_commit_lag_score = self.source_graph_commit_lag.min(1_000_000);
694        if source_graph_commit_lag_score > 0 {
695            score = score.saturating_add(source_graph_commit_lag_score);
696            reason_codes.push(BackgroundWorkReasonCode::SourceGraphCommitLag);
697            reasons.push(format!(
698                "source graph commit lag {}",
699                self.source_graph_commit_lag
700            ));
701        }
702
703        if let Some(ttl) = self.staleness_ttl_millis {
704            let staleness_score = scaled_staleness_score(self.staleness_millis, ttl);
705            if staleness_score > 0 {
706                score = score.saturating_add(staleness_score);
707                reason_codes.push(BackgroundWorkReasonCode::StalenessTtl);
708                if self.staleness_millis >= ttl {
709                    reasons.push(format!(
710                        "staleness ttl reached at {} ms",
711                        self.staleness_millis
712                    ));
713                } else {
714                    reasons.push(format!(
715                        "staleness {} of ttl {} ms",
716                        self.staleness_millis, ttl
717                    ));
718                }
719            }
720        }
721
722        if let Some(slo) = self.freshness_slo_millis {
723            let freshness_score = scaled_staleness_score(self.staleness_millis, slo);
724            if freshness_score > 0 {
725                score = score.saturating_add(freshness_score);
726                reason_codes.push(BackgroundWorkReasonCode::FreshnessSlo);
727                if self.staleness_millis >= slo {
728                    reasons.push(format!(
729                        "freshness slo missed at {} ms",
730                        self.staleness_millis
731                    ));
732                } else {
733                    reasons.push(format!(
734                        "freshness age {} of slo {} ms",
735                        self.staleness_millis, slo
736                    ));
737                }
738            }
739        }
740
741        (score, reason_codes, reasons)
742    }
743}
744
745impl BackgroundWorkPlan {
746    pub fn background(
747        class: WorkClass,
748        estimated_operations: usize,
749        hint: BackgroundWorkHint,
750    ) -> Self {
751        Self {
752            request: WorkRequest::background(class, estimated_operations),
753            hint,
754        }
755    }
756}
757
758impl LocalQosPolicy {
759    pub fn snapshot(&self, state: &LocalQosState) -> LocalQosSnapshot {
760        let foreground_admission = self.foreground_admission();
761        let foreground_admitted = matches!(foreground_admission, QosAdmission::Admit);
762        let background_bounded = self.max_background_operations.is_some()
763            || self.max_total_background_operations.is_some()
764            || self
765                .max_background_operations_by_class
766                .iter()
767                .any(Option::is_some);
768        let total_background_over_budget = self
769            .max_total_background_operations
770            .is_some_and(|limit| state.running_background_operations > limit);
771        let class_snapshots = local_qos_class_snapshots(self, state);
772        let class_background_over_budget =
773            class_snapshots.iter().any(|snapshot| snapshot.over_budget);
774        let mut blocker_codes = Vec::new();
775        if !foreground_admitted {
776            blocker_codes.push(QosSnapshotBlockerCode::ForegroundAdmissionBlocked);
777        }
778        if !self.background_enabled {
779            blocker_codes.push(QosSnapshotBlockerCode::BackgroundDisabled);
780        }
781        if !background_bounded {
782            blocker_codes.push(QosSnapshotBlockerCode::BackgroundUnbounded);
783        }
784        if total_background_over_budget {
785            blocker_codes.push(QosSnapshotBlockerCode::TotalBackgroundOverBudget);
786        }
787        if class_background_over_budget {
788            blocker_codes.push(QosSnapshotBlockerCode::ClassBackgroundOverBudget);
789        }
790        LocalQosSnapshot {
791            ready: blocker_codes.is_empty(),
792            foreground_admitted,
793            background_enabled: self.background_enabled,
794            background_bounded,
795            running_background_operations: state.running_background_operations,
796            max_total_background_operations: self.max_total_background_operations,
797            remaining_total_background_operations: self
798                .max_total_background_operations
799                .map(|limit| limit.saturating_sub(state.running_background_operations)),
800            total_background_over_budget,
801            class_snapshots,
802            blocker_codes,
803        }
804    }
805
806    /// Foreground work bypasses this local background budget policy.
807    /// Runtime resource admission is enforced separately by the governor.
808    pub fn foreground_admission(&self) -> QosAdmission {
809        QosAdmission::Admit
810    }
811
812    pub fn admit(&self, state: &LocalQosState, request: &WorkRequest) -> QosAdmission {
813        match request.priority {
814            WorkPriority::Foreground => self.foreground_admission(),
815            WorkPriority::Background => self.admit_background(state, request),
816        }
817    }
818
819    pub fn evaluate_background_work(
820        &self,
821        state: &LocalQosState,
822        plan: &BackgroundWorkPlan,
823    ) -> BackgroundWorkDecision {
824        let policy_admission = self.admit(state, &plan.request);
825        if plan.request.priority != WorkPriority::Background {
826            return BackgroundWorkDecision {
827                admission: policy_admission,
828                score: 0,
829                reason_codes: vec![BackgroundWorkReasonCode::ForegroundNotRanked],
830                reasons: vec!["foreground work is not background-ranked".to_string()],
831            };
832        }
833
834        let admission = match (
835            policy_admission,
836            plan.hint
837                .tenant_budget_defer_reason(plan.request.estimated_operations),
838        ) {
839            (QosAdmission::Admit, Some(reason)) => QosAdmission::Defer {
840                code: QosAdmissionCode::TenantBudgetExceeded,
841                reason,
842            },
843            (admission, _) => admission,
844        };
845        let (score, mut reason_codes, mut reasons) = plan
846            .hint
847            .score_with_reasons(plan.request.estimated_operations);
848        match &admission {
849            QosAdmission::Admit => {}
850            QosAdmission::Defer { reason, .. } => {
851                reason_codes.push(BackgroundWorkReasonCode::AdmissionDeferred);
852                reasons.push(format!("admission deferred: {reason}"));
853            }
854            QosAdmission::Reject { reason, .. } => {
855                reason_codes.push(BackgroundWorkReasonCode::AdmissionRejected);
856                reasons.push(format!("admission rejected: {reason}"));
857            }
858        }
859
860        BackgroundWorkDecision {
861            admission,
862            score,
863            reason_codes,
864            reasons,
865        }
866    }
867
868    pub fn rank_background_work(
869        &self,
870        state: &LocalQosState,
871        plans: &[BackgroundWorkPlan],
872    ) -> Vec<RankedBackgroundWork> {
873        let mut ranked = plans
874            .iter()
875            .enumerate()
876            .map(|(index, plan)| RankedBackgroundWork {
877                index,
878                decision: self.evaluate_background_work(state, plan),
879            })
880            .collect::<Vec<_>>();
881        ranked.sort_by(|left, right| {
882            admission_rank(&left.decision.admission)
883                .cmp(&admission_rank(&right.decision.admission))
884                .then_with(|| right.decision.score.cmp(&left.decision.score))
885                .then_with(|| left.index.cmp(&right.index))
886        });
887        ranked
888    }
889
890    fn admit_background(&self, state: &LocalQosState, request: &WorkRequest) -> QosAdmission {
891        if !self.background_enabled {
892            return QosAdmission::Defer {
893                code: QosAdmissionCode::BackgroundDisabled,
894                reason: "background work is disabled".to_string(),
895            };
896        }
897        if let Some(limit) = self.max_background_operations
898            && request.estimated_operations > limit
899        {
900            return QosAdmission::Defer {
901                code: QosAdmissionCode::PerWorkLimitExceeded,
902                reason: format!(
903                    "background {:?} estimated operations {} exceeded per-work limit {limit}",
904                    request.class, request.estimated_operations
905                ),
906            };
907        }
908        if let Some(limit) = self.max_total_background_operations {
909            let total = state
910                .running_background_operations
911                .saturating_add(request.estimated_operations);
912            if total > limit {
913                return QosAdmission::Defer {
914                    code: QosAdmissionCode::TotalBackgroundLimitExceeded,
915                    reason: format!(
916                        "background {:?} would raise running operations to {total}, above limit {limit}",
917                        request.class
918                    ),
919                };
920            }
921        }
922        if let Some(limit) = self.max_background_operations_by_class[request.class.as_index()] {
923            let class_total = state.running_background_operations_by_class
924                [request.class.as_index()]
925            .saturating_add(request.estimated_operations);
926            if class_total > limit {
927                return QosAdmission::Defer {
928                    code: QosAdmissionCode::ClassBackgroundLimitExceeded,
929                    reason: format!(
930                        "background {:?} would raise class running operations to {class_total}, above class limit {limit}",
931                        request.class
932                    ),
933                };
934            }
935        }
936        QosAdmission::Admit
937    }
938}
939
940impl BackgroundWorkHint {
941    fn tenant_budget_defer_reason(&self, estimated_operations: usize) -> Option<String> {
942        self.tenant_budget_remaining_operations
943            .filter(|remaining| *remaining < estimated_operations)
944            .map(|remaining| {
945                format!(
946                    "tenant budget remaining {remaining} below estimated operations {estimated_operations}"
947                )
948            })
949    }
950}
951
952impl QosAdmission {
953    pub const fn as_str(&self) -> &'static str {
954        match self {
955            Self::Admit => "admit",
956            Self::Defer { .. } => "defer",
957            Self::Reject { .. } => "reject",
958        }
959    }
960
961    pub fn code(&self) -> Option<QosAdmissionCode> {
962        match self {
963            QosAdmission::Admit => None,
964            QosAdmission::Defer { code, .. } | QosAdmission::Reject { code, .. } => Some(*code),
965        }
966    }
967
968    pub fn reason(&self) -> Option<&str> {
969        match self {
970            QosAdmission::Admit => None,
971            QosAdmission::Defer { reason, .. } | QosAdmission::Reject { reason, .. } => {
972                Some(reason)
973            }
974        }
975    }
976}
977
978fn admission_rank(admission: &QosAdmission) -> u8 {
979    match admission {
980        QosAdmission::Admit => 0,
981        QosAdmission::Defer { .. } => 1,
982        QosAdmission::Reject { .. } => 2,
983    }
984}
985
986fn scaled_staleness_score(age_millis: u64, limit_millis: u64) -> u64 {
987    if age_millis == 0 || limit_millis == 0 {
988        return 0;
989    }
990    if age_millis >= limit_millis {
991        return 1_000_000;
992    }
993    age_millis.saturating_mul(1_000_000) / limit_millis
994}
995
996impl LocalQosPermit {
997    pub fn request(&self) -> &WorkRequest {
998        &self.request
999    }
1000
1001    pub fn finish(mut self) {
1002        self.release(true);
1003    }
1004
1005    pub fn finish_with_outcome(mut self, success: bool) {
1006        self.release(success);
1007    }
1008
1009    fn release(&mut self, success: bool) {
1010        if self.released {
1011            return;
1012        }
1013        self.released = true;
1014        self.scheduler
1015            .release(&self.request, self.started_at, Instant::now(), success);
1016    }
1017}
1018
1019impl Drop for LocalQosPermit {
1020    fn drop(&mut self) {
1021        self.release(false);
1022    }
1023}
1024
1025impl LocalQosScheduler {
1026    pub fn new(policy: LocalQosPolicy) -> Self {
1027        Self {
1028            inner: Arc::new(LocalQosSchedulerInner {
1029                policy,
1030                state: Mutex::new(SchedulerState::default()),
1031                telemetry: RwLock::new(None),
1032            }),
1033        }
1034    }
1035
1036    /// Replace the sink. Idle batches are reclaimed first and report their
1037    /// completion to the previous sink, so every later batch admission and
1038    /// its units are observed by the new one.
1039    pub fn set_telemetry_sink(&self, telemetry: Option<Arc<dyn QosTelemetrySink>>) {
1040        self.inner.reclaim_idle_batches();
1041        *self
1042            .inner
1043            .telemetry
1044            .write()
1045            .unwrap_or_else(|poisoned| poisoned.into_inner()) = telemetry;
1046    }
1047
1048    pub fn policy(&self) -> &LocalQosPolicy {
1049        &self.inner.policy
1050    }
1051
1052    pub fn state(&self) -> LocalQosState {
1053        self.inner.state()
1054    }
1055
1056    pub fn admit(&self, request: &WorkRequest) -> QosAdmission {
1057        self.inner.policy.admit(&self.inner.state(), request)
1058    }
1059
1060    pub fn evaluate_background_work(&self, plan: &BackgroundWorkPlan) -> BackgroundWorkDecision {
1061        self.inner
1062            .policy
1063            .evaluate_background_work(&self.inner.state(), plan)
1064    }
1065
1066    pub fn rank_background_work(&self, plans: &[BackgroundWorkPlan]) -> Vec<RankedBackgroundWork> {
1067        self.inner
1068            .policy
1069            .rank_background_work(&self.inner.state(), plans)
1070    }
1071
1072    pub fn snapshot(&self) -> LocalQosSnapshot {
1073        self.inner.policy.snapshot(&self.inner.state())
1074    }
1075
1076    /// The sink currently attached to this scheduler.
1077    pub fn telemetry_sink(&self) -> Option<Arc<dyn QosTelemetrySink>> {
1078        self.inner
1079            .telemetry
1080            .read()
1081            .unwrap_or_else(|poisoned| poisoned.into_inner())
1082            .clone()
1083    }
1084
1085    pub fn try_start(
1086        &self,
1087        request: WorkRequest,
1088    ) -> std::result::Result<LocalQosPermit, QosAdmission> {
1089        self.try_start_with_state(request)
1090            .map_err(|(admission, _)| admission)
1091    }
1092
1093    /// Admit and charge `request`. A refusal also returns the charged state
1094    /// it was decided against, so callers can report its headroom.
1095    fn try_start_with_state(
1096        &self,
1097        request: WorkRequest,
1098    ) -> std::result::Result<LocalQosPermit, (QosAdmission, LocalQosState)> {
1099        let (admission, refused_state) = self.admit_and_charge(&request, None);
1100        self.record_admission(&request, &admission);
1101        match admission {
1102            QosAdmission::Admit => Ok(LocalQosPermit {
1103                scheduler: Arc::clone(&self.inner),
1104                request,
1105                started_at: Instant::now(),
1106                released: false,
1107            }),
1108            admission => Err((admission, refused_state)),
1109        }
1110    }
1111
1112    /// Admit a [`LocalQosBatchPermit`] at a caller-supplied timestamp. The
1113    /// returned batch is running; mark it idle between units.
1114    pub fn try_start_batch_at(
1115        &self,
1116        request: WorkRequest,
1117        started_at: Instant,
1118    ) -> std::result::Result<LocalQosBatchPermit, QosAdmission> {
1119        let slot = Arc::new(BatchSlot {
1120            state: AtomicU8::new(BATCH_ACTIVE),
1121            request,
1122            started_at,
1123        });
1124        let (admission, _) = self.admit_and_charge(&slot.request, Some(&slot));
1125        self.record_admission(&slot.request, &admission);
1126        match admission {
1127            QosAdmission::Admit => Ok(LocalQosBatchPermit {
1128                scheduler: Arc::clone(&self.inner),
1129                slot,
1130                finished: false,
1131            }),
1132            admission => Err(admission),
1133        }
1134    }
1135
1136    /// Admit under the policy and charge background work. Idle batches are
1137    /// reclaimed only when their charge would refuse this request. A refusal
1138    /// also returns the charged state it was decided against (default
1139    /// otherwise).
1140    fn admit_and_charge(
1141        &self,
1142        request: &WorkRequest,
1143        batch: Option<&Arc<BatchSlot>>,
1144    ) -> (QosAdmission, LocalQosState) {
1145        let (admission, reclaimed, refused_state) = {
1146            let mut state = self.inner.lock();
1147            let mut admission = self.inner.policy.admit(&state.charged, request);
1148            let mut reclaimed = Vec::new();
1149            if !matches!(admission, QosAdmission::Admit)
1150                && request.priority == WorkPriority::Background
1151                && !state.batches.is_empty()
1152            {
1153                reclaimed = state.reclaim_idle();
1154                if !reclaimed.is_empty() {
1155                    admission = self.inner.policy.admit(&state.charged, request);
1156                }
1157            }
1158            if matches!(admission, QosAdmission::Admit)
1159                && request.priority == WorkPriority::Background
1160            {
1161                state.charge(request);
1162                if let Some(batch) = batch {
1163                    state.batches.push(batch.clone());
1164                }
1165            }
1166            let refused_state = if matches!(admission, QosAdmission::Admit) {
1167                LocalQosState::default()
1168            } else {
1169                state.charged.clone()
1170            };
1171            (admission, reclaimed, refused_state)
1172        };
1173        if !reclaimed.is_empty() {
1174            let now = Instant::now();
1175            for slot in reclaimed {
1176                self.inner
1177                    .record_completion(&slot.request, slot.started_at, now, true);
1178            }
1179        }
1180        (admission, refused_state)
1181    }
1182
1183    fn record_admission(&self, request: &WorkRequest, admission: &QosAdmission) {
1184        let outcome = match admission {
1185            QosAdmission::Admit => QosTelemetryOutcome::Admitted,
1186            QosAdmission::Defer { .. } => QosTelemetryOutcome::Deferred,
1187            QosAdmission::Reject { .. } => QosTelemetryOutcome::Rejected,
1188        };
1189        self.inner.record_background_event(
1190            request,
1191            QosTelemetryPhase::Admission,
1192            outcome,
1193            admission.code(),
1194            0,
1195        );
1196    }
1197}
1198
1199impl LocalQosSchedulerInner {
1200    fn lock(&self) -> std::sync::MutexGuard<'_, SchedulerState> {
1201        self.state
1202            .lock()
1203            .unwrap_or_else(|poisoned| poisoned.into_inner())
1204    }
1205
1206    fn state(&self) -> LocalQosState {
1207        self.lock().view()
1208    }
1209
1210    fn reclaim_idle_batches(&self) {
1211        let reclaimed = self.lock().reclaim_idle();
1212        if !reclaimed.is_empty() {
1213            let now = Instant::now();
1214            for slot in reclaimed {
1215                self.record_completion(&slot.request, slot.started_at, now, true);
1216            }
1217        }
1218    }
1219
1220    fn release(
1221        &self,
1222        request: &WorkRequest,
1223        started_at: Instant,
1224        finished_at: Instant,
1225        success: bool,
1226    ) {
1227        if request.priority == WorkPriority::Background {
1228            SchedulerState::refund(&mut self.lock().charged, request);
1229        }
1230        self.record_completion(request, started_at, finished_at, success);
1231    }
1232
1233    fn record_completion(
1234        &self,
1235        request: &WorkRequest,
1236        started_at: Instant,
1237        finished_at: Instant,
1238        success: bool,
1239    ) {
1240        let elapsed_micros = finished_at
1241            .saturating_duration_since(started_at)
1242            .as_micros()
1243            .min(u128::from(u64::MAX)) as u64;
1244        self.record_background_event(
1245            request,
1246            QosTelemetryPhase::Completion,
1247            if success {
1248                QosTelemetryOutcome::Completed
1249            } else {
1250                QosTelemetryOutcome::Failed
1251            },
1252            None,
1253            elapsed_micros,
1254        );
1255    }
1256
1257    fn record_background_event(
1258        &self,
1259        request: &WorkRequest,
1260        phase: QosTelemetryPhase,
1261        outcome: QosTelemetryOutcome,
1262        admission_code: Option<QosAdmissionCode>,
1263        elapsed_micros: u64,
1264    ) {
1265        if request.priority != WorkPriority::Background {
1266            return;
1267        }
1268        let telemetry = self
1269            .telemetry
1270            .read()
1271            .unwrap_or_else(|poisoned| poisoned.into_inner())
1272            .clone();
1273        if let Some(telemetry) = telemetry {
1274            telemetry.record_qos(QosTelemetryEvent {
1275                phase,
1276                outcome,
1277                class: request.class,
1278                estimated_operations: request.estimated_operations,
1279                elapsed_micros,
1280                admission_code,
1281            });
1282        }
1283    }
1284}
1285
1286fn local_qos_class_snapshots(
1287    policy: &LocalQosPolicy,
1288    state: &LocalQosState,
1289) -> [LocalQosClassSnapshot; WORK_CLASS_COUNT] {
1290    WorkClass::ALL.map(|class| local_qos_class_snapshot(policy, state, class))
1291}
1292
1293fn local_qos_class_snapshot(
1294    policy: &LocalQosPolicy,
1295    state: &LocalQosState,
1296    class: WorkClass,
1297) -> LocalQosClassSnapshot {
1298    let running_background_operations =
1299        state.running_background_operations_by_class[class.as_index()];
1300    let max_background_operations = policy.max_background_operations_by_class[class.as_index()]
1301        .or(policy.max_background_operations);
1302    LocalQosClassSnapshot {
1303        class,
1304        running_background_operations,
1305        max_background_operations,
1306        remaining_background_operations: max_background_operations
1307            .map(|limit| limit.saturating_sub(running_background_operations)),
1308        over_budget: max_background_operations
1309            .is_some_and(|limit| running_background_operations > limit),
1310    }
1311}
1312
1313#[cfg(test)]
1314mod batch_tests;
1315
1316#[cfg(test)]
1317mod tests {
1318    use super::{
1319        BackgroundWorkHint, BackgroundWorkPlan, BackgroundWorkReasonCode, LocalQosPolicy,
1320        LocalQosScheduler, LocalQosState, QosAdmission, QosAdmissionCode, QosSnapshotBlockerCode,
1321        QosTelemetryEvent, QosTelemetryOutcome, QosTelemetryPhase, QosTelemetrySink, WorkClass,
1322        WorkPriority, WorkRequest,
1323    };
1324    use std::panic::{catch_unwind, AssertUnwindSafe};
1325    use std::sync::{Arc, Barrier, Mutex};
1326    use std::thread;
1327
1328    #[derive(Debug, Default)]
1329    struct RecordingQosTelemetry {
1330        events: Mutex<Vec<QosTelemetryEvent>>,
1331    }
1332
1333    impl QosTelemetrySink for RecordingQosTelemetry {
1334        fn record_qos(&self, event: QosTelemetryEvent) {
1335            self.events.lock().unwrap().push(event);
1336        }
1337    }
1338
1339    #[test]
1340    fn work_priorities_have_stable_string_encodings() {
1341        assert_eq!(WorkPriority::Foreground.as_str(), "foreground");
1342        assert_eq!(WorkPriority::Background.as_str(), "background");
1343        assert_eq!(
1344            "foreground".parse::<WorkPriority>(),
1345            Ok(WorkPriority::Foreground)
1346        );
1347        assert_eq!(
1348            "background".parse::<WorkPriority>(),
1349            Ok(WorkPriority::Background)
1350        );
1351        assert!("foreground_work".parse::<WorkPriority>().is_err());
1352    }
1353
1354    #[test]
1355    fn background_scheduler_records_admission_and_completion() {
1356        let telemetry = Arc::new(RecordingQosTelemetry::default());
1357        let scheduler = LocalQosScheduler::new(LocalQosPolicy::default());
1358        scheduler.set_telemetry_sink(Some(telemetry.clone()));
1359
1360        let permit = scheduler
1361            .try_start(WorkRequest::background(WorkClass::Projection, 3))
1362            .unwrap();
1363        permit.finish_with_outcome(false);
1364
1365        let events = telemetry.events.lock().unwrap();
1366        assert_eq!(events.len(), 2);
1367        assert_eq!(events[0].phase, QosTelemetryPhase::Admission);
1368        assert_eq!(events[0].outcome, QosTelemetryOutcome::Admitted);
1369        assert_eq!(events[0].class, WorkClass::Projection);
1370        assert_eq!(events[0].estimated_operations, 3);
1371        assert_eq!(events[1].phase, QosTelemetryPhase::Completion);
1372        assert_eq!(events[1].outcome, QosTelemetryOutcome::Failed);
1373        assert_eq!(events[1].admission_code, None);
1374    }
1375
1376    #[test]
1377    fn background_scheduler_records_bounded_defer_code() {
1378        let telemetry = Arc::new(RecordingQosTelemetry::default());
1379        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
1380            max_background_operations: Some(1),
1381            ..LocalQosPolicy::default()
1382        });
1383        scheduler.set_telemetry_sink(Some(telemetry.clone()));
1384
1385        let admission = scheduler
1386            .try_start(WorkRequest::background(WorkClass::Import, 2))
1387            .unwrap_err();
1388
1389        assert!(matches!(admission, QosAdmission::Defer { .. }));
1390        let events = telemetry.events.lock().unwrap();
1391        assert_eq!(events.len(), 1);
1392        assert_eq!(events[0].phase, QosTelemetryPhase::Admission);
1393        assert_eq!(events[0].outcome, QosTelemetryOutcome::Deferred);
1394        assert_eq!(
1395            events[0].admission_code,
1396            Some(QosAdmissionCode::PerWorkLimitExceeded)
1397        );
1398    }
1399
1400    #[test]
1401    fn foreground_scheduler_does_not_emit_background_metrics() {
1402        let telemetry = Arc::new(RecordingQosTelemetry::default());
1403        let scheduler = LocalQosScheduler::new(LocalQosPolicy::default());
1404        scheduler.set_telemetry_sink(Some(telemetry.clone()));
1405
1406        let permit = scheduler
1407            .try_start(WorkRequest::foreground(WorkClass::Query, 1))
1408            .unwrap();
1409        permit.finish();
1410
1411        assert!(telemetry.events.lock().unwrap().is_empty());
1412    }
1413
1414    #[test]
1415    fn work_class_snapshots_follow_the_exhaustive_index_order() {
1416        let state = LocalQosState {
1417            running_background_operations: (1..=super::WORK_CLASS_COUNT).sum(),
1418            running_background_operations_by_class: std::array::from_fn(|index| index + 1),
1419        };
1420        let policy = LocalQosPolicy {
1421            max_background_operations_by_class: std::array::from_fn(|index| Some(index + 3)),
1422            ..LocalQosPolicy::default()
1423        };
1424        let snapshot = policy.snapshot(&state);
1425        for (index, class) in WorkClass::ALL.into_iter().enumerate() {
1426            assert_eq!(class.as_index(), index);
1427            assert_eq!(class.as_str().parse::<WorkClass>(), Ok(class));
1428            let entry = snapshot.class_snapshots[index];
1429            assert_eq!(entry.class, class);
1430            assert_eq!(entry.running_background_operations, index + 1);
1431            assert_eq!(entry.max_background_operations, Some(index + 3));
1432            assert_eq!(entry.remaining_background_operations, Some(2));
1433            assert!(!entry.over_budget);
1434        }
1435    }
1436
1437    #[test]
1438    fn foreground_probe_and_admission_agree_under_background_pressure() {
1439        let state = LocalQosState {
1440            running_background_operations: usize::MAX,
1441            running_background_operations_by_class: [usize::MAX; super::WORK_CLASS_COUNT],
1442        };
1443        for background_enabled in [false, true] {
1444            let policy = LocalQosPolicy {
1445                background_enabled,
1446                max_background_operations: Some(0),
1447                max_total_background_operations: Some(0),
1448                max_background_operations_by_class: [Some(0); super::WORK_CLASS_COUNT],
1449            };
1450            assert_eq!(policy.foreground_admission(), QosAdmission::Admit);
1451            assert!(policy.snapshot(&state).foreground_admitted);
1452            for class in WorkClass::ALL {
1453                for estimate in [0, 1, usize::MAX] {
1454                    assert_eq!(
1455                        policy.admit(&state, &WorkRequest::foreground(class, estimate)),
1456                        policy.foreground_admission()
1457                    );
1458                }
1459            }
1460        }
1461    }
1462
1463    #[test]
1464    fn expected_score_matches_admission_scoring_at_tenant_budget_boundaries() {
1465        for remaining in [None, Some(0), Some(1), Some(8), Some(usize::MAX)] {
1466            for estimate in [0, 1, 7, 8, 9, usize::MAX] {
1467                for background_enabled in [false, true] {
1468                    for active_topic in [false, true] {
1469                        let hint = BackgroundWorkHint {
1470                            active_topic,
1471                            query_probability_per_million: u32::MAX,
1472                            recent_delta_operations: usize::MAX,
1473                            source_graph_commit_lag: u64::MAX,
1474                            staleness_millis: u64::MAX,
1475                            staleness_ttl_millis: Some(1),
1476                            freshness_slo_millis: Some(0),
1477                            tenant_budget_remaining_operations: remaining,
1478                        };
1479                        let policy = LocalQosPolicy {
1480                            background_enabled,
1481                            ..LocalQosPolicy::default()
1482                        };
1483                        let plan = BackgroundWorkPlan::background(
1484                            WorkClass::Projection,
1485                            estimate,
1486                            hint.clone(),
1487                        );
1488                        let decision =
1489                            policy.evaluate_background_work(&LocalQosState::default(), &plan);
1490                        assert_eq!(hint.expected_value_score(estimate), decision.score);
1491                        let tenant_exhausted = remaining.is_some_and(|budget| budget < estimate);
1492                        assert_eq!(decision.score == 0, tenant_exhausted);
1493                        assert_eq!(
1494                            decision
1495                                .reason_codes
1496                                .contains(&BackgroundWorkReasonCode::TenantBudgetBelowEstimate),
1497                            tenant_exhausted
1498                        );
1499                    }
1500                }
1501            }
1502        }
1503    }
1504
1505    #[test]
1506    fn work_classes_have_stable_string_encodings() {
1507        assert_eq!(WorkClass::Query.as_str(), "query");
1508        assert_eq!(WorkClass::Mutation.as_str(), "mutation");
1509        assert_eq!(WorkClass::Projection.as_str(), "projection");
1510        assert_eq!(WorkClass::Import.as_str(), "import");
1511        assert_eq!(WorkClass::Analytics.as_str(), "analytics");
1512        assert_eq!(WorkClass::Shadow.as_str(), "shadow");
1513        assert_eq!("query".parse::<WorkClass>(), Ok(WorkClass::Query));
1514        assert_eq!("mutation".parse::<WorkClass>(), Ok(WorkClass::Mutation));
1515        assert_eq!("projection".parse::<WorkClass>(), Ok(WorkClass::Projection));
1516        assert_eq!("import".parse::<WorkClass>(), Ok(WorkClass::Import));
1517        assert_eq!("analytics".parse::<WorkClass>(), Ok(WorkClass::Analytics));
1518        assert_eq!("shadow".parse::<WorkClass>(), Ok(WorkClass::Shadow));
1519        assert!("maintenance".parse::<WorkClass>().is_err());
1520    }
1521
1522    #[test]
1523    fn qos_admission_codes_have_stable_string_encodings() {
1524        assert_eq!(
1525            QosAdmissionCode::BackgroundDisabled.as_str(),
1526            "background_disabled"
1527        );
1528        assert_eq!(
1529            QosAdmissionCode::PerWorkLimitExceeded.as_str(),
1530            "per_work_limit_exceeded"
1531        );
1532        assert_eq!(
1533            QosAdmissionCode::TotalBackgroundLimitExceeded.as_str(),
1534            "total_background_limit_exceeded"
1535        );
1536        assert_eq!(
1537            QosAdmissionCode::ClassBackgroundLimitExceeded.as_str(),
1538            "class_background_limit_exceeded"
1539        );
1540        assert_eq!(
1541            QosAdmissionCode::TenantBudgetExceeded.as_str(),
1542            "tenant_budget_exceeded"
1543        );
1544        assert_eq!(
1545            "background_disabled".parse::<QosAdmissionCode>(),
1546            Ok(QosAdmissionCode::BackgroundDisabled)
1547        );
1548        assert_eq!(
1549            "per_work_limit_exceeded".parse::<QosAdmissionCode>(),
1550            Ok(QosAdmissionCode::PerWorkLimitExceeded)
1551        );
1552        assert_eq!(
1553            "total_background_limit_exceeded".parse::<QosAdmissionCode>(),
1554            Ok(QosAdmissionCode::TotalBackgroundLimitExceeded)
1555        );
1556        assert_eq!(
1557            "class_background_limit_exceeded".parse::<QosAdmissionCode>(),
1558            Ok(QosAdmissionCode::ClassBackgroundLimitExceeded)
1559        );
1560        assert_eq!(
1561            "tenant_budget_exceeded".parse::<QosAdmissionCode>(),
1562            Ok(QosAdmissionCode::TenantBudgetExceeded)
1563        );
1564        assert!("background_paused".parse::<QosAdmissionCode>().is_err());
1565    }
1566
1567    #[test]
1568    fn qos_admissions_have_stable_string_encodings() {
1569        assert_eq!(QosAdmission::Admit.as_str(), "admit");
1570        assert_eq!(
1571            QosAdmission::Defer {
1572                code: QosAdmissionCode::BackgroundDisabled,
1573                reason: "disabled".to_string(),
1574            }
1575            .as_str(),
1576            "defer"
1577        );
1578        assert_eq!(
1579            QosAdmission::Reject {
1580                code: QosAdmissionCode::TenantBudgetExceeded,
1581                reason: "budget".to_string(),
1582            }
1583            .as_str(),
1584            "reject"
1585        );
1586    }
1587
1588    #[test]
1589    fn background_work_reason_codes_have_stable_string_encodings() {
1590        let cases = [
1591            (
1592                BackgroundWorkReasonCode::ForegroundNotRanked,
1593                "foreground_not_ranked",
1594            ),
1595            (
1596                BackgroundWorkReasonCode::TenantBudgetBelowEstimate,
1597                "tenant_budget_below_estimate",
1598            ),
1599            (BackgroundWorkReasonCode::ActiveTopic, "active_topic"),
1600            (
1601                BackgroundWorkReasonCode::QueryProbability,
1602                "query_probability",
1603            ),
1604            (
1605                BackgroundWorkReasonCode::RecentDeltaOperations,
1606                "recent_delta_operations",
1607            ),
1608            (
1609                BackgroundWorkReasonCode::SourceGraphCommitLag,
1610                "source_graph_commit_lag",
1611            ),
1612            (BackgroundWorkReasonCode::StalenessTtl, "staleness_ttl"),
1613            (BackgroundWorkReasonCode::FreshnessSlo, "freshness_slo"),
1614            (
1615                BackgroundWorkReasonCode::AdmissionDeferred,
1616                "admission_deferred",
1617            ),
1618            (
1619                BackgroundWorkReasonCode::AdmissionRejected,
1620                "admission_rejected",
1621            ),
1622        ];
1623
1624        for (code, name) in cases {
1625            assert_eq!(code.as_str(), name);
1626            assert_eq!(name.parse::<BackgroundWorkReasonCode>(), Ok(code));
1627        }
1628        assert!("cron_reason".parse::<BackgroundWorkReasonCode>().is_err());
1629    }
1630
1631    #[test]
1632    fn admits_foreground_work_without_budget_gate() {
1633        let policy = LocalQosPolicy::default();
1634        let request = WorkRequest::foreground(WorkClass::Query, usize::MAX);
1635
1636        assert_eq!(
1637            policy.admit(&LocalQosState::default(), &request),
1638            QosAdmission::Admit
1639        );
1640    }
1641
1642    #[test]
1643    fn defers_background_when_disabled() {
1644        let policy = LocalQosPolicy {
1645            background_enabled: false,
1646            ..LocalQosPolicy::default()
1647        };
1648        let request = WorkRequest::background(WorkClass::Projection, 1);
1649
1650        let admission = policy.admit(&LocalQosState::default(), &request);
1651
1652        assert_eq!(admission.code(), Some(QosAdmissionCode::BackgroundDisabled));
1653        assert_eq!(
1654            admission.code().map(QosAdmissionCode::as_str),
1655            Some("background_disabled")
1656        );
1657        assert_eq!(
1658            "background_disabled".parse::<QosAdmissionCode>(),
1659            admission.code().ok_or("missing admission code")
1660        );
1661        assert!(matches!(
1662            admission,
1663            QosAdmission::Defer { reason, .. } if reason.contains("disabled")
1664        ));
1665    }
1666
1667    #[test]
1668    fn foreground_work_evaluation_reports_not_ranked_code() {
1669        let decision = LocalQosPolicy::default().evaluate_background_work(
1670            &LocalQosState::default(),
1671            &BackgroundWorkPlan {
1672                request: WorkRequest::foreground(WorkClass::Query, 1),
1673                hint: BackgroundWorkHint::default(),
1674            },
1675        );
1676
1677        assert_eq!(decision.admission, QosAdmission::Admit);
1678        assert_eq!(decision.score, 0);
1679        assert_eq!(
1680            decision.reason_codes,
1681            vec![BackgroundWorkReasonCode::ForegroundNotRanked]
1682        );
1683        assert_eq!(
1684            decision.reasons,
1685            vec!["foreground work is not background-ranked".to_string()]
1686        );
1687    }
1688
1689    #[test]
1690    fn defers_background_over_per_work_budget() {
1691        let policy = LocalQosPolicy {
1692            max_background_operations: Some(4),
1693            ..LocalQosPolicy::default()
1694        };
1695        let request = WorkRequest::background(WorkClass::Projection, 5);
1696
1697        let admission = policy.admit(&LocalQosState::default(), &request);
1698
1699        assert_eq!(
1700            admission.code(),
1701            Some(QosAdmissionCode::PerWorkLimitExceeded)
1702        );
1703        assert_eq!(
1704            admission.code().map(QosAdmissionCode::as_str),
1705            Some("per_work_limit_exceeded")
1706        );
1707        assert!(matches!(
1708            admission,
1709            QosAdmission::Defer { reason, .. } if reason.contains("per-work limit")
1710        ));
1711    }
1712
1713    #[test]
1714    fn defers_background_when_running_budget_is_exhausted() {
1715        let policy = LocalQosPolicy {
1716            max_background_operations: Some(10),
1717            max_total_background_operations: Some(12),
1718            ..LocalQosPolicy::default()
1719        };
1720        let state = LocalQosState {
1721            running_background_operations: 8,
1722            ..LocalQosState::default()
1723        };
1724        let request = WorkRequest::background(WorkClass::Analytics, 5);
1725
1726        let admission = policy.admit(&state, &request);
1727
1728        assert_eq!(
1729            admission.code(),
1730            Some(QosAdmissionCode::TotalBackgroundLimitExceeded)
1731        );
1732        assert_eq!(
1733            admission.code().map(QosAdmissionCode::as_str),
1734            Some("total_background_limit_exceeded")
1735        );
1736        assert!(matches!(
1737            admission,
1738            QosAdmission::Defer { reason, .. } if reason.contains("above limit 12")
1739        ));
1740    }
1741
1742    #[test]
1743    fn background_work_hint_scores_expected_value_signals() {
1744        let low = BackgroundWorkHint {
1745            query_probability_per_million: 10_000,
1746            recent_delta_operations: 2,
1747            staleness_millis: 100,
1748            staleness_ttl_millis: Some(1_000),
1749            ..BackgroundWorkHint::default()
1750        };
1751        let high = BackgroundWorkHint {
1752            active_topic: true,
1753            query_probability_per_million: 800_000,
1754            recent_delta_operations: 20,
1755            source_graph_commit_lag: 3,
1756            staleness_millis: 6_000,
1757            staleness_ttl_millis: Some(1_000),
1758            freshness_slo_millis: Some(5_000),
1759            ..BackgroundWorkHint::default()
1760        };
1761
1762        assert!(high.expected_value_score(1) > low.expected_value_score(1));
1763        let decision = LocalQosPolicy::default().evaluate_background_work(
1764            &LocalQosState::default(),
1765            &BackgroundWorkPlan::background(WorkClass::Projection, 1, high),
1766        );
1767
1768        assert_eq!(decision.admission, QosAdmission::Admit);
1769        assert!(decision.score > 0);
1770        assert!(decision
1771            .reason_codes
1772            .contains(&BackgroundWorkReasonCode::ActiveTopic));
1773        assert!(decision
1774            .reason_codes
1775            .contains(&BackgroundWorkReasonCode::QueryProbability));
1776        assert!(decision
1777            .reason_codes
1778            .contains(&BackgroundWorkReasonCode::RecentDeltaOperations));
1779        assert!(decision
1780            .reason_codes
1781            .contains(&BackgroundWorkReasonCode::SourceGraphCommitLag));
1782        assert!(decision
1783            .reason_codes
1784            .contains(&BackgroundWorkReasonCode::StalenessTtl));
1785        assert!(decision
1786            .reason_codes
1787            .contains(&BackgroundWorkReasonCode::FreshnessSlo));
1788        assert!(decision
1789            .reasons
1790            .iter()
1791            .any(|reason| reason.contains("active topic")));
1792        assert!(decision
1793            .reasons
1794            .iter()
1795            .any(|reason| reason.contains("source graph commit lag 3")));
1796        assert!(decision
1797            .reasons
1798            .iter()
1799            .any(|reason| reason.contains("staleness ttl reached")));
1800        assert!(decision
1801            .reasons
1802            .iter()
1803            .any(|reason| reason.contains("freshness slo missed")));
1804    }
1805
1806    #[test]
1807    fn background_work_evaluation_keeps_value_when_budget_defers() {
1808        let policy = LocalQosPolicy {
1809            max_total_background_operations: Some(4),
1810            ..LocalQosPolicy::default()
1811        };
1812        let state = LocalQosState {
1813            running_background_operations: 3,
1814            ..LocalQosState::default()
1815        };
1816        let decision = policy.evaluate_background_work(
1817            &state,
1818            &BackgroundWorkPlan::background(
1819                WorkClass::Analytics,
1820                2,
1821                BackgroundWorkHint {
1822                    active_topic: true,
1823                    query_probability_per_million: 500_000,
1824                    ..BackgroundWorkHint::default()
1825                },
1826            ),
1827        );
1828
1829        assert!(matches!(
1830            decision.admission,
1831            QosAdmission::Defer { reason, .. } if reason.contains("above limit 4")
1832        ));
1833        assert!(decision.score > 0);
1834        assert!(decision
1835            .reason_codes
1836            .contains(&BackgroundWorkReasonCode::AdmissionDeferred));
1837        assert!(decision
1838            .reasons
1839            .iter()
1840            .any(|reason| reason.contains("admission deferred")));
1841    }
1842
1843    #[test]
1844    fn tenant_budget_defers_background_work_without_rejecting_it() {
1845        let decision = LocalQosPolicy::default().evaluate_background_work(
1846            &LocalQosState::default(),
1847            &BackgroundWorkPlan::background(
1848                WorkClass::Import,
1849                8,
1850                BackgroundWorkHint {
1851                    active_topic: true,
1852                    query_probability_per_million: 1_000_000,
1853                    tenant_budget_remaining_operations: Some(4),
1854                    ..BackgroundWorkHint::default()
1855                },
1856            ),
1857        );
1858
1859        assert_eq!(
1860            decision.admission.code(),
1861            Some(QosAdmissionCode::TenantBudgetExceeded)
1862        );
1863        assert_eq!(
1864            decision.admission.code().map(QosAdmissionCode::as_str),
1865            Some("tenant_budget_exceeded")
1866        );
1867        assert_eq!(
1868            decision.admission.reason(),
1869            Some("tenant budget remaining 4 below estimated operations 8")
1870        );
1871        assert!(matches!(
1872            decision.admission,
1873            QosAdmission::Defer { ref reason, .. } if reason.contains("tenant budget remaining 4")
1874        ));
1875        assert_eq!(decision.score, 0);
1876        assert!(decision
1877            .reason_codes
1878            .contains(&BackgroundWorkReasonCode::TenantBudgetBelowEstimate));
1879        assert!(decision
1880            .reason_codes
1881            .contains(&BackgroundWorkReasonCode::AdmissionDeferred));
1882        assert!(decision
1883            .reasons
1884            .iter()
1885            .any(|reason| reason.contains("tenant budget remaining 4")));
1886    }
1887
1888    #[test]
1889    fn scheduler_evaluates_background_work_against_running_state() {
1890        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
1891            max_total_background_operations: Some(4),
1892            ..LocalQosPolicy::default()
1893        });
1894        let running = scheduler
1895            .try_start(WorkRequest::background(WorkClass::Projection, 3))
1896            .unwrap();
1897
1898        let decision = scheduler.evaluate_background_work(&BackgroundWorkPlan::background(
1899            WorkClass::Import,
1900            2,
1901            BackgroundWorkHint {
1902                active_topic: true,
1903                ..BackgroundWorkHint::default()
1904            },
1905        ));
1906
1907        assert!(matches!(
1908            decision.admission,
1909            QosAdmission::Defer { reason, .. } if reason.contains("above limit 4")
1910        ));
1911        assert!(decision.score > 0);
1912
1913        running.finish();
1914    }
1915
1916    #[test]
1917    fn background_work_ranking_prefers_admitted_high_value_plans_stably() {
1918        let policy = LocalQosPolicy {
1919            max_total_background_operations: Some(3),
1920            ..LocalQosPolicy::default()
1921        };
1922        let state = LocalQosState {
1923            running_background_operations: 1,
1924            ..LocalQosState::default()
1925        };
1926        let plans = vec![
1927            BackgroundWorkPlan::background(
1928                WorkClass::Projection,
1929                3,
1930                BackgroundWorkHint {
1931                    active_topic: true,
1932                    query_probability_per_million: 1_000_000,
1933                    ..BackgroundWorkHint::default()
1934                },
1935            ),
1936            BackgroundWorkPlan::background(
1937                WorkClass::Import,
1938                1,
1939                BackgroundWorkHint {
1940                    query_probability_per_million: 10,
1941                    ..BackgroundWorkHint::default()
1942                },
1943            ),
1944            BackgroundWorkPlan::background(
1945                WorkClass::Analytics,
1946                1,
1947                BackgroundWorkHint {
1948                    query_probability_per_million: 100_000,
1949                    ..BackgroundWorkHint::default()
1950                },
1951            ),
1952            BackgroundWorkPlan::background(
1953                WorkClass::Shadow,
1954                1,
1955                BackgroundWorkHint {
1956                    query_probability_per_million: 100_000,
1957                    ..BackgroundWorkHint::default()
1958                },
1959            ),
1960        ];
1961
1962        let ranked = policy.rank_background_work(&state, &plans);
1963
1964        assert_eq!(
1965            ranked.iter().map(|entry| entry.index).collect::<Vec<_>>(),
1966            vec![2, 3, 1, 0]
1967        );
1968        assert!(matches!(ranked[0].decision.admission, QosAdmission::Admit));
1969        assert!(matches!(ranked[1].decision.admission, QosAdmission::Admit));
1970        assert!(matches!(ranked[2].decision.admission, QosAdmission::Admit));
1971        assert!(matches!(
1972            ranked[3].decision.admission,
1973            QosAdmission::Defer { .. }
1974        ));
1975        assert!(ranked[0].decision.score >= ranked[1].decision.score);
1976    }
1977
1978    #[test]
1979    fn scheduler_ranks_background_work_against_current_state() {
1980        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
1981            max_total_background_operations: Some(2),
1982            ..LocalQosPolicy::default()
1983        });
1984        let running = scheduler
1985            .try_start(WorkRequest::background(WorkClass::Projection, 1))
1986            .unwrap();
1987        let plans = vec![
1988            BackgroundWorkPlan::background(
1989                WorkClass::Import,
1990                2,
1991                BackgroundWorkHint {
1992                    active_topic: true,
1993                    ..BackgroundWorkHint::default()
1994                },
1995            ),
1996            BackgroundWorkPlan::background(
1997                WorkClass::Import,
1998                1,
1999                BackgroundWorkHint {
2000                    query_probability_per_million: 1,
2001                    ..BackgroundWorkHint::default()
2002                },
2003            ),
2004        ];
2005
2006        let ranked = scheduler.rank_background_work(&plans);
2007
2008        assert_eq!(ranked[0].index, 1);
2009        assert_eq!(ranked[1].index, 0);
2010        assert!(matches!(ranked[0].decision.admission, QosAdmission::Admit));
2011        assert!(matches!(
2012            ranked[1].decision.admission,
2013            QosAdmission::Defer { .. }
2014        ));
2015
2016        running.finish();
2017    }
2018
2019    #[test]
2020    fn scheduler_tracks_background_running_operations() {
2021        let policy = LocalQosPolicy {
2022            max_background_operations: Some(10),
2023            max_total_background_operations: Some(12),
2024            ..LocalQosPolicy::default()
2025        };
2026        let scheduler = LocalQosScheduler::new(policy);
2027
2028        let first = scheduler
2029            .try_start(WorkRequest::background(WorkClass::Projection, 8))
2030            .unwrap();
2031        assert_eq!(scheduler.state().running_background_operations, 8);
2032
2033        let second = scheduler
2034            .try_start(WorkRequest::background(WorkClass::Analytics, 5))
2035            .unwrap_err();
2036        assert!(matches!(
2037            second,
2038            QosAdmission::Defer { reason, .. } if reason.contains("above limit 12")
2039        ));
2040        assert_eq!(scheduler.state().running_background_operations, 8);
2041
2042        first.finish();
2043        assert_eq!(scheduler.state().running_background_operations, 0);
2044
2045        let second = scheduler
2046            .try_start(WorkRequest::background(WorkClass::Analytics, 5))
2047            .unwrap();
2048        assert_eq!(scheduler.state().running_background_operations, 5);
2049        second.finish();
2050        assert_eq!(scheduler.state().running_background_operations, 0);
2051    }
2052
2053    #[test]
2054    fn scheduler_clones_share_one_background_budget() {
2055        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
2056            max_total_background_operations: Some(4),
2057            ..LocalQosPolicy::default()
2058        });
2059        let shared = scheduler.clone();
2060        let permit = scheduler
2061            .try_start(WorkRequest::background(WorkClass::Projection, 3))
2062            .unwrap();
2063
2064        let admission = shared
2065            .try_start(WorkRequest::background(WorkClass::Analytics, 2))
2066            .unwrap_err();
2067        assert_eq!(
2068            admission.code(),
2069            Some(QosAdmissionCode::TotalBackgroundLimitExceeded)
2070        );
2071
2072        drop(permit);
2073        assert_eq!(shared.state().running_background_operations, 0);
2074        shared
2075            .try_start(WorkRequest::background(WorkClass::Analytics, 2))
2076            .unwrap()
2077            .finish();
2078    }
2079
2080    #[test]
2081    fn concurrent_scheduler_clones_never_over_admit_shared_budget() {
2082        const WORKER_COUNT: usize = 8;
2083        const BACKGROUND_LIMIT: usize = 4;
2084
2085        let scheduler = Arc::new(LocalQosScheduler::new(LocalQosPolicy {
2086            max_total_background_operations: Some(BACKGROUND_LIMIT),
2087            ..LocalQosPolicy::default()
2088        }));
2089        let start = Arc::new(Barrier::new(WORKER_COUNT + 1));
2090        let settled = Arc::new(Barrier::new(WORKER_COUNT + 1));
2091        let release = Arc::new(Barrier::new(WORKER_COUNT + 1));
2092
2093        let workers = (0..WORKER_COUNT)
2094            .map(|_| {
2095                let scheduler = Arc::clone(&scheduler);
2096                let start = Arc::clone(&start);
2097                let settled = Arc::clone(&settled);
2098                let release = Arc::clone(&release);
2099                thread::spawn(move || {
2100                    start.wait();
2101                    let permit = scheduler
2102                        .try_start(WorkRequest::background(WorkClass::Projection, 1))
2103                        .ok();
2104                    settled.wait();
2105                    let admitted = permit.is_some();
2106                    release.wait();
2107                    drop(permit);
2108                    admitted
2109                })
2110            })
2111            .collect::<Vec<_>>();
2112
2113        start.wait();
2114        settled.wait();
2115        assert_eq!(
2116            scheduler.state().running_background_operations,
2117            BACKGROUND_LIMIT
2118        );
2119        release.wait();
2120        assert_eq!(
2121            workers
2122                .into_iter()
2123                .map(|worker| worker.join().unwrap())
2124                .filter(|admitted| *admitted)
2125                .count(),
2126            BACKGROUND_LIMIT
2127        );
2128        assert_eq!(scheduler.state().running_background_operations, 0);
2129    }
2130
2131    #[test]
2132    fn permit_drop_releases_background_budget_after_error_and_panic() {
2133        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
2134            max_total_background_operations: Some(3),
2135            ..LocalQosPolicy::default()
2136        });
2137        let fail_after_admission = || -> std::result::Result<(), &'static str> {
2138            let _permit = scheduler
2139                .try_start(WorkRequest::background(WorkClass::Projection, 3))
2140                .unwrap();
2141            Err("operation failed")
2142        };
2143
2144        assert_eq!(fail_after_admission(), Err("operation failed"));
2145        assert_eq!(scheduler.state().running_background_operations, 0);
2146
2147        let panic = catch_unwind(AssertUnwindSafe(|| {
2148            let _permit = scheduler
2149                .try_start(WorkRequest::background(WorkClass::Projection, 3))
2150                .unwrap();
2151            panic!("operation panicked");
2152        }));
2153        assert!(panic.is_err());
2154        assert_eq!(scheduler.state().running_background_operations, 0);
2155        scheduler
2156            .try_start(WorkRequest::background(WorkClass::Projection, 3))
2157            .unwrap()
2158            .finish();
2159    }
2160
2161    #[test]
2162    fn scheduler_does_not_charge_foreground_work() {
2163        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
2164            max_total_background_operations: Some(1),
2165            ..LocalQosPolicy::default()
2166        });
2167
2168        let permit = scheduler
2169            .try_start(WorkRequest::foreground(WorkClass::Query, usize::MAX))
2170            .unwrap();
2171        assert_eq!(scheduler.state().running_background_operations, 0);
2172
2173        permit.finish();
2174        assert_eq!(scheduler.state().running_background_operations, 0);
2175    }
2176
2177    #[test]
2178    fn scheduler_tracks_background_running_operations_by_class() {
2179        let mut class_limits = [None; super::WORK_CLASS_COUNT];
2180        class_limits[WorkClass::Projection.as_index()] = Some(4);
2181        class_limits[WorkClass::Analytics.as_index()] = Some(10);
2182        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
2183            max_background_operations: Some(10),
2184            max_total_background_operations: Some(20),
2185            max_background_operations_by_class: class_limits,
2186            ..LocalQosPolicy::default()
2187        });
2188
2189        let projection = scheduler
2190            .try_start(WorkRequest::background(WorkClass::Projection, 3))
2191            .unwrap();
2192        assert_eq!(
2193            scheduler.state().running_background_operations_by_class
2194                [WorkClass::Projection.as_index()],
2195            3
2196        );
2197
2198        let same_class = scheduler
2199            .try_start(WorkRequest::background(WorkClass::Projection, 2))
2200            .unwrap_err();
2201        assert_eq!(
2202            same_class.code(),
2203            Some(QosAdmissionCode::ClassBackgroundLimitExceeded)
2204        );
2205        assert_eq!(
2206            same_class.code().map(QosAdmissionCode::as_str),
2207            Some("class_background_limit_exceeded")
2208        );
2209        assert!(matches!(
2210            same_class,
2211            QosAdmission::Defer { reason, .. } if reason.contains("class limit 4")
2212        ));
2213
2214        let analytics = scheduler
2215            .try_start(WorkRequest::background(WorkClass::Analytics, 2))
2216            .unwrap();
2217        assert_eq!(scheduler.state().running_background_operations, 5);
2218        assert_eq!(
2219            scheduler.state().running_background_operations_by_class
2220                [WorkClass::Analytics.as_index()],
2221            2
2222        );
2223
2224        projection.finish();
2225        assert_eq!(
2226            scheduler.state().running_background_operations_by_class
2227                [WorkClass::Projection.as_index()],
2228            0
2229        );
2230        assert_eq!(scheduler.state().running_background_operations, 2);
2231
2232        analytics.finish();
2233        assert_eq!(scheduler.state().running_background_operations, 0);
2234    }
2235
2236    #[test]
2237    fn class_budget_does_not_gate_foreground_work() {
2238        let mut class_limits = [None; super::WORK_CLASS_COUNT];
2239        class_limits[WorkClass::Projection.as_index()] = Some(0);
2240        let policy = LocalQosPolicy {
2241            max_background_operations_by_class: class_limits,
2242            ..LocalQosPolicy::default()
2243        };
2244        let request = WorkRequest::foreground(WorkClass::Projection, usize::MAX);
2245
2246        assert_eq!(
2247            policy.admit(&LocalQosState::default(), &request),
2248            QosAdmission::Admit
2249        );
2250    }
2251
2252    #[test]
2253    fn qos_snapshot_reports_foreground_first_bounded_background_state() {
2254        let mut class_limits = [None; super::WORK_CLASS_COUNT];
2255        class_limits[WorkClass::Projection.as_index()] = Some(4);
2256        let scheduler = LocalQosScheduler::new(LocalQosPolicy {
2257            max_background_operations: Some(8),
2258            max_total_background_operations: Some(12),
2259            max_background_operations_by_class: class_limits,
2260            ..LocalQosPolicy::default()
2261        });
2262        let permit = scheduler
2263            .try_start(WorkRequest::background(WorkClass::Projection, 3))
2264            .unwrap();
2265
2266        let snapshot = scheduler.snapshot();
2267
2268        assert!(snapshot.ready);
2269        assert!(snapshot.foreground_admitted);
2270        assert!(snapshot.background_enabled);
2271        assert!(snapshot.background_bounded);
2272        assert_eq!(snapshot.running_background_operations, 3);
2273        assert_eq!(snapshot.remaining_total_background_operations, Some(9));
2274        assert!(!snapshot.total_background_over_budget);
2275        assert!(snapshot.blocker_codes.is_empty());
2276        let projection = snapshot.class_snapshots[WorkClass::Projection.as_index()];
2277        assert_eq!(projection.class, WorkClass::Projection);
2278        assert_eq!(projection.running_background_operations, 3);
2279        assert_eq!(projection.max_background_operations, Some(4));
2280        assert_eq!(projection.remaining_background_operations, Some(1));
2281        assert!(!projection.over_budget);
2282
2283        permit.finish();
2284    }
2285
2286    #[test]
2287    fn qos_snapshot_fails_closed_for_unbounded_or_over_budget_background() {
2288        let unbounded = LocalQosPolicy {
2289            max_background_operations: None,
2290            max_total_background_operations: None,
2291            max_background_operations_by_class: [None; super::WORK_CLASS_COUNT],
2292            background_enabled: true,
2293        }
2294        .snapshot(&LocalQosState::default());
2295        assert!(!unbounded.ready);
2296        assert_eq!(
2297            unbounded.blocker_codes,
2298            vec![QosSnapshotBlockerCode::BackgroundUnbounded]
2299        );
2300        assert_eq!(unbounded.blocker_codes[0].as_str(), "background_unbounded");
2301
2302        let mut class_limits = [None; super::WORK_CLASS_COUNT];
2303        class_limits[WorkClass::Projection.as_index()] = Some(2);
2304        let over_budget = LocalQosPolicy {
2305            max_background_operations: Some(8),
2306            max_total_background_operations: Some(4),
2307            max_background_operations_by_class: class_limits,
2308            background_enabled: true,
2309        }
2310        .snapshot(&LocalQosState {
2311            running_background_operations: 5,
2312            running_background_operations_by_class: [0, 0, 3, 0, 0, 0],
2313        });
2314
2315        assert!(!over_budget.ready);
2316        assert!(over_budget.total_background_over_budget);
2317        assert!(over_budget.class_snapshots[WorkClass::Projection.as_index()].over_budget);
2318        assert_eq!(
2319            over_budget.blocker_codes,
2320            vec![
2321                QosSnapshotBlockerCode::TotalBackgroundOverBudget,
2322                QosSnapshotBlockerCode::ClassBackgroundOverBudget
2323            ]
2324        );
2325    }
2326}
2327
2328#[cfg(all(test, feature = "loom-tests"))]
2329mod loom_tests {
2330    use super::{
2331        LocalQosPolicy, LocalQosScheduler, QosAdmissionCode, WorkClass, WorkRequest,
2332        WORK_CLASS_COUNT,
2333    };
2334    use loom::sync::Arc;
2335    use loom::thread;
2336
2337    #[test]
2338    fn scheduler_preserves_background_budget_under_modeled_concurrent_start_finish() {
2339        loom::model(|| {
2340            let mut class_limits = [None; WORK_CLASS_COUNT];
2341            class_limits[WorkClass::Projection.as_index()] = Some(4);
2342            let scheduler = Arc::new(LocalQosScheduler::new(LocalQosPolicy {
2343                max_background_operations: Some(4),
2344                max_total_background_operations: Some(4),
2345                max_background_operations_by_class: class_limits,
2346                background_enabled: true,
2347            }));
2348
2349            let first = spawn_projection_worker(Arc::clone(&scheduler));
2350            let second = spawn_projection_worker(Arc::clone(&scheduler));
2351
2352            let first_admitted = first.join().unwrap();
2353            let second_admitted = second.join().unwrap();
2354
2355            assert!(first_admitted || second_admitted);
2356            assert!(scheduler.state().running_background_operations <= 4);
2357            assert_eq!(scheduler.state().running_background_operations, 0);
2358            assert_eq!(
2359                scheduler.state().running_background_operations_by_class
2360                    [WorkClass::Projection.as_index()],
2361                0
2362            );
2363        });
2364    }
2365
2366    fn spawn_projection_worker(scheduler: Arc<LocalQosScheduler>) -> thread::JoinHandle<bool> {
2367        thread::spawn(move || {
2368            let admission = scheduler.try_start(WorkRequest::background(WorkClass::Projection, 3));
2369            assert!(scheduler.state().running_background_operations <= 4);
2370            assert!(
2371                scheduler.state().running_background_operations_by_class
2372                    [WorkClass::Projection.as_index()]
2373                    <= 4
2374            );
2375
2376            thread::yield_now();
2377
2378            match admission {
2379                Ok(permit) => {
2380                    assert!(scheduler.state().running_background_operations <= 4);
2381                    permit.finish();
2382                    assert!(scheduler.state().running_background_operations <= 4);
2383                    true
2384                }
2385                Err(admission) => {
2386                    assert!(matches!(
2387                        admission.code(),
2388                        Some(
2389                            QosAdmissionCode::TotalBackgroundLimitExceeded
2390                                | QosAdmissionCode::ClassBackgroundLimitExceeded
2391                        )
2392                    ));
2393                    false
2394                }
2395            }
2396        })
2397    }
2398}