Skip to main content

micromegas/servers/
query_admission.rs

1//! Fair per-identity admission scheduler for FlightSQL queries.
2//!
3//! The scheduler never rejects: every identity gets its own FIFO queue, a per-process budget caps
4//! the cost in flight, and each time capacity frees up the next query comes from the identity
5//! with the least cost in flight. It is generic over cost and identity and knows nothing about
6//! DataFusion.
7
8use anyhow::{Result, bail};
9use micromegas_tracing::prelude::*;
10use std::collections::{HashMap, VecDeque};
11use std::sync::{Arc, Mutex};
12use tokio::sync::oneshot;
13
14const MIB: u64 = 1 << 20;
15const GIB: f64 = (1u64 << 30) as f64;
16
17pub const ADMISSION_BUDGET_ENV: &str = "MICROMEGAS_ADMISSION_BUDGET_GB";
18pub const ADMISSION_MIN_COST_ENV: &str = "MICROMEGAS_ADMISSION_MIN_COST_MB";
19pub const ADMISSION_MAX_PER_IDENTITY_ENV: &str = "MICROMEGAS_ADMISSION_MAX_PER_IDENTITY_GB";
20pub const ADMISSION_OPAQUE_LEAF_COST_ENV: &str = "MICROMEGAS_ADMISSION_OPAQUE_LEAF_COST_MB";
21
22const DEFAULT_MIN_COST_MB: u64 = 8;
23const DEFAULT_OPAQUE_LEAF_COST_MB: u64 = 64;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct AdmissionConfig {
27    /// Per-process cost units allowed in flight.
28    pub budget: u64,
29    /// Floor per query, so 0-byte queries still occupy a slot.
30    pub min_cost: u64,
31    /// The most one identity may hold in flight (<= budget).
32    pub identity_cap: u64,
33}
34
35impl AdmissionConfig {
36    /// Fails on combinations that would deadlock or panic: `clamp(estimate, min_cost,
37    /// identity_cap)` panics when `min_cost > identity_cap`.
38    pub fn validate(&self) -> Result<()> {
39        if self.budget == 0 {
40            bail!("admission budget must be greater than zero");
41        }
42        if self.identity_cap > self.budget {
43            bail!(
44                "admission per-identity maximum ({}) exceeds the budget ({})",
45                self.identity_cap,
46                self.budget
47            );
48        }
49        if self.min_cost > self.identity_cap {
50            bail!(
51                "admission minimum cost ({}) exceeds the per-identity maximum ({})",
52                self.min_cost,
53                self.identity_cap
54            );
55        }
56        Ok(())
57    }
58
59    /// Builds the validated config from parsed values. An unset maximum defaults to 80% of the
60    /// budget.
61    pub fn resolve(budget: u64, min_cost: u64, max_per_identity: Option<u64>) -> Result<Self> {
62        let config = Self {
63            budget,
64            min_cost,
65            identity_cap: max_per_identity.unwrap_or((budget as u128 * 4 / 5) as u64),
66        };
67        config.validate()?;
68        Ok(config)
69    }
70}
71
72/// Converts a decimal GB value to bytes, rejecting anything that is not a finite non-negative
73/// number that fits in a `u64`.
74pub fn gb_to_bytes(gb: f64) -> Result<u64> {
75    if !gb.is_finite() || gb < 0.0 {
76        bail!("expected a finite non-negative number of GB, got {gb}");
77    }
78    let bytes = (gb * GIB).round();
79    if bytes > u64::MAX as f64 {
80        bail!("{gb} GB does not fit in 64 bits of bytes");
81    }
82    Ok(bytes as u64)
83}
84
85/// Parses a decimal-GB env knob: unset is `None`, anything unparseable is an error so a typo
86/// such as `4GB` cannot silently leave the knob off. Takes the `std::env::var` result so it can
87/// be tested without touching the process environment.
88pub fn parse_gb_env(
89    name: &str,
90    var: std::result::Result<String, std::env::VarError>,
91) -> Result<Option<u64>> {
92    match var {
93        Ok(raw) => {
94            let gb: f64 = raw
95                .trim()
96                .parse()
97                .map_err(|e| anyhow::anyhow!("invalid {name} value '{raw}': {e}"))?;
98            gb_to_bytes(gb)
99                .map(Some)
100                .map_err(|e| anyhow::anyhow!("invalid {name} value '{raw}': {e}"))
101        }
102        Err(std::env::VarError::NotPresent) => Ok(None),
103        Err(e) => Err(anyhow::anyhow!("invalid {name}: {e}")),
104    }
105}
106
107fn mb_env_to_bytes(name: &str, default_mb: u64) -> u64 {
108    crate::settings::resolve_u64_env(name, default_mb).saturating_mul(MIB)
109}
110
111/// Flat cost charged for a plan leaf whose work cannot be seen at plan time.
112pub fn opaque_leaf_cost_from_env() -> u64 {
113    mb_env_to_bytes(ADMISSION_OPAQUE_LEAF_COST_ENV, DEFAULT_OPAQUE_LEAF_COST_MB)
114}
115
116/// Builds the scheduler from the environment. `None` (budget unset) means admission is
117/// disabled. The min-cost and per-identity knobs are not read then, so they cannot fail startup.
118pub fn admission_scheduler_from_env() -> Result<Option<Arc<AdmissionScheduler>>> {
119    let Some(budget) = parse_gb_env(ADMISSION_BUDGET_ENV, std::env::var(ADMISSION_BUDGET_ENV))?
120    else {
121        return Ok(None);
122    };
123    let min_cost = mb_env_to_bytes(ADMISSION_MIN_COST_ENV, DEFAULT_MIN_COST_MB);
124    let max_per_identity = parse_gb_env(
125        ADMISSION_MAX_PER_IDENTITY_ENV,
126        std::env::var(ADMISSION_MAX_PER_IDENTITY_ENV),
127    )?;
128    let config = AdmissionConfig::resolve(budget, min_cost, max_per_identity)?;
129    info!(
130        "query admission enabled: budget={} identity_cap={} min_cost={}",
131        config.budget, config.identity_cap, config.min_cost
132    );
133    Ok(Some(Arc::new(AdmissionScheduler::new(config))))
134}
135
136struct Waiter {
137    cost: u64,
138    arrival: u64,
139    grant: oneshot::Sender<()>,
140}
141
142#[derive(Default)]
143struct IdentityState {
144    in_flight: u64,
145    queue: VecDeque<Waiter>,
146}
147
148impl IdentityState {
149    fn is_idle(&self) -> bool {
150        self.in_flight == 0 && self.queue.is_empty()
151    }
152}
153
154#[derive(Default)]
155struct State {
156    in_flight_total: u64,
157    queued_total: u64,
158    /// Set by dispatch when the chosen head is waiting on the budget. Stops a small query from
159    /// an idle identity from passing it on the fast path.
160    head_blocked: bool,
161    next_arrival: u64,
162    per_identity: HashMap<Arc<str>, IdentityState>,
163}
164
165/// Gauges sampled under the lock and published after releasing it.
166struct Sample {
167    in_flight: u64,
168    queued: u64,
169}
170
171impl State {
172    fn sample(&self) -> Sample {
173        Sample {
174            in_flight: self.in_flight_total,
175            queued: self.queued_total,
176        }
177    }
178
179    fn remove_if_idle(&mut self, identity: &Arc<str>) {
180        if self
181            .per_identity
182            .get(identity)
183            .is_some_and(IdentityState::is_idle)
184        {
185            self.per_identity.remove(identity);
186        }
187    }
188
189    fn release(&mut self, identity: &Arc<str>, cost: u64) {
190        if let Some(state) = self.per_identity.get_mut(identity) {
191            state.in_flight -= cost;
192        }
193        self.in_flight_total -= cost;
194        self.remove_if_idle(identity);
195    }
196
197    /// Grants queued waiters in least-in-flight order until the next one does not fit.
198    fn dispatch(&mut self, config: &AdmissionConfig) {
199        loop {
200            let pick = self
201                .per_identity
202                .iter()
203                .filter_map(|(id, st)| {
204                    let head = st.queue.front()?;
205                    (st.in_flight + head.cost <= config.identity_cap)
206                        .then(|| (st.in_flight, head.arrival, id.clone(), head.cost))
207                })
208                .min_by_key(|(in_flight, arrival, _, _)| (*in_flight, *arrival));
209            let Some((_, _, identity, cost)) = pick else {
210                self.head_blocked = false;
211                return;
212            };
213            if self.in_flight_total + cost > config.budget {
214                // Nobody with more in flight may pass this head, so a large query cannot be
215                // starved by a steady stream of small ones; its identity's own in-flight only
216                // drains, so it eventually fits.
217                self.head_blocked = true;
218                return;
219            }
220            let state = self
221                .per_identity
222                .get_mut(&identity)
223                .expect("picked identity exists");
224            let waiter = state.queue.pop_front().expect("picked head exists");
225            self.queued_total -= 1;
226            state.in_flight += cost;
227            self.in_flight_total += cost;
228            if waiter.grant.send(()).is_err() {
229                // The receiver is gone; its drop guard cannot see this waiter anymore.
230                self.release(&identity, cost);
231            }
232        }
233    }
234}
235
236pub struct AdmissionScheduler {
237    state: Mutex<State>,
238    config: AdmissionConfig,
239}
240
241impl AdmissionScheduler {
242    pub fn new(config: AdmissionConfig) -> Self {
243        Self {
244            state: Mutex::new(State::default()),
245            config,
246        }
247    }
248
249    pub fn config(&self) -> &AdmissionConfig {
250        &self.config
251    }
252
253    /// Waiters across all identities; backs the `admission_queued_queries` gauge.
254    pub fn queued_count(&self) -> u64 {
255        self.lock().queued_total
256    }
257
258    /// The cost `admit` would charge for an estimate.
259    pub fn charged_cost(&self, estimate: u64) -> u64 {
260        // Clamping to the cap lets a query larger than the whole budget run instead of waiting
261        // forever, which is what never rejecting requires.
262        estimate.clamp(self.config.min_cost, self.config.identity_cap)
263    }
264
265    fn lock(&self) -> std::sync::MutexGuard<'_, State> {
266        self.state.lock().unwrap_or_else(|e| e.into_inner())
267    }
268
269    fn publish(sample: Sample) {
270        imetric!("admission_in_flight_cost", "bytes", sample.in_flight);
271        imetric!("admission_queued_queries", "count", sample.queued);
272    }
273
274    /// Waits for this identity's turn and returns a permit holding `cost` until dropped.
275    pub async fn admit(self: &Arc<Self>, identity: Arc<str>, cost: u64) -> AdmissionPermit {
276        let charged = self.charged_cost(cost);
277        let (arrival, rx, sample, still_queued) = {
278            let mut state = self.lock();
279            let id_state = state.per_identity.entry(identity.clone()).or_default();
280            let identity_free = id_state.queue.is_empty()
281                && id_state.in_flight + charged <= self.config.identity_cap;
282            let fast = identity_free
283                && state.in_flight_total + charged <= self.config.budget
284                && !state.head_blocked;
285            if fast {
286                state
287                    .per_identity
288                    .get_mut(&identity)
289                    .expect("entry created above")
290                    .in_flight += charged;
291                state.in_flight_total += charged;
292                let sample = state.sample();
293                drop(state);
294                Self::publish(sample);
295                return AdmissionPermit::new(self.clone(), identity, charged);
296            }
297            let arrival = state.next_arrival;
298            state.next_arrival += 1;
299            let (tx, rx) = oneshot::channel();
300            state
301                .per_identity
302                .get_mut(&identity)
303                .expect("entry created above")
304                .queue
305                .push_back(Waiter {
306                    cost: charged,
307                    arrival,
308                    grant: tx,
309                });
310            state.queued_total += 1;
311            state.dispatch(&self.config);
312            // dispatch may grant this waiter immediately; only count those that actually wait.
313            let still_queued = state
314                .per_identity
315                .get(&identity)
316                .is_some_and(|s| s.queue.iter().any(|w| w.arrival == arrival));
317            (arrival, rx, state.sample(), still_queued)
318        };
319        if still_queued {
320            imetric!("admission_queued", "count", 1_u64);
321        }
322        Self::publish(sample);
323        let mut guard = WaitGuard {
324            scheduler: self.clone(),
325            identity: identity.clone(),
326            arrival,
327            charged,
328            rx: Some(rx),
329        };
330        let granted = guard.rx.as_mut().expect("receiver present").await;
331        guard.rx = None;
332        debug_assert!(
333            granted.is_ok(),
334            "a waiter's sender is only dropped after a grant"
335        );
336        AdmissionPermit::new(self.clone(), identity, charged)
337    }
338
339    fn release(&self, identity: &Arc<str>, cost: u64) {
340        let sample = {
341            let mut state = self.lock();
342            state.release(identity, cost);
343            state.dispatch(&self.config);
344            state.sample()
345        };
346        Self::publish(sample);
347    }
348}
349
350/// Removes a cancelled waiter, or gives back the cost of a grant nobody took.
351struct WaitGuard {
352    scheduler: Arc<AdmissionScheduler>,
353    identity: Arc<str>,
354    arrival: u64,
355    charged: u64,
356    rx: Option<oneshot::Receiver<()>>,
357}
358
359impl Drop for WaitGuard {
360    fn drop(&mut self) {
361        if self.rx.is_none() {
362            return;
363        }
364        let sample = {
365            let mut state = self.scheduler.lock();
366            let removed = state
367                .per_identity
368                .get_mut(&self.identity)
369                .and_then(|st| {
370                    let pos = st.queue.iter().position(|w| w.arrival == self.arrival)?;
371                    st.queue.remove(pos)
372                })
373                .is_some();
374            if removed {
375                state.queued_total -= 1;
376                state.remove_if_idle(&self.identity);
377            } else {
378                // Not queued anymore, so a grant raced the cancellation.
379                state.release(&self.identity, self.charged);
380            }
381            state.dispatch(&self.scheduler.config);
382            state.sample()
383        };
384        AdmissionScheduler::publish(sample);
385    }
386}
387
388/// Holds an identity's share of the budget until dropped.
389pub struct AdmissionPermit {
390    scheduler: Arc<AdmissionScheduler>,
391    identity: Arc<str>,
392    cost: u64,
393}
394
395impl AdmissionPermit {
396    fn new(scheduler: Arc<AdmissionScheduler>, identity: Arc<str>, cost: u64) -> Self {
397        Self {
398            scheduler,
399            identity,
400            cost,
401        }
402    }
403
404    /// The cost this permit holds against the budget.
405    pub fn cost(&self) -> u64 {
406        self.cost
407    }
408}
409
410impl Drop for AdmissionPermit {
411    fn drop(&mut self) {
412        self.scheduler.release(&self.identity, self.cost);
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    fn scheduler(budget: u64, min_cost: u64, cap: u64) -> Arc<AdmissionScheduler> {
421        Arc::new(AdmissionScheduler::new(AdmissionConfig {
422            budget,
423            min_cost,
424            identity_cap: cap,
425        }))
426    }
427
428    #[tokio::test]
429    async fn idle_identities_are_removed() {
430        let s = scheduler(100, 1, 100);
431        let a: Arc<str> = Arc::from("a");
432        let p1 = s.admit(a.clone(), 10).await;
433        let p2 = s.admit(Arc::from("b"), 10).await;
434        assert_eq!(s.lock().per_identity.len(), 2);
435        assert_eq!(s.lock().per_identity[&a].in_flight, 10);
436        drop(p1);
437        assert_eq!(s.lock().per_identity.len(), 1);
438        drop(p2);
439        assert!(s.lock().per_identity.is_empty());
440        assert_eq!(s.lock().in_flight_total, 0);
441    }
442
443    #[tokio::test]
444    async fn cancelled_waiter_leaves_no_state() {
445        let s = scheduler(10, 10, 10);
446        let held = s.admit(Arc::from("a"), 10).await;
447        let waiting = tokio::spawn({
448            let s = s.clone();
449            async move { s.admit(Arc::from("b"), 10).await }
450        });
451        while s.queued_count() == 0 {
452            tokio::task::yield_now().await;
453        }
454        waiting.abort();
455        let _ = waiting.await;
456        assert_eq!(s.queued_count(), 0);
457        assert_eq!(s.lock().per_identity.len(), 1);
458        drop(held);
459        assert!(s.lock().per_identity.is_empty());
460    }
461}