1mod admission;
20mod knee;
21mod model;
22mod regime;
23
24use std::num::NonZeroU64;
25use std::sync::Arc;
26use std::sync::atomic::AtomicU64;
27use std::sync::atomic::Ordering::Relaxed;
28use std::time::{Duration, Instant};
29
30pub use admission::{
31 AdmissionOrder, InFlightBudget, InFlightPermit, InFlightStats, in_issue_order,
32};
33use crossbeam_queue::ArrayQueue;
34use knee::{BOUND_FRACTION, KneeConfig, KneeController, KneeTick, LimiterTick};
35pub use model::Model;
36use polars_core::runtime::ASYNC;
37use polars_utils::relaxed_cell::RelaxedCell;
38pub use regime::{Regime, RegimeState};
39
40const SAMPLE_QUEUE_CAPACITY: usize = 8192;
43
44use crate::cloud::concurrency_config::get_random_access_chunk_size;
45use crate::cloud::http_rate_limit::PacingBudget;
46
47#[derive(Clone, Copy, Debug)]
48pub struct IoSample {
49 pub n_bytes: u64,
50 pub ttfb: Duration,
52 pub ttlb: Duration,
54 pub completion_time: Instant,
56}
57
58#[derive(Default)]
60struct TickReads {
61 n: usize,
62 n_bytes: u64,
63 ttlb_byte_secs: f64,
65 slowest: Option<IoSample>,
67}
68
69impl TickReads {
70 fn add(&mut self, s: &IoSample) {
71 self.n += 1;
72 self.n_bytes += s.n_bytes;
73 self.ttlb_byte_secs += s.n_bytes as f64 * s.ttlb.as_secs_f64();
74 if self.slowest.is_none_or(|m| s.ttlb > m.ttlb) {
75 self.slowest = Some(*s);
76 }
77 }
78
79 fn ttlb_byte_avg_ms(&self) -> f64 {
81 if self.n_bytes == 0 {
82 return 0.0;
83 }
84 self.ttlb_byte_secs / self.n_bytes as f64 * 1e3
85 }
86}
87
88#[derive(Debug, Clone)]
89pub struct ControllerConfig {
90 window: Duration,
93 init_byte_budget: u64,
95 floor_byte_budget: u64,
97 request_budget: u64,
99 floor_request_budget: u64,
101 control_interval: Duration,
103 budget_resize_threshold: f64,
105 bdp_model: BdpModel,
107 admission_order: AdmissionOrder,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq)]
114enum BdpModel {
115 Ttfb,
116 Knee {
117 max_byte_budget: u64,
119 },
120}
121
122impl Default for ControllerConfig {
123 fn default() -> Self {
124 let target_chunk_size = get_random_access_chunk_size() as u64;
126 let init_byte_budget = get_init_byte_budget(target_chunk_size);
127 let request_budget = get_inflight_request_budget();
128 let (bdp_model, init_byte_budget) =
129 match std::env::var("POLARS_INFLIGHT_BYTE_BUDGET_MODEL").as_deref() {
130 Err(_) | Ok("knee") => {
131 let max_byte_budget = get_knee_max_byte_budget(
132 init_byte_budget,
133 target_chunk_size,
134 request_budget.saturating_mul(target_chunk_size),
135 );
136 (
137 BdpModel::Knee { max_byte_budget },
138 init_byte_budget.min(max_byte_budget),
139 )
140 },
141 Ok("ttfb") => (BdpModel::Ttfb, init_byte_budget),
142 Ok(v) => panic!("invalid value for POLARS_INFLIGHT_BYTE_BUDGET_MODEL: {v}"),
143 };
144 let admission_order = match std::env::var("POLARS_INFLIGHT_ADMISSION_ORDER").as_deref() {
145 Err(_) | Ok("issue") => AdmissionOrder::Issue,
146 Ok("arrival") => AdmissionOrder::Arrival,
147 Ok(v) => panic!("invalid value for POLARS_INFLIGHT_ADMISSION_ORDER: {v}"),
148 };
149 Self {
150 window: Duration::from_millis(1000),
151
152 init_byte_budget,
163
164 floor_byte_budget: target_chunk_size,
167
168 request_budget,
170 floor_request_budget: get_inflight_floor_request_budget(),
171 control_interval: Duration::from_millis(100),
172 budget_resize_threshold: 0.05,
173 bdp_model,
174 admission_order,
175 }
176 }
177}
178
179fn get_knee_max_byte_budget(
184 init_byte_budget: u64,
185 target_chunk_size: u64,
186 max_inflight_bytes: u64,
187) -> u64 {
188 std::env::var("POLARS_INFLIGHT_MAX_BYTE_BUDGET").map_or_else(
189 |_| {
190 (polars_utils::sys::total_memory() / 16)
191 .min(max_inflight_bytes)
192 .max(init_byte_budget)
193 },
194 |x| {
195 x.parse::<NonZeroU64>()
196 .unwrap_or_else(|_| {
197 panic!("invalid value for POLARS_INFLIGHT_MAX_BYTE_BUDGET: {x}")
198 })
199 .get()
200 .max(target_chunk_size)
201 },
202 )
203}
204
205fn get_init_byte_budget(target_chunk_size: u64) -> u64 {
207 let init_byte_budget = std::env::var("POLARS_INFLIGHT_INIT_BYTE_BUDGET")
208 .map(|x| {
209 x.parse::<NonZeroU64>()
210 .unwrap_or_else(|_| {
211 panic!("invalid value for POLARS_INFLIGHT_INIT_BYTE_BUDGET: {x}")
212 })
213 .get()
214 })
215 .unwrap_or_else(|_| {
216 let n = polars_config::config().max_threads() as u64;
220 n.div_ceil(8).max(4) * target_chunk_size
221 })
222 .max(1);
223
224 if init_byte_budget < target_chunk_size {
225 panic!("in-flight byte budget init must be larger than the target_chunk_size");
226 }
227
228 init_byte_budget
229}
230
231pub fn get_inflight_request_budget() -> u64 {
233 std::env::var("POLARS_INFLIGHT_REQUEST_BUDGET")
238 .map(|x| {
239 x.parse::<NonZeroU64>()
240 .unwrap_or_else(|_| panic!("invalid value for POLARS_INFLIGHT_REQUEST_BUDGET: {x}"))
241 .get()
242 })
243 .unwrap_or(512)
244 .max(1)
245}
246
247pub fn get_inflight_floor_request_budget() -> u64 {
249 std::env::var("POLARS_INFLIGHT_FLOOR_REQUEST_BUDGET")
254 .map(|x| {
255 x.parse::<NonZeroU64>()
256 .unwrap_or_else(|_| {
257 panic!("invalid value for POLARS_INFLIGHT_FLOOR_REQUEST_BUDGET: {x}")
258 })
259 .get()
260 })
261 .unwrap_or(polars_config::config().max_threads() as u64)
262 .max(1)
263}
264
265#[derive(Debug)]
268pub struct HeadRttChannel {
269 min_ns: AtomicU64,
270 sum_ns: AtomicU64,
271 count: AtomicU64,
272 total: AtomicU64,
275}
276
277#[derive(Clone, Copy, Debug)]
279pub struct HeadRttWindow {
280 pub min: Option<Duration>,
281 pub avg: Option<Duration>,
282 pub count: u64,
283}
284
285impl HeadRttChannel {
286 fn new() -> Self {
287 Self {
288 min_ns: AtomicU64::new(u64::MAX),
289 sum_ns: AtomicU64::new(0),
290 count: AtomicU64::new(0),
291 total: AtomicU64::new(0),
292 }
293 }
294
295 fn record(&self, rtt: Duration) {
297 let ns = rtt.as_nanos() as u64;
298 self.min_ns.fetch_min(ns, Relaxed);
299 self.sum_ns.fetch_add(ns, Relaxed);
300 self.count.fetch_add(1, Relaxed);
301
302 if self.total.fetch_add(1, Relaxed) == 0 && polars_config::config().verbose() {
303 eprintln!(
304 "[InFlightConcurrency]: observed first RTT sample (metadata): {} ms",
305 rtt.as_millis()
306 );
307 }
308 }
309
310 fn take(&self) -> HeadRttWindow {
312 let min_ns = self.min_ns.swap(u64::MAX, Relaxed);
313 let sum_ns = self.sum_ns.swap(0, Relaxed);
314 let count = self.count.swap(0, Relaxed);
315
316 HeadRttWindow {
317 min: (min_ns != u64::MAX).then(|| Duration::from_nanos(min_ns)),
318 avg: (count > 0).then(|| Duration::from_nanos(sum_ns / count)),
319 count,
320 }
321 }
322}
323
324#[derive(Debug)]
325pub struct ConcurrencyController {
326 config: ControllerConfig,
327 sample_queue: Arc<ArrayQueue<IoSample>>,
328 samples_dropped: Arc<RelaxedCell<u64>>,
329 arrived_bytes: Option<Arc<RelaxedCell<u64>>>,
332 head_rtt: Arc<HeadRttChannel>,
333 inflight_budget: Arc<InFlightBudget>,
334 _control_task: tokio::task::JoinHandle<()>,
335}
336
337impl ConcurrencyController {
338 pub fn new(config: ControllerConfig, pacing_budget: Option<PacingBudget>) -> Self {
339 let sample_queue = Arc::new(ArrayQueue::new(SAMPLE_QUEUE_CAPACITY));
340 let samples_dropped = Arc::new(RelaxedCell::new_u64(0));
341 let arrived_bytes = matches!(config.bdp_model, BdpModel::Knee { .. })
342 .then(|| Arc::new(RelaxedCell::new_u64(0)));
343 let head_rtt = Arc::new(HeadRttChannel::new());
344
345 let inflight_budget = Arc::new(InFlightBudget::new(
346 config.init_byte_budget,
347 config.floor_byte_budget,
348 config.request_budget,
349 config.floor_request_budget,
350 config.admission_order,
351 ));
352
353 let control_task = Self::spawn_control_loop(
354 sample_queue.clone(),
355 samples_dropped.clone(),
356 arrived_bytes.clone(),
357 head_rtt.clone(),
358 inflight_budget.clone(),
359 config.clone(),
360 pacing_budget,
361 );
362
363 Self {
364 config,
365 sample_queue,
366 samples_dropped,
367 arrived_bytes,
368 head_rtt,
369 inflight_budget,
370 _control_task: control_task,
371 }
372 }
373
374 pub fn config(&self) -> &ControllerConfig {
375 &self.config
376 }
377
378 pub fn record_io(&self, sample: IoSample) {
380 if self.sample_queue.push(sample).is_err() {
381 self.samples_dropped.fetch_add(1);
383 }
384 }
385
386 pub fn record_arrived(&self, n_bytes: u64) {
388 if let Some(arrived_bytes) = &self.arrived_bytes {
389 arrived_bytes.fetch_add(n_bytes);
390 }
391 }
392
393 pub fn record_head_rtt(&self, rtt: Duration) {
395 self.head_rtt.record(rtt);
396 }
397
398 pub fn inflight_budget(&self) -> &Arc<InFlightBudget> {
399 &self.inflight_budget
400 }
401
402 pub async fn acquire(&self, bytes: u64) -> InFlightPermit {
403 self.inflight_budget.acquire(bytes).await
404 }
405
406 fn spawn_control_loop(
407 sample_queue: Arc<ArrayQueue<IoSample>>,
408 samples_dropped: Arc<RelaxedCell<u64>>,
409 arrived_bytes: Option<Arc<RelaxedCell<u64>>>,
410 head_rtt: Arc<HeadRttChannel>,
411 admission: Arc<InFlightBudget>,
412 config: ControllerConfig,
413 pacing_budget: Option<PacingBudget>,
414 ) -> tokio::task::JoinHandle<()> {
415 if polars_config::config().verbose() {
416 eprintln!(
417 "[InFlightConcurrency]: spawn control loop: control_interval: {}ms, \
418 bdp_model: {:?}, initial_byte_budget: {}, floor_byte_budget: {}, \
419 request_budget: {}, floor_request_budget: {}, admission_order: {:?}",
420 config.control_interval.as_millis(),
421 config.bdp_model,
422 config.init_byte_budget,
423 config.floor_byte_budget,
424 config.request_budget,
425 config.floor_request_budget,
426 config.admission_order,
427 );
428 }
429 ASYNC.spawn(async move {
430 let mut model = Model::new(config.window);
431 let mut regime = Regime::new(Instant::now());
432
433 let mut ticker = tokio::time::interval(config.control_interval);
434 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
435
436 let max_inflight_budget = config.request_budget as f64;
437 let mut limiter_admitted = pacing_budget.as_ref().map_or(0, PacingBudget::admitted);
438
439 let mut knee_controller = match config.bdp_model {
440 BdpModel::Knee { max_byte_budget } => Some(KneeController::new(KneeConfig {
441 init_budget: config.init_byte_budget,
442 max_budget: max_byte_budget,
443 tick: config.control_interval,
444 })),
445 BdpModel::Ttfb => None,
446 };
447 let mut last_tick: Option<Instant> = None;
448
449 loop {
450 ticker.tick().await;
451 let now = Instant::now();
452 let tick_secs = last_tick.map_or(config.control_interval.as_secs_f64(), |last| {
453 now.duration_since(last).as_secs_f64()
454 });
455 last_tick = Some(now);
456
457 if let Some(ref pacing_budget) = pacing_budget {
459 let request_budget = pacing_budget.request_budget(max_inflight_budget) as u64;
460 admission.resize_request_budget(request_budget);
461 }
462
463 let log = polars_config::config().log_concurrency();
465 let (state, signal, dropped, bw_hwm_held, reads) = {
466 let mut reads = TickReads::default();
467 for _ in 0..SAMPLE_QUEUE_CAPACITY {
468 let Some(s) = sample_queue.pop() else { break };
469 if log {
470 reads.add(&s);
471 }
472 model.record(s);
473 }
474 let dropped = samples_dropped.swap(0);
475 model.update(now);
476 let signal = model.signal();
477 let state = regime.step(signal, now);
478 let bw_hwm_held = model.bw_hwm_bps();
479 (state, signal, dropped, bw_hwm_held, reads)
480 };
481
482 let bytes_arrived = arrived_bytes.as_ref().map_or(0, |c| c.swap(0));
483 let limiter = pacing_budget.as_ref().map(|p| {
484 let admitted = p.admitted();
485 let delta = admitted.wrapping_sub(limiter_admitted);
486 limiter_admitted = admitted;
487 LimiterTick {
488 rate: p.rate(),
489 admitted: delta,
490 }
491 });
492 let byte_acquires_unparked = admission.take_byte_acquires_unparked();
493 let stats = admission.stats();
494 let knee_tick = KneeTick {
495 now,
496 bytes_arrived,
497 bytes_in_use: stats.bytes_in_use,
498 byte_acquires_waited: byte_acquires_unparked + stats.byte_acquires_parked,
499 bytes_budget: admission.current_byte_budget(),
500 limiter,
501 };
502 let knee_budget = knee_controller.as_mut().map(|k| k.step(knee_tick));
503 let delivered_bw = knee_controller
504 .as_ref()
505 .map_or(bw_hwm_held.unwrap_or(0.0), |k| k.sustained_bw_max());
506 admission.set_delivered_bandwidth(delivered_bw as u64);
507
508 if let Some(target) = knee_budget {
509 let current = admission.current_byte_budget();
510 let ratio = target as f64 / current.max(1) as f64;
511 let threshold = config.budget_resize_threshold;
512 if ratio < (1.0 - threshold) || ratio > (1.0 + threshold) {
513 admission.resize_byte_budget(target);
514 }
515 } else if !matches!(state, RegimeState::WarmIdle { .. }) {
516 let base_byte_budget = match (state, signal) {
518 (RegimeState::Init, _) | (_, None) => config.init_byte_budget,
519 (_, Some(signal)) => signal.bdp_bytes().max(config.init_byte_budget),
520 };
521
522 let gain = match state {
524 RegimeState::Init => 1.0,
525 RegimeState::RampUp { .. } => 2.0,
526 RegimeState::Stable => 2.0,
528 RegimeState::ProbeUp { .. } => 3.0,
529 RegimeState::WarmIdle { .. } => 1.0,
531 };
532 let target_byte_budget = (base_byte_budget as f64 * gain) as u64;
533
534 let current_byte_budget = admission.current_byte_budget();
536 let threshold = config.budget_resize_threshold;
537 let should_resize = match current_byte_budget {
538 0 => target_byte_budget > 0,
539 current => {
540 let ratio = target_byte_budget as f64 / current as f64;
541 ratio < (1.0 - threshold) || ratio > (1.0 + threshold)
542 },
543 };
544
545 if should_resize {
546 admission.resize_byte_budget(target_byte_budget);
547 }
548 }
549
550 let head_rtt_window = head_rtt.take();
552
553 if log {
556 let bound = [
558 ("bytes", knee_tick.bytes_bound()),
559 ("requests", stats.requests_saturation >= BOUND_FRACTION),
560 ("limiter", limiter.is_some_and(|l| l.bound(tick_secs))),
561 ]
562 .iter()
563 .filter(|(_, bound)| *bound)
564 .map(|(name, _)| *name)
565 .collect::<Vec<_>>()
566 .join("+");
567 let bound = if bound.is_empty() { "none" } else { &bound };
568 let model_fields = match &knee_controller {
569 Some(k) => format!(
570 "kphase={}, knee={:.1} MB, knee_src={}, bound={bound}, \
571 bw_round={:.1} MB/s, probe_ref={:.1} MB/s, braking={}",
572 k.phase_label(),
573 k.knee().unwrap_or(0) as f64 / 1e6,
574 k.knee_source().map_or("-", |source| source.label()),
575 k.last_bw_round() / 1e6,
576 k.probe_ref_bw() / 1e6,
577 u8::from(k.braking()),
578 ),
579 None => format!(
580 "regime={}, bound={bound}, bw_hwm={:.1} MB/s, bw_avg={:.1} MB/s, \
581 bdp_obs={:.1} MB",
582 state.label(),
583 signal.map(|s| s.bw_hwm_bps).or(bw_hwm_held).unwrap_or(0.0) / 1e6,
584 signal.map_or(0.0, |s| s.bw_avg_bps) / 1e6,
585 signal.map_or(0, |s| s.bdp_bytes()) as f64 / 1e6,
586 ),
587 };
588 eprintln!(
589 "[InFlightConcurrency {}] {model_fields}, \
590 bytes_budget={:.1} MB, \
591 bytes_in_use={:.1} MB ({:.0}%), \
592 req_budget={}, \
593 req_in_use={} ({:.0}%), \
594 rtt_min={:.1} ms, \
595 rtt_avg={:.1} ms, \
596 head_rtt_min={:.1} ms, \
597 head_rtt_avg={:.1} ms, \
598 head_n={}, \
599 reads_done={}, \
600 bytes_done={:.1} MB, \
601 ttlb_byte_avg={:.1} ms, \
602 slowest_ttlb={:.1} ms, \
603 slowest_ttfb={:.1} ms, \
604 slowest_bytes={:.1} MB",
605 chrono::Utc::now(),
606 stats.bytes_budget as f64 / 1e6,
607 stats.bytes_in_use as f64 / 1e6,
608 stats.bytes_saturation * 100.0,
609 stats.request_budget,
610 stats.requests_in_use,
611 stats.requests_saturation * 100.0,
612 signal.map_or(0, |s| s.ttfb_min.as_millis()),
613 signal.map_or(0, |s| s.ttfb_avg.as_millis()),
614 head_rtt_window.min.map_or(0.0, |d| d.as_secs_f64() * 1e3),
615 head_rtt_window.avg.map_or(0.0, |d| d.as_secs_f64() * 1e3),
616 head_rtt_window.count,
617 reads.n,
618 reads.n_bytes as f64 / 1e6,
619 reads.ttlb_byte_avg_ms(),
620 reads.slowest.map_or(0.0, |s| s.ttlb.as_secs_f64() * 1e3),
621 reads.slowest.map_or(0.0, |s| s.ttfb.as_secs_f64() * 1e3),
622 reads.slowest.map_or(0.0, |s| s.n_bytes as f64 / 1e6),
623 );
624 if dropped > 0 {
625 eprintln!(
626 "[InFlightConcurrency] WARN: {dropped} samples dropped (queue full)"
627 );
628 }
629 }
630 }
631 })
632 }
633}
634
635impl Drop for ConcurrencyController {
636 fn drop(&mut self) {
637 self._control_task.abort();
638 }
639}