cache2 0.6.1

Performance-first bounded RAM and NVMe hybrid cache
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
// Copyright 2026 ScopeDB, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Bounded pre-timeout observation and worker-paced fill admission.

use std::io;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;

use crate::FillControlOptions;
use crate::FillControlSnapshot;
use crate::FillLimits;
use crate::FillPressure;

const CREDIT_UNIT_BYTES: u64 = 64;
const MAX_CAS_ATTEMPTS: usize = 4;
const MIN_BYTES_PER_SECOND: u64 = 640;
const MAX_BYTES_PER_SECOND: u64 = 1 << 40;
const MIN_RECORDS_PER_SECOND: u32 = 10;
const MAX_RECORDS_PER_SECOND: u32 = u32::MAX;
const TICKS_PER_SECOND: u64 = 10;

/// Wake shard workers this often when a non-essential flush is waiting for budget.
pub const FLUSH_RETRY: Duration = Duration::from_millis(100);

/// Credit taken by one non-essential flush. Zero for Observe and essential work.
#[derive(Clone, Copy)]
pub struct FlushCharge {
    pub records: u64,
    pub byte_units: u64,
}

fn packed_records(value: u64) -> u64 {
    value >> 32
}

fn packed_byte_units(value: u64) -> u64 {
    value & u64::from(u32::MAX)
}

fn pack_credit(records: u64, byte_units: u64) -> u64 {
    (records << 32) | byte_units
}

fn nanos(duration: Duration) -> u64 {
    duration.as_nanos().min(u128::from(u64::MAX)) as u64
}

struct Slot {
    start_ns: AtomicU64,
    bytes: AtomicU64,
}

pub struct FillController {
    limits: FillLimits,
    enforcing: bool,
    max_byte_units: u64,
    max_records: u64,
    origin: Instant,
    credit: AtomicU64,
    last_refill_ns: AtomicU64,
    paused: AtomicBool,
    stopped: AtomicBool,
    pause_holders: AtomicUsize,
    rejections: AtomicU64,
    would_reject: AtomicU64,
    dropped_observations: AtomicU64,
    completed_bytes: AtomicU64,
    slots: Box<[Slot]>,
}

impl FillController {
    pub fn allocation_bytes(options: FillControlOptions, slots: usize) -> io::Result<usize> {
        let limits = match options {
            FillControlOptions::Disabled => return Ok(0),
            FillControlOptions::Observe(limits) | FillControlOptions::Adaptive(limits) => limits,
        };
        if !(MIN_BYTES_PER_SECOND..=MAX_BYTES_PER_SECOND).contains(&limits.max_bytes_per_second)
            || !(MIN_RECORDS_PER_SECOND..=MAX_RECORDS_PER_SECOND)
                .contains(&limits.max_records_per_second)
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "fill rate ceilings are out of range",
            ));
        }
        slots
            .checked_mul(size_of::<Slot>())
            .and_then(|bytes| bytes.checked_add(size_of::<Self>() + 256))
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "fill controller memory overflow",
                )
            })
    }

    pub fn new(
        options: FillControlOptions,
        slots: usize,
        max_flush_bytes: u64,
    ) -> io::Result<Option<Self>> {
        Self::allocation_bytes(options, slots)?;
        let (limits, enforcing) = match options {
            FillControlOptions::Disabled => return Ok(None),
            FillControlOptions::Observe(limits) => (limits, false),
            FillControlOptions::Adaptive(limits) => (limits, true),
        };
        let max_byte_units = (limits.max_bytes_per_second / TICKS_PER_SECOND)
            .max(max_flush_bytes)
            .div_ceil(CREDIT_UNIT_BYTES);
        if max_byte_units > u64::from(u32::MAX) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "fill burst exceeds budget representation",
            ));
        }
        let max_records = u64::from(limits.max_records_per_second / TICKS_PER_SECOND as u32).max(1);
        let mut table = Vec::new();
        table.try_reserve_exact(slots).map_err(|_| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "cannot allocate fill observations",
            )
        })?;
        table.resize_with(slots, || Slot {
            start_ns: AtomicU64::new(0),
            bytes: AtomicU64::new(0),
        });
        Ok(Some(Self {
            limits,
            enforcing,
            max_byte_units,
            max_records,
            origin: Instant::now(),
            credit: AtomicU64::new(pack_credit(max_records, max_byte_units)),
            last_refill_ns: AtomicU64::new(0),
            paused: AtomicBool::new(false),
            stopped: AtomicBool::new(false),
            pause_holders: AtomicUsize::new(0),
            rejections: AtomicU64::new(0),
            would_reject: AtomicU64::new(0),
            dropped_observations: AtomicU64::new(0),
            completed_bytes: AtomicU64::new(0),
            slots: table.into_boxed_slice(),
        }))
    }

    fn elapsed_ns(&self) -> u64 {
        nanos(self.origin.elapsed())
    }

    pub fn stop(&self) {
        self.stopped.store(true, Ordering::Release);
        self.publish();
    }

    pub fn hold_pause(&self) {
        self.pause_holders.fetch_add(1, Ordering::AcqRel);
        self.publish();
    }

    pub fn release_pause(&self) {
        self.pause_holders.fetch_sub(1, Ordering::AcqRel);
        self.publish();
    }

    fn publish(&self) {
        let next = self.is_paused();
        if self.paused.swap(next, Ordering::Release) != next {
            let pressure = if next { "paused" } else { "healthy" };
            log::info!(
                target: "cache2::health",
                event = "cache_fill_pressure_changed",
                pressure;
                "cache fill admission pressure changed"
            );
        }
    }

    fn is_paused(&self) -> bool {
        self.stopped.load(Ordering::Acquire) || self.pause_holders.load(Ordering::Acquire) != 0
    }

    pub fn suppress_reinsertion(&self) -> bool {
        self.enforcing && self.is_paused()
    }

    pub fn snapshot(&self) -> FillControlSnapshot {
        let paused = self.is_paused();
        let pressure = if paused {
            FillPressure::Paused
        } else {
            FillPressure::Healthy
        };
        let now = self.elapsed_ns();
        let mut outstanding_operations = 0_u64;
        let mut outstanding_bytes = 0_u64;
        let mut oldest = 0_u64;
        for slot in self.slots.iter() {
            let start = slot.start_ns.load(Ordering::Acquire);
            if start == 0 {
                continue;
            }
            outstanding_operations += 1;
            outstanding_bytes =
                outstanding_bytes.saturating_add(slot.bytes.load(Ordering::Relaxed));
            oldest = oldest.max(now.saturating_sub(start));
        }
        let completed = self.completed_bytes.load(Ordering::Relaxed);
        let drain = if outstanding_operations != 0 && completed != 0 && now != 0 {
            (outstanding_bytes as f64 / (completed as f64 / (now as f64 / 1e9)) * 1e9)
                .min(u64::MAX as f64) as u64
        } else {
            0
        };
        let (byte_rate, record_rate) = if paused {
            (0, 0)
        } else {
            (
                self.limits.max_bytes_per_second,
                self.limits.max_records_per_second,
            )
        };
        FillControlSnapshot {
            pressure,
            enforcing: self.enforcing,
            bytes_per_second: byte_rate,
            records_per_second: record_rate,
            rejections: self.rejections.load(Ordering::Relaxed),
            would_reject: self.would_reject.load(Ordering::Relaxed),
            dropped_observations: self.dropped_observations.load(Ordering::Relaxed),
            outstanding_operations,
            outstanding_bytes,
            oldest_operation_ns: oldest,
            estimated_drain_ns: drain,
        }
    }

    /// Foreground admission: Adaptive rejects only while paused.
    pub fn try_admit_fill(&self) -> bool {
        let paused = self.is_paused();
        if !self.enforcing {
            if paused {
                self.would_reject.fetch_add(1, Ordering::Relaxed);
            }
            return true;
        }
        if paused {
            self.rejections.fetch_add(1, Ordering::Relaxed);
            false
        } else {
            true
        }
    }

    /// Background flush pacing. Essential flushes always proceed.
    pub fn try_acquire_flush_budget(
        &self,
        bytes: u64,
        records: u32,
        essential: bool,
    ) -> Option<FlushCharge> {
        if essential || !self.enforcing {
            return Some(FlushCharge {
                records: 0,
                byte_units: 0,
            });
        }
        self.refill();
        let raw_byte_units = bytes.div_ceil(CREDIT_UNIT_BYTES).max(1);
        let raw_records = u64::from(records.max(1));
        let byte_oversized = raw_byte_units >= self.max_byte_units;
        let record_oversized = raw_records >= self.max_records;
        let min_byte_units = if byte_oversized { 1 } else { raw_byte_units };
        let min_records = if record_oversized { 1 } else { raw_records };
        let mut value = self.credit.load(Ordering::Relaxed);
        for _ in 0..MAX_CAS_ATTEMPTS {
            let have_byte_units = packed_byte_units(value);
            let have_records = packed_records(value);
            if have_byte_units < min_byte_units || have_records < min_records {
                return None;
            }
            let take_byte_units = if byte_oversized {
                have_byte_units
            } else {
                raw_byte_units
            };
            let take_records = if record_oversized {
                have_records
            } else {
                raw_records
            };
            let next = pack_credit(
                have_records - take_records,
                have_byte_units - take_byte_units,
            );
            match self
                .credit
                .compare_exchange(value, next, Ordering::AcqRel, Ordering::Relaxed)
            {
                Ok(_) => {
                    return Some(FlushCharge {
                        records: take_records,
                        byte_units: take_byte_units,
                    });
                }
                Err(current) => value = current,
            }
        }
        None
    }

    pub fn refund_flush_budget(&self, charge: FlushCharge) {
        if self.enforcing {
            self.add_credit(charge.records, charge.byte_units);
        }
    }

    fn refill(&self) {
        let now = self.elapsed_ns();
        let last = self.last_refill_ns.load(Ordering::Relaxed);
        let Some(dt) = now.checked_sub(last).filter(|dt| *dt != 0) else {
            return;
        };
        let add_byte_units =
            self.limits.max_bytes_per_second.saturating_mul(dt) / 1_000_000_000 / CREDIT_UNIT_BYTES;
        let add_records =
            u64::from(self.limits.max_records_per_second).saturating_mul(dt) / 1_000_000_000;
        if add_byte_units == 0 && add_records == 0 {
            return;
        }
        if self
            .last_refill_ns
            .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
            .is_err()
        {
            return;
        }
        self.add_credit(add_records, add_byte_units);
    }

    fn add_credit(&self, records: u64, byte_units: u64) {
        if records == 0 && byte_units == 0 {
            return;
        }
        let mut value = self.credit.load(Ordering::Relaxed);
        loop {
            let next = pack_credit(
                (packed_records(value) + records).min(self.max_records),
                (packed_byte_units(value) + byte_units).min(self.max_byte_units),
            );
            match self
                .credit
                .compare_exchange(value, next, Ordering::Relaxed, Ordering::Relaxed)
            {
                Ok(_) => return,
                Err(current) => value = current,
            }
        }
    }

    pub fn observe_io(&self, bytes: u64) -> Option<IoObservation<'_>> {
        let start = self.elapsed_ns().max(1);
        for (index, slot) in self.slots.iter().enumerate() {
            if slot
                .start_ns
                .compare_exchange(0, start, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                slot.bytes.store(bytes, Ordering::Relaxed);
                return Some(IoObservation {
                    control: self,
                    index,
                    succeeded: false,
                    slow: false,
                });
            }
        }
        self.dropped_observations.fetch_add(1, Ordering::Relaxed);
        None
    }
}

/// One worker-owned observation. Failed work is removed, never marked successful.
pub struct IoObservation<'a> {
    control: &'a FillController,
    index: usize,
    succeeded: bool,
    slow: bool,
}

impl IoObservation<'_> {
    pub fn note_slow(&mut self) {
        if self.slow {
            return;
        }
        self.slow = true;
        self.control.hold_pause();
    }

    pub fn clear_slow(&mut self) {
        if !self.slow {
            return;
        }
        self.slow = false;
        self.control.release_pause();
    }

    pub fn finish(mut self) {
        self.succeeded = true;
    }
}

impl Drop for IoObservation<'_> {
    fn drop(&mut self) {
        let slot = &self.control.slots[self.index];
        let bytes = slot.bytes.load(Ordering::Relaxed);
        slot.start_ns.store(0, Ordering::Release);
        if self.succeeded {
            self.control
                .completed_bytes
                .fetch_add(bytes, Ordering::Relaxed);
        }
        if self.slow {
            self.control.release_pause();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;

    use super::*;

    fn control(enforcing: bool) -> FillController {
        let limits = FillLimits::new(64_000, 100);
        FillController::new(
            if enforcing {
                FillControlOptions::Adaptive(limits)
            } else {
                FillControlOptions::Observe(limits)
            },
            4,
            4096,
        )
        .unwrap()
        .unwrap()
    }

    fn restore_burst(control: &FillController) {
        control.credit.store(
            pack_credit(control.max_records, control.max_byte_units),
            Ordering::Release,
        );
    }

    fn freeze_refill(control: &FillController) {
        control
            .last_refill_ns
            .store(control.elapsed_ns(), Ordering::Relaxed);
    }

    #[test]
    fn foreground_admit_ignores_flush_budget() {
        let control = control(true);
        for _ in 0..10 {
            assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        }
        assert!(control.try_acquire_flush_budget(64, 1, false).is_none());
        assert!(control.try_admit_fill());
    }

    #[test]
    fn record_budget_paces_nonessential_flush() {
        let control = control(true);
        for _ in 0..10 {
            assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        }
        assert!(control.try_acquire_flush_budget(64, 1, false).is_none());
        assert!(control.try_acquire_flush_budget(64, 1, true).is_some());
        restore_burst(&control);
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
    }

    #[test]
    fn byte_budget_paces_nonessential_flush() {
        let control = control(true);
        assert!(control.try_acquire_flush_budget(4096, 1, false).is_some());
        assert!(control.try_acquire_flush_budget(4096, 1, false).is_none());
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        restore_burst(&control);
        assert!(control.try_acquire_flush_budget(4096, 1, false).is_some());
    }

    #[test]
    fn old_request_pauses_while_other_requests_progress() {
        let control = control(true);
        let mut old = control.observe_io(4096).unwrap();
        let fast = control.observe_io(64).unwrap();
        fast.finish();
        old.note_slow();
        assert_eq!(control.snapshot().pressure, FillPressure::Paused);
        assert!(!control.try_admit_fill());
        drop(old);
        assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
        assert!(control.try_admit_fill());
    }

    #[test]
    fn observe_never_rejects_or_suppresses_reinsertion() {
        let control = control(false);
        let mut old = control.observe_io(4096).unwrap();
        old.note_slow();
        assert_eq!(control.snapshot().pressure, FillPressure::Paused);
        for _ in 0..20 {
            assert!(control.try_admit_fill());
        }
        assert_eq!(control.snapshot().would_reject, 20);
        assert_eq!(control.snapshot().rejections, 0);
        assert!(!control.suppress_reinsertion());
    }

    #[test]
    fn observe_would_reject_counts_pause_not_budget() {
        let control = control(false);
        for _ in 0..20 {
            assert!(control.try_acquire_flush_budget(4096, 1, false).is_some());
            assert!(control.try_admit_fill());
        }
        assert_eq!(control.snapshot().would_reject, 0);
        let mut old = control.observe_io(4096).unwrap();
        old.note_slow();
        assert_eq!(control.snapshot().pressure, FillPressure::Paused);
        assert!(control.try_admit_fill());
        assert_eq!(control.snapshot().would_reject, 1);
        assert_eq!(control.snapshot().rejections, 0);
    }

    #[test]
    fn idle_time_does_not_inflate_credit() {
        let control = control(true);
        control.last_refill_ns.store(0, Ordering::Relaxed);
        control.refill();
        let credit = control.credit.load(Ordering::Relaxed);
        assert_eq!(packed_records(credit), control.max_records);
        assert_eq!(packed_byte_units(credit), control.max_byte_units);
    }

    #[test]
    fn large_flush_remains_eligible_and_stop_cannot_reopen_admission() {
        let control = FillController::new(
            FillControlOptions::Adaptive(FillLimits::new(640, 10)),
            1,
            4096,
        )
        .unwrap()
        .unwrap();
        assert!(control.try_acquire_flush_budget(4096, 1, false).is_some());
        restore_burst(&control);
        assert!(control.try_acquire_flush_budget(4096, 1, false).is_some());
        control.stop();
        assert!(!control.try_admit_fill());
    }

    #[test]
    fn recovering_fence_does_not_need_outstanding_io() {
        let control = control(true);
        control.hold_pause();
        assert_eq!(control.snapshot().pressure, FillPressure::Paused);
        assert!(!control.try_admit_fill());
        control.release_pause();
        assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
        assert!(control.try_admit_fill());
    }

    #[test]
    fn overlapping_recovery_holds_resume_when_all_release() {
        let control = control(true);
        control.hold_pause();
        control.hold_pause();
        assert!(!control.try_admit_fill());
        control.release_pause();
        assert_eq!(control.snapshot().pressure, FillPressure::Paused);
        assert!(!control.try_admit_fill());
        control.release_pause();
        assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
        assert!(control.try_admit_fill());
    }

    #[test]
    fn failed_observations_release_capacity_without_reporting_success() {
        let control = FillController::new(
            FillControlOptions::Observe(FillLimits::new(640, 10)),
            1,
            4096,
        )
        .unwrap()
        .unwrap();
        let pending = control.observe_io(4096).unwrap();
        assert!(control.observe_io(64).is_none());
        assert_eq!(control.snapshot().dropped_observations, 1);
        drop(pending);
        let pending = control.observe_io(4096).unwrap();
        drop(pending);
        assert_eq!(control.completed_bytes.load(Ordering::Relaxed), 0);
        assert_eq!(control.slots[0].start_ns.load(Ordering::Acquire), 0);
    }

    #[test]
    fn concurrent_flush_never_exceeds_shared_budget() {
        let control = control(true);
        freeze_refill(&control);
        let accepted = AtomicU64::new(0);
        thread::scope(|scope| {
            for _ in 0..8 {
                let control = &control;
                let accepted = &accepted;
                scope.spawn(move || {
                    for _ in 0..100 {
                        if control.try_acquire_flush_budget(640, 1, false).is_some() {
                            accepted.fetch_add(1, Ordering::Relaxed);
                        }
                    }
                });
            }
        });
        assert_eq!(accepted.load(Ordering::Relaxed), 10);
    }

    #[test]
    fn io_completion_releases_pause_before_observation_drop() {
        let control = control(true);
        let mut pending = control.observe_io(4096).unwrap();
        pending.note_slow();
        assert!(!control.try_admit_fill());
        pending.clear_slow();
        assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
        assert!(control.try_admit_fill());
        pending.finish();
    }

    #[test]
    fn concurrent_pause_holders_resume_when_all_release() {
        let control = control(true);
        thread::scope(|scope| {
            for _ in 0..8 {
                let control = &control;
                scope.spawn(move || {
                    let mut pending = control.observe_io(64).unwrap();
                    pending.note_slow();
                    assert!(!control.try_admit_fill());
                    drop(pending);
                });
            }
        });
        assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
        assert_eq!(control.pause_holders.load(Ordering::Acquire), 0);
        assert!(control.try_admit_fill());
    }

    #[test]
    fn overlapping_hold_and_release_cannot_stick_paused() {
        let control = control(true);
        for _ in 0..1_000 {
            let mut first = control.observe_io(64).unwrap();
            let mut second = control.observe_io(64).unwrap();
            first.note_slow();
            second.note_slow();
            drop(first);
            drop(second);
            assert_eq!(control.pause_holders.load(Ordering::Acquire), 0);
            assert_eq!(control.snapshot().pressure, FillPressure::Healthy);
            assert!(control.try_admit_fill());
        }
    }

    #[test]
    fn burst_sized_flush_proceeds_on_remaining_credit() {
        let control = control(true);
        freeze_refill(&control);
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        assert!(
            control
                .try_acquire_flush_budget(1_000_000, 1, false)
                .is_some()
        );
        restore_burst(&control);
        freeze_refill(&control);
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        assert!(
            control
                .try_acquire_flush_budget(64, 1_000_000, false)
                .is_some()
        );
    }

    #[test]
    fn refund_restores_nonessential_budget() {
        let control = control(true);
        freeze_refill(&control);
        let mut last = FlushCharge {
            records: 0,
            byte_units: 0,
        };
        for _ in 0..10 {
            last = control.try_acquire_flush_budget(64, 1, false).unwrap();
        }
        assert!(control.try_acquire_flush_budget(64, 1, false).is_none());
        control.refund_flush_budget(last);
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
    }

    #[test]
    fn sub_tick_refills_do_not_burn_elapsed_time() {
        let mut control = FillController::new(
            FillControlOptions::Adaptive(FillLimits::new(640, 10)),
            1,
            4096,
        )
        .unwrap()
        .unwrap();
        freeze_refill(&control);
        while control.try_acquire_flush_budget(64, 1, false).is_some() {}
        let one_ms_ago = control.elapsed_ns().saturating_sub(1_000_000);
        control.last_refill_ns.store(one_ms_ago, Ordering::Relaxed);
        for _ in 0..32 {
            control.refill();
        }
        assert_eq!(control.last_refill_ns.load(Ordering::Relaxed), one_ms_ago);
        control.origin = control
            .origin
            .checked_sub(Duration::from_millis(110))
            .unwrap();
        control.refill();
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
    }

    #[test]
    fn concurrent_refunds_are_not_dropped() {
        let control = FillController::new(
            FillControlOptions::Adaptive(FillLimits::new(64_000, 10_000)),
            1,
            4096,
        )
        .unwrap()
        .unwrap();
        freeze_refill(&control);
        while control.try_acquire_flush_budget(64, 1, false).is_some() {}
        let before = control.credit.load(Ordering::Relaxed);
        thread::scope(|scope| {
            for _ in 0..32 {
                let control = &control;
                scope.spawn(move || {
                    control.refund_flush_budget(FlushCharge {
                        records: 1,
                        byte_units: 1,
                    });
                });
            }
        });
        let credit = control.credit.load(Ordering::Relaxed);
        assert_eq!(
            packed_records(credit),
            (packed_records(before) + 32).min(control.max_records)
        );
        assert_eq!(
            packed_byte_units(credit),
            (packed_byte_units(before) + 32).min(control.max_byte_units)
        );
    }

    #[test]
    fn oversized_refund_restores_only_consumed_remainder() {
        let control = control(true);
        freeze_refill(&control);
        for _ in 0..9 {
            assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        }
        let charge = control
            .try_acquire_flush_budget(1_000_000, 1, false)
            .unwrap();
        assert_eq!(charge.records, 1);
        assert_eq!(charge.byte_units, control.max_byte_units - 9);
        control.refund_flush_budget(charge);
        let credit = control.credit.load(Ordering::Relaxed);
        assert_eq!(packed_records(credit), 1);
        assert_eq!(packed_byte_units(credit), charge.byte_units);
        assert!(control.try_acquire_flush_budget(64, 1, false).is_some());
        assert!(control.try_acquire_flush_budget(64, 1, false).is_none());
    }
}