lance-core 6.0.0

Lance Columnar Format -- Core Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! AIMD (Additive Increase / Multiplicative Decrease) rate controller.
//!
//! This module provides a reusable AIMD algorithm for dynamically adjusting
//! request rates. On success windows, the rate increases additively. On
//! windows with throttle signals, the rate decreases multiplicatively.
//!
//! The algorithm operates in discrete time windows. At the end of each window,
//! the throttle ratio (throttled / total) is compared against a threshold:
//! - Above threshold: `rate = max(rate * decrease_factor, min_rate)`
//! - At or below threshold: `rate = min(rate + additive_increment, max_rate)`

use std::sync::Mutex;
use std::time::Duration;

use crate::Result;

/// Configuration for the AIMD rate controller.
///
/// Use builder methods to customize. Defaults are tuned for cloud object stores
/// and will start at about 40% of the max rate and require 10 seconds to reach
/// the max rate.
///
/// - initial_rate: 2000 req/s
/// - min_rate: 1 req/s
/// - max_rate: 5000 req/s (0.0 disables ceiling)
/// - decrease_factor: 0.5 (halve on throttle)
/// - additive_increment: 300 req/s per success window
/// - window_duration: 1 second
/// - throttle_threshold: 0.0 (any throttle triggers decrease)
#[derive(Debug, Clone)]
pub struct AimdConfig {
    pub initial_rate: f64,
    pub min_rate: f64,
    pub max_rate: f64,
    pub decrease_factor: f64,
    pub additive_increment: f64,
    pub window_duration: Duration,
    pub throttle_threshold: f64,
}

impl Default for AimdConfig {
    fn default() -> Self {
        Self {
            initial_rate: 2000.0,
            min_rate: 1.0,
            max_rate: 5000.0,
            decrease_factor: 0.5,
            additive_increment: 300.0,
            window_duration: Duration::from_secs(1),
            throttle_threshold: 0.0,
        }
    }
}

impl AimdConfig {
    pub fn with_initial_rate(self, initial_rate: f64) -> Self {
        Self {
            initial_rate,
            ..self
        }
    }

    pub fn with_min_rate(self, min_rate: f64) -> Self {
        Self { min_rate, ..self }
    }

    pub fn with_max_rate(self, max_rate: f64) -> Self {
        Self { max_rate, ..self }
    }

    pub fn with_decrease_factor(self, decrease_factor: f64) -> Self {
        Self {
            decrease_factor,
            ..self
        }
    }

    pub fn with_additive_increment(self, additive_increment: f64) -> Self {
        Self {
            additive_increment,
            ..self
        }
    }

    pub fn with_window_duration(self, window_duration: Duration) -> Self {
        Self {
            window_duration,
            ..self
        }
    }

    pub fn with_throttle_threshold(self, throttle_threshold: f64) -> Self {
        Self {
            throttle_threshold,
            ..self
        }
    }

    /// Validate that the configuration values are sensible.
    pub fn validate(&self) -> Result<()> {
        if self.initial_rate <= 0.0 {
            return Err(crate::Error::invalid_input(format!(
                "initial_rate must be positive, got {}",
                self.initial_rate
            )));
        }
        if self.min_rate <= 0.0 {
            return Err(crate::Error::invalid_input(format!(
                "min_rate must be positive, got {}",
                self.min_rate
            )));
        }
        if self.max_rate < 0.0 {
            return Err(crate::Error::invalid_input(format!(
                "max_rate must be non-negative (0.0 = no ceiling), got {}",
                self.max_rate
            )));
        }
        if self.max_rate > 0.0 && self.min_rate > self.max_rate {
            return Err(crate::Error::invalid_input(format!(
                "min_rate ({}) must not exceed max_rate ({})",
                self.min_rate, self.max_rate
            )));
        }
        if self.decrease_factor <= 0.0 || self.decrease_factor >= 1.0 {
            return Err(crate::Error::invalid_input(format!(
                "decrease_factor must be in (0, 1), got {}",
                self.decrease_factor
            )));
        }
        if self.additive_increment <= 0.0 {
            return Err(crate::Error::invalid_input(format!(
                "additive_increment must be positive, got {}",
                self.additive_increment
            )));
        }
        if self.window_duration.is_zero() {
            return Err(crate::Error::invalid_input(
                "window_duration must be non-zero",
            ));
        }
        if !(0.0..=1.0).contains(&self.throttle_threshold) {
            return Err(crate::Error::invalid_input(format!(
                "throttle_threshold must be in [0.0, 1.0], got {}",
                self.throttle_threshold
            )));
        }
        if self.max_rate > 0.0 && self.initial_rate > self.max_rate {
            return Err(crate::Error::invalid_input(format!(
                "initial_rate ({}) must not exceed max_rate ({})",
                self.initial_rate, self.max_rate
            )));
        }
        if self.initial_rate < self.min_rate {
            return Err(crate::Error::invalid_input(format!(
                "initial_rate ({}) must not be below min_rate ({})",
                self.initial_rate, self.min_rate
            )));
        }
        Ok(())
    }
}

/// Outcome of a single request, used to feed the AIMD controller.
///
/// Non-throttle errors (e.g. 404, network timeout) should be mapped to
/// `Success` since they don't indicate capacity problems.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestOutcome {
    Success,
    Throttled,
}

struct AimdState {
    rate: f64,
    window_start: std::time::Instant,
    success_count: u64,
    throttle_count: u64,
}

/// AIMD rate controller.
///
/// Thread-safe: uses an internal `Mutex` to protect state. The lock is held
/// only briefly during `record_outcome` and `current_rate`.
pub struct AimdController {
    config: AimdConfig,
    state: Mutex<AimdState>,
}

impl std::fmt::Debug for AimdController {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AimdController")
            .field("config", &self.config)
            .field("rate", &self.current_rate())
            .finish()
    }
}

impl AimdController {
    /// Create a new AIMD controller with the given configuration.
    pub fn new(config: AimdConfig) -> Result<Self> {
        config.validate()?;
        let rate = config.initial_rate;
        Ok(Self {
            config,
            state: Mutex::new(AimdState {
                rate,
                window_start: std::time::Instant::now(),
                success_count: 0,
                throttle_count: 0,
            }),
        })
    }

    /// Record a request outcome and return the current rate.
    ///
    /// If the current time window has expired, the rate is adjusted before
    /// recording the new outcome in a fresh window.
    pub fn record_outcome(&self, outcome: RequestOutcome) -> f64 {
        let mut state = self.state.lock().unwrap();
        self.record_outcome_inner(&mut state, outcome, std::time::Instant::now())
    }

    fn record_outcome_inner(
        &self,
        state: &mut AimdState,
        outcome: RequestOutcome,
        now: std::time::Instant,
    ) -> f64 {
        // Check if the window has expired
        let elapsed = now.duration_since(state.window_start);
        if elapsed >= self.config.window_duration {
            let total = state.success_count + state.throttle_count;
            if total > 0 {
                let throttle_ratio = state.throttle_count as f64 / total as f64;
                if throttle_ratio > self.config.throttle_threshold {
                    // Multiplicative decrease
                    state.rate =
                        (state.rate * self.config.decrease_factor).max(self.config.min_rate);
                } else {
                    // Additive increase
                    state.rate += self.config.additive_increment;
                    if self.config.max_rate > 0.0 {
                        state.rate = state.rate.min(self.config.max_rate);
                    }
                }
            }
            // Reset window
            state.window_start = now;
            state.success_count = 0;
            state.throttle_count = 0;
        }

        // Record this outcome
        match outcome {
            RequestOutcome::Success => state.success_count += 1,
            RequestOutcome::Throttled => state.throttle_count += 1,
        }

        state.rate
    }

    /// Get the current rate without recording an outcome.
    pub fn current_rate(&self) -> f64 {
        self.state.lock().unwrap().rate
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    #[rstest]
    #[case::zero_initial_rate(
        AimdConfig::default().with_initial_rate(0.0),
        "initial_rate must be positive"
    )]
    #[case::negative_min_rate(
        AimdConfig::default().with_min_rate(-1.0),
        "min_rate must be positive"
    )]
    #[case::negative_max_rate(
        AimdConfig::default().with_max_rate(-1.0),
        "max_rate must be non-negative"
    )]
    #[case::min_exceeds_max(
        AimdConfig::default().with_min_rate(100.0).with_max_rate(10.0),
        "min_rate (100) must not exceed max_rate (10)"
    )]
    #[case::decrease_factor_zero(
        AimdConfig::default().with_decrease_factor(0.0),
        "decrease_factor must be in (0, 1)"
    )]
    #[case::decrease_factor_one(
        AimdConfig::default().with_decrease_factor(1.0),
        "decrease_factor must be in (0, 1)"
    )]
    #[case::decrease_factor_over_one(
        AimdConfig::default().with_decrease_factor(1.5),
        "decrease_factor must be in (0, 1)"
    )]
    #[case::zero_additive_increment(
        AimdConfig::default().with_additive_increment(0.0),
        "additive_increment must be positive"
    )]
    #[case::zero_window_duration(
        AimdConfig::default().with_window_duration(Duration::ZERO),
        "window_duration must be non-zero"
    )]
    #[case::threshold_over_one(
        AimdConfig::default().with_throttle_threshold(1.1),
        "throttle_threshold must be in [0.0, 1.0]"
    )]
    #[case::threshold_negative(
        AimdConfig::default().with_throttle_threshold(-0.1),
        "throttle_threshold must be in [0.0, 1.0]"
    )]
    #[case::initial_exceeds_max(
        AimdConfig::default().with_initial_rate(6000.0),
        "initial_rate (6000) must not exceed max_rate (5000)"
    )]
    #[case::initial_below_min(
        AimdConfig::default().with_initial_rate(0.5).with_min_rate(1.0),
        "initial_rate (0.5) must not be below min_rate (1)"
    )]
    fn test_config_validation_rejects_invalid(
        #[case] config: AimdConfig,
        #[case] expected_msg: &str,
    ) {
        let err = config.validate().unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains(expected_msg),
            "Expected error containing '{}', got: {}",
            expected_msg,
            msg
        );
    }

    #[test]
    fn test_default_config_is_valid() {
        AimdConfig::default().validate().unwrap();
    }

    #[test]
    fn test_no_ceiling_config_is_valid() {
        AimdConfig::default().with_max_rate(0.0).validate().unwrap();
    }

    #[test]
    fn test_additive_increase_on_success_window() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_additive_increment(10.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        // Record some successes in the first window
        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, start);
        }

        // Advance past the window boundary and record another success
        let after_window = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, after_window);
        }

        // Rate should have increased by additive_increment
        assert_eq!(controller.current_rate(), 110.0);
    }

    #[test]
    fn test_multiplicative_decrease_on_throttle_window() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_decrease_factor(0.5)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
        }

        // Advance past window
        let after_window = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, after_window);
        }

        assert_eq!(controller.current_rate(), 50.0);
    }

    #[test]
    fn test_floor_enforcement() {
        let config = AimdConfig::default()
            .with_initial_rate(2.0)
            .with_min_rate(1.0)
            .with_decrease_factor(0.5)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
        }

        // After decrease: 2.0 * 0.5 = 1.0 (at floor)
        let t1 = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, t1);
        }
        assert_eq!(controller.current_rate(), 1.0);

        // Another decrease should stay at floor
        let t2 = t1 + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t2);
        }
        assert_eq!(controller.current_rate(), 1.0);
    }

    #[test]
    fn test_ceiling_enforcement() {
        let config = AimdConfig::default()
            .with_initial_rate(4990.0)
            .with_max_rate(5000.0)
            .with_additive_increment(20.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, start);
        }

        let t1 = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t1);
        }
        // 4990 + 20 = 5010, clamped to 5000
        assert_eq!(controller.current_rate(), 5000.0);
    }

    #[test]
    fn test_no_ceiling_allows_unbounded_growth() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_max_rate(0.0)
            .with_additive_increment(50.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        let mut t = start;

        for _ in 0..5 {
            {
                let mut state = controller.state.lock().unwrap();
                controller.record_outcome_inner(&mut state, RequestOutcome::Success, t);
            }
            t += Duration::from_millis(150);
        }

        // Trigger final window evaluation
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t);
        }

        // 100 + 50*5 = 350
        assert_eq!(controller.current_rate(), 350.0);
    }

    #[test]
    fn test_empty_window_no_adjustment() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        // Don't record anything in the first window, just advance time
        let start = std::time::Instant::now();
        let after = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            // First outcome in a new window after empty window
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, after);
        }
        // No adjustment because the expired window had 0 total
        assert_eq!(controller.current_rate(), 100.0);
    }

    #[test]
    fn test_throttle_threshold_filtering() {
        // With threshold 0.5, less than 50% throttles should still increase
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_throttle_threshold(0.5)
            .with_additive_increment(10.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            // 1 throttle out of 3 = 33% < 50% threshold
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, start);
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, start);
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
        }

        // Advance past window
        let t1 = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t1);
        }

        // Should have increased because 33% <= 50%
        assert_eq!(controller.current_rate(), 110.0);
    }

    #[test]
    fn test_throttle_threshold_triggers_decrease() {
        // With threshold 0.5, >= 50% throttles should decrease
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_throttle_threshold(0.5)
            .with_decrease_factor(0.5)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();
        {
            let mut state = controller.state.lock().unwrap();
            // 2 throttle out of 3 = 67% > 50% threshold
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, start);
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
        }

        let t1 = start + Duration::from_millis(150);
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t1);
        }

        assert_eq!(controller.current_rate(), 50.0);
    }

    #[test]
    fn test_recovery_after_decrease() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_decrease_factor(0.5)
            .with_additive_increment(10.0)
            .with_window_duration(Duration::from_millis(100));
        let controller = AimdController::new(config).unwrap();

        let start = std::time::Instant::now();

        // Window 1: throttle → decrease to 50
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Throttled, start);
        }
        let t1 = start + Duration::from_millis(150);

        // Window 2: success → increase to 60
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t1);
        }
        let t2 = t1 + Duration::from_millis(150);

        // Window 3: success → increase to 70
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t2);
        }
        let t3 = t2 + Duration::from_millis(150);

        // Trigger final evaluation
        {
            let mut state = controller.state.lock().unwrap();
            controller.record_outcome_inner(&mut state, RequestOutcome::Success, t3);
        }

        assert_eq!(controller.current_rate(), 70.0);
    }

    #[test]
    fn test_within_window_no_adjustment() {
        let config = AimdConfig::default()
            .with_initial_rate(100.0)
            .with_window_duration(Duration::from_secs(10));
        let controller = AimdController::new(config).unwrap();

        // Record many outcomes but all within the same window
        for _ in 0..100 {
            controller.record_outcome(RequestOutcome::Throttled);
        }

        // Rate should still be initial since window hasn't expired
        assert_eq!(controller.current_rate(), 100.0);
    }
}