autozstd 0.2.1

Zstd envelope compression with automatic raw fallback and magicless frames
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
use std::{array::from_fn, cmp::Ordering};

use crate::{
  DEFAULT_MAX_WINDOW_LOG, EncodeOpt, Encoded, LOW_LATENCY_WINDOW_LOG, Level, Type,
  encode::{
    MIN_OBSERVE, effective_window_log, encode_into_with, encode_owned_with, encode_vec_with,
  },
  probe::ContentBucket,
};

const ALL_CNT: usize = Level::ALL.len();
const ONLINE_CNT: usize = Level::ONLINE_CNT;
const BUCKET_CNT: usize = 3;

/// Reference encoding throughput per byte (`s / B`) on baseline x86 release hardware:
/// `[UltraFast(-4), SuperFast(-1), Fastest(1), Fast(3), Balanced(6), Strong(9), High(12), Best(19)]`.
const PRIOR_TIME_SPB: [f64; ALL_CNT] = [
  1.0 / 9.0e8, // -4 (~900 MB/s)
  1.0 / 5.5e8, // -1 (~550 MB/s)
  1.0 / 2.8e8, //  1 (~280 MB/s)
  1.0 / 1.4e8, //  3 (~140 MB/s)
  1.0 / 5.5e7, //  6 (~55 MB/s)
  1.0 / 2.2e7, //  9 (~22 MB/s)
  1.0 / 8.0e6, // 12 (~8 MB/s)
  1.0 / 3.0e6, // 19 (~3 MB/s)
];

/// Approximate wire ratio priors per `(ContentBucket::{Low, Medium, High}, level)`.
const PRIOR_RATIO_TABLE: [[f64; ALL_CNT]; BUCKET_CNT] = [
  [0.86, 0.82, 0.78, 0.74, 0.70, 0.67, 0.64, 0.61], // Low redundancy
  [0.68, 0.62, 0.56, 0.49, 0.43, 0.39, 0.36, 0.33], // Medium redundancy
  [0.42, 0.36, 0.30, 0.25, 0.21, 0.18, 0.16, 0.14], // High redundancy
];

/// Estimated Zstd decode cost (~1.2 GB/s per core, normalized in s/B).
const DECODE_SPB: f64 = 1.0 / 1.2e9;
const DEFAULT_CPU_WEIGHT: f64 = 0.02;
const ALPHA: f64 = 0.2;
const HW_ALPHA: f64 = 0.25;
const MAX_SHIFT: f64 = 4.0;
const HW_SCALE_MIN: f64 = 1e-3;
const HW_SCALE_MAX: f64 = 1e3;
const MIN_SPB: f64 = 1e-12;
const MAX_SPB: f64 = 1.0;
const RATIO_MIN: f64 = 1e-6;
const RATIO_MAX: f64 = 1.0 - RATIO_MIN;
/// Minimum net speedup over raw before entering compression (5% gain hysteresis).
const RAW_HYSTERESIS: f64 = 1.05;
/// Switching between two compressed levels requires at least 3% improvement.
const SWITCH_HYSTERESIS: f64 = 1.03;
const EXPLORE_INTERVAL: u32 = 64;

#[inline]
fn ratio_to_odds(ratio: f64) -> f64 {
  let r = ratio.clamp(RATIO_MIN, RATIO_MAX);
  r / (1.0 - r)
}

#[inline]
fn finite_nonneg(v: f64) -> f64 {
  if v.is_finite() { v.max(0.0) } else { 0.0 }
}

#[inline]
fn odds_to_ratio(odds: f64) -> f64 {
  if !odds.is_finite() {
    return RATIO_MAX;
  }
  (odds / (1.0 + odds)).clamp(RATIO_MIN, RATIO_MAX)
}

#[inline]
const fn approx_level_ctx_bytes(level: Level, eff_wlog: u32) -> u64 {
  let win = 1u64 << eff_wlog;
  let table_mul = match level {
    Level::UltraFast | Level::SuperFast | Level::Fastest => 1,
    Level::Fast | Level::Balanced => 2,
    Level::Strong | Level::High => 4,
    Level::Best => 8,
  };
  win + win * table_mul
}

/// Real-time link, concurrency, latency, and memory signals for compression decisions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NetSignal {
  /// Effective link capacity in bytes/s (`0` = unknown, selects default preset).
  pub bw_bps: u64,
  /// Encoder worker concurrency (`>= 1`).
  pub workers: u16,
  /// Queued uncompressed bytes waiting ahead of the encoder pool.
  pub backlog_bytes: u64,
  /// Pipeline overlap factor in `[0.0, 1.0]` (`0.0` = serial/low-latency, `0.85..=1.0` = pipeline).
  pub overlap_rho: f64,
  /// Hard per-block encoding latency ceiling in microseconds (`0` = unbounded).
  pub max_encode_us: u64,
  /// Hard queue drain ceiling in microseconds (`0` = unbounded).
  pub max_queue_us: u64,
  /// Maximum per-context Zstd `windowLog` (`10..=27`).
  pub max_window_log: u32,
  /// Per-context memory ceiling in bytes (`0` = unbounded).
  pub mem_budget_bytes: u64,
  /// Tie-breaker penalty weight against burning CPU for diminishing ratio gains.
  pub cpu_weight: f64,
  /// Extra bandwidth-saving weight (`> 0` favors smaller wire size on metered links).
  pub bw_weight: f64,
}

impl Default for NetSignal {
  #[inline]
  fn default() -> Self {
    Self::serial(0)
  }
}

impl NetSignal {
  /// Builds a serial single-frame signal (latency-dominated: `overlap_rho = 0.0`).
  #[must_use]
  pub const fn serial(bw_bps: u64) -> Self {
    Self {
      bw_bps,
      workers: 1,
      backlog_bytes: 0,
      overlap_rho: 0.0,
      max_encode_us: 0,
      max_queue_us: 0,
      max_window_log: DEFAULT_MAX_WINDOW_LOG,
      mem_budget_bytes: 0,
      cpu_weight: DEFAULT_CPU_WEIGHT,
      bw_weight: 0.0,
    }
  }

  /// Builds a multi-worker pipelined bulk signal (`overlap_rho = 0.85`).
  #[must_use]
  pub const fn pipeline(bw_bps: u64, workers: u16, backlog_bytes: u64) -> Self {
    let w = if workers == 0 { 1 } else { workers };
    Self {
      bw_bps,
      workers: w,
      backlog_bytes,
      overlap_rho: 0.85,
      max_encode_us: 40_000,
      max_queue_us: 250_000,
      max_window_log: DEFAULT_MAX_WINDOW_LOG,
      mem_budget_bytes: 32 << 20,
      cpu_weight: DEFAULT_CPU_WEIGHT,
      bw_weight: 0.0,
    }
  }

  /// Builds a low-latency interactive terminal/RPC signal (32 KiB window, tight budget).
  #[must_use]
  pub const fn low_latency(bw_bps: u64, rtt_us: u64) -> Self {
    let raw = rtt_us / 6;
    let budget = if rtt_us == 0 {
      2_000
    } else if raw < 800 {
      800
    } else if raw > 5_000 {
      5_000
    } else {
      raw
    };
    Self {
      bw_bps,
      workers: 1,
      backlog_bytes: 0,
      overlap_rho: 0.0,
      max_encode_us: budget,
      max_queue_us: 0,
      max_window_log: LOW_LATENCY_WINDOW_LOG,
      mem_budget_bytes: 1 << 20,
      cpu_weight: DEFAULT_CPU_WEIGHT,
      bw_weight: 0.0,
    }
  }
}

/// Chosen compression mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Choice {
  /// Send the raw bytes.
  Off,
  /// Compress at this level.
  Level(Level),
}

/// Estimated behavior of one level.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stat {
  /// The level.
  pub level: Level,
  /// Compression speed in uncompressed bytes per second.
  pub speed: f64,
  /// Wire size ratio: compressed envelope size over raw size.
  pub ratio: f64,
  /// Number of measurements folded into this estimate.
  pub sample_cnt: u32,
}

#[derive(Debug, Clone, Copy)]
struct BucketModel {
  spb_li: [f64; ALL_CNT],
  ratio_li: [f64; ALL_CNT],
  sample_li: [u32; ALL_CNT],
}

impl BucketModel {
  const fn new(bucket_idx: usize) -> Self {
    Self {
      spb_li: PRIOR_TIME_SPB,
      ratio_li: PRIOR_RATIO_TABLE[bucket_idx],
      sample_li: [0; ALL_CNT],
    }
  }

  fn enforce_monotone(&mut self, i: usize) {
    // Faster levels (`j < i`) have <= encode time (spb) and >= wire ratio.
    for j in (0..i).rev() {
      self.spb_li[j] = self.spb_li[j].min(self.spb_li[j + 1]);
      self.ratio_li[j] = self.ratio_li[j].max(self.ratio_li[j + 1]);
    }
    // Stronger levels (`j > i`) have >= encode time (spb) and <= wire ratio.
    for j in (i + 1)..ALL_CNT {
      self.spb_li[j] = self.spb_li[j].max(self.spb_li[j - 1]);
      self.ratio_li[j] = self.ratio_li[j].min(self.ratio_li[j - 1]);
    }
  }
  fn sync_unsampled_spb(&mut self, hw_scale: f64) {
    for j in 0..ALL_CNT {
      if self.sample_li[j] == 0 {
        self.spb_li[j] = (PRIOR_TIME_SPB[j] * hw_scale).clamp(MIN_SPB, MAX_SPB);
      }
    }
    for k in 0..ALL_CNT {
      if self.sample_li[k] > 0 {
        self.enforce_monotone(k);
      }
    }
  }
}

/// Network-, worker-, latency-, and content-aware compression policy.
///
/// Tracks per-bucket (`Low`, `Medium`, `High`) unit-byte encoding time (`s/B`)
/// and wire ratio via damped EWMA, plus a shared hardware speed multiplier so a
/// single observation calibrates relative level tables across architectures.
#[derive(Debug, Clone)]
pub struct Adaptive {
  bucket_li: [BucketModel; BUCKET_CNT],
  hw_scale: f64,
  last_choice_li: [Option<Choice>; BUCKET_CNT],
  step: u32,
  explore_up: bool,
  explore_bucket: u8,
}

impl Default for Adaptive {
  fn default() -> Self {
    Self::new()
  }
}

impl Adaptive {
  /// Creates an instance initialized with empirically calibrated priors.
  #[must_use]
  pub const fn new() -> Self {
    Self {
      bucket_li: [
        BucketModel::new(0),
        BucketModel::new(1),
        BucketModel::new(2),
      ],
      hw_scale: 1.0,
      last_choice_li: [None; BUCKET_CNT],
      step: 0,
      explore_up: true,
      explore_bucket: 0,
    }
  }

  #[inline]
  fn level_spb(&self, bucket_idx: usize, level_idx: usize) -> f64 {
    self.bucket_li[bucket_idx].spb_li[level_idx].clamp(MIN_SPB, MAX_SPB)
  }

  fn level_cost(&self, bucket_idx: usize, level_idx: usize, sig: &NetSignal) -> f64 {
    let spb = self.level_spb(bucket_idx, level_idx);
    let ratio = self.bucket_li[bucket_idx].ratio_li[level_idx];
    let net_spb = 1.0 / (sig.bw_bps as f64);
    let ser = spb + ratio * net_spb + DECODE_SPB;
    let w = f64::from(sig.workers.max(1));
    let rho = finite_nonneg(sig.overlap_rho).min(1.0);
    let cpu_w = finite_nonneg(sig.cpu_weight);
    let bw_w = finite_nonneg(sig.bw_weight);
    let pipe = (spb / w).max(ratio * net_spb).max(DECODE_SPB);
    (1.0 - rho) * ser + rho * pipe + cpu_w * spb + bw_w * ratio * net_spb
  }

  fn level_feasible(
    &self,
    bucket_idx: usize,
    level_idx: usize,
    len: usize,
    sig: &NetSignal,
  ) -> bool {
    let spb = self.level_spb(bucket_idx, level_idx);
    if sig.max_encode_us > 0 {
      let est_us = (len as f64) * spb * 1e6;
      if est_us > sig.max_encode_us as f64 {
        return false;
      }
    }
    if sig.max_queue_us > 0 {
      let q_bytes = sig.backlog_bytes.saturating_add(len as u64) as f64;
      let est_q_us = q_bytes * spb * 1e6 / f64::from(sig.workers.max(1));
      if est_q_us > sig.max_queue_us as f64 {
        return false;
      }
    }
    if sig.mem_budget_bytes > 0 {
      let eff_wlog = effective_window_log(len, sig.max_window_log);
      if approx_level_ctx_bytes(Level::ALL[level_idx], eff_wlog) > sig.mem_budget_bytes {
        return false;
      }
    }
    true
  }

  /// Backward-compatible decision using a serial single-stream signal on the `Medium` bucket.
  ///
  /// `net_speed == 0` selects [`Level::Balanced`].
  #[must_use]
  pub fn choice(&self, net_speed: u64) -> Choice {
    let sig = NetSignal::serial(net_speed);
    self.plan(128 * 1024, ContentBucket::Medium, &sig)
  }

  /// Plans compression level for `data_len`, `bucket`, and [`NetSignal`] without mutation.
  #[must_use]
  pub fn plan(&self, data_len: usize, bucket: ContentBucket, sig: &NetSignal) -> Choice {
    let Some(bidx) = bucket.index() else {
      return Choice::Off;
    };
    if sig.bw_bps == 0 {
      return Choice::Level(Level::Balanced);
    }

    let raw_cost = (1.0 + finite_nonneg(sig.bw_weight)) / (sig.bw_bps as f64);
    let ceiling = raw_cost / RAW_HYSTERESIS;
    let mut best_cost = ceiling;
    let mut best = Choice::Off;

    for (idx, &level) in Level::ALL.iter().take(ONLINE_CNT).enumerate() {
      if !self.level_feasible(bidx, idx, data_len, sig) {
        continue;
      }
      let cost = self.level_cost(bidx, idx, sig);
      if cost < best_cost {
        best_cost = cost;
        best = Choice::Level(level);
      }
    }

    // Apply switch hysteresis when staying among compressed levels.
    if let (Some(Choice::Level(prev_lvl)), Choice::Level(new_lvl)) =
      (self.last_choice_li[bidx], best)
      && prev_lvl != new_lvl
      && prev_lvl.index() < ONLINE_CNT
    {
      let prev_idx = prev_lvl.index();
      if self.level_feasible(bidx, prev_idx, data_len, sig) {
        let prev_cost = self.level_cost(bidx, prev_idx, sig);
        if prev_cost <= best_cost * SWITCH_HYSTERESIS {
          return Choice::Level(prev_lvl);
        }
      }
    }

    best
  }

  fn advance_explore_slot(
    &mut self,
    bidx: usize,
    base: Choice,
    data_len: usize,
    sig: &NetSignal,
  ) -> Choice {
    // Skip speculative probe if compute backlog is already elevated.
    if sig.backlog_bytes > 0 && sig.max_queue_us > 0 {
      return base;
    }

    match base {
      Choice::Off => {
        if self.level_feasible(bidx, 0, data_len, sig)
          && self.level_spb(bidx, 0) * (sig.bw_bps as f64) <= MAX_SHIFT
        {
          Choice::Level(Level::ALL[0])
        } else {
          Choice::Off
        }
      }
      Choice::Level(cur) => {
        let i = cur.index();
        let lo = i
          .checked_sub(1)
          .filter(|&j| self.level_feasible(bidx, j, data_len, sig));
        let hi =
          (i + 1 < ONLINE_CNT && self.level_feasible(bidx, i + 1, data_len, sig)).then_some(i + 1);
        let probe = match (lo, hi) {
          (Some(a), Some(b)) => {
            match self.bucket_li[bidx].sample_li[a].cmp(&self.bucket_li[bidx].sample_li[b]) {
              Ordering::Less => a,
              Ordering::Greater => b,
              Ordering::Equal => {
                self.explore_up = !self.explore_up;
                if self.explore_up { b } else { a }
              }
            }
          }
          (Some(j), None) | (None, Some(j)) => j,
          (None, None) => return Choice::Level(cur),
        };
        Choice::Level(Level::ALL[probe])
      }
    }
  }

  fn maybe_explore_step(&mut self) -> bool {
    self.step += 1;
    if self.step < EXPLORE_INTERVAL {
      return false;
    }
    self.step = 0;
    true
  }

  /// Pre-computes per-bucket choices (`[Low, Medium, High]`) for `data_len` and `sig`,
  /// advancing exploration state without inspecting payload bytes.
  #[must_use]
  pub fn plan_buckets(&mut self, data_len: usize, sig: &NetSignal) -> [Choice; BUCKET_CNT] {
    let mut out = [
      self.plan(data_len, ContentBucket::Low, sig),
      self.plan(data_len, ContentBucket::Medium, sig),
      self.plan(data_len, ContentBucket::High, sig),
    ];
    for (bidx, &choice) in out.iter().enumerate() {
      self.last_choice_li[bidx] = Some(choice);
    }
    if sig.bw_bps > 0 && data_len >= MIN_OBSERVE && self.maybe_explore_step() {
      // Rotate exploration across Low / Medium / High so no content class starves.
      let bidx = usize::from(self.explore_bucket) % BUCKET_CNT;
      self.explore_bucket = ((bidx + 1) % BUCKET_CNT) as u8;
      out[bidx] = self.advance_explore_slot(bidx, out[bidx], data_len, sig);
    }
    out
  }

  fn pick_opt(
    &mut self,
    data_len: usize,
    bucket: ContentBucket,
    sig: &NetSignal,
    observable: bool,
  ) -> Option<EncodeOpt> {
    let bidx = bucket.index()?;
    let base = self.plan(data_len, bucket, sig);
    self.last_choice_li[bidx] = Some(base);
    let choice = if sig.bw_bps > 0 && observable && self.maybe_explore_step() {
      self.advance_explore_slot(bidx, base, data_len, sig)
    } else {
      base
    };
    match choice {
      Choice::Off => None,
      Choice::Level(level) => Some(EncodeOpt::new(level).with_max_window_log(sig.max_window_log)),
    }
  }

  /// Compresses with full [`NetSignal`] control and updates the online model.
  #[must_use]
  pub fn encode_signal(&mut self, data: &[u8], sig: &NetSignal) -> Vec<u8> {
    let raw_len = data.len();
    encode_vec_with(
      data,
      self,
      |this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
      true,
      |this, opt, bucket, wire_len, ns| {
        this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
      },
    )
  }

  /// Owned zero-copy-raw path with explicit [`NetSignal`].
  #[must_use]
  pub fn encode_owned_signal(&mut self, data: Vec<u8>, sig: &NetSignal) -> Encoded {
    let raw_len = data.len();
    encode_owned_with(
      data,
      self,
      |this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
      true,
      |this, opt, bucket, wire_len, ns| {
        this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
      },
    )
  }

  /// Reuses caller buffer `out` with explicit [`NetSignal`].
  pub fn encode_into_signal(&mut self, data: &[u8], sig: &NetSignal, out: &mut Vec<u8>) -> Type {
    let raw_len = data.len();
    encode_into_with(
      data,
      self,
      |this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
      out,
      true,
      |this, opt, bucket, wire_len, ns| {
        this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
      },
    )
  }

  /// Serial-network shorthand calling [`Self::encode_signal`] with [`NetSignal::serial`].
  #[must_use]
  pub fn encode(&mut self, data: &[u8], net_speed: u64) -> Vec<u8> {
    self.encode_signal(data, &NetSignal::serial(net_speed))
  }

  /// Serial-network shorthand calling [`Self::encode_owned_signal`].
  #[must_use]
  pub fn encode_owned(&mut self, data: Vec<u8>, net_speed: u64) -> Encoded {
    self.encode_owned_signal(data, &NetSignal::serial(net_speed))
  }

  /// Serial-network shorthand calling [`Self::encode_into_signal`].
  pub fn encode_into(&mut self, data: &[u8], net_speed: u64, out: &mut Vec<u8>) -> Type {
    self.encode_into_signal(data, &NetSignal::serial(net_speed), out)
  }

  /// Records a completed compression observation for a specific [`ContentBucket`].
  pub fn observe_bucket(
    &mut self,
    level: Level,
    bucket: ContentBucket,
    raw_len: usize,
    wire_len: usize,
    elapsed_ns: u64,
  ) {
    let Some(bidx) = bucket.index() else {
      return;
    };
    if raw_len == 0 || elapsed_ns == 0 {
      return;
    }
    let spb = (elapsed_ns as f64 * 1e-9) / (raw_len as f64);
    let ratio = (wire_len as f64) / (raw_len.saturating_add(1) as f64);
    self.observe_at(bidx, level, spb, ratio);
  }

  /// Records an external `(speed_bps, ratio)` measurement onto the default `Medium` bucket.
  pub fn observe(&mut self, level: Level, speed: f64, ratio: f64) {
    if !speed.is_finite() || speed <= 0.0 || !ratio.is_finite() {
      return;
    }
    self.observe_at(1, level, 1.0 / speed, ratio);
  }

  fn observe_at(&mut self, bidx: usize, level: Level, spb: f64, ratio: f64) {
    if !spb.is_finite() || spb <= 0.0 || !ratio.is_finite() {
      return;
    }
    let i = level.index();
    let obs_scale =
      (spb / PRIOR_TIME_SPB[i]).clamp(self.hw_scale / MAX_SHIFT, self.hw_scale * MAX_SHIFT);
    let next_scale = self.hw_scale + (obs_scale - self.hw_scale) * HW_ALPHA;
    self.hw_scale = if next_scale.is_finite() {
      next_scale.clamp(HW_SCALE_MIN, HW_SCALE_MAX)
    } else {
      1.0
    };

    {
      let b = &mut self.bucket_li[bidx];
      let cur_spb = b.spb_li[i];
      let clamped_spb = spb.clamp(
        (cur_spb / MAX_SHIFT).max(MIN_SPB),
        (cur_spb * MAX_SHIFT).min(MAX_SPB),
      );
      let n = b.sample_li[i].saturating_add(1);
      b.sample_li[i] = n;
      let weight = (1.0 / f64::from(n)).clamp(ALPHA, 0.5);

      // Log-time update preserves geometric properties across orders of magnitude.
      let ln_next = cur_spb.ln() + (clamped_spb.ln() - cur_spb.ln()) * weight;
      b.spb_li[i] = ln_next.exp().clamp(MIN_SPB, MAX_SPB);
      b.ratio_li[i] += (ratio.clamp(0.0, 1.0) - b.ratio_li[i]) * weight;

      let odds_scale = ratio_to_odds(b.ratio_li[i]) / ratio_to_odds(PRIOR_RATIO_TABLE[bidx][i]);
      for j in 0..ALL_CNT {
        if b.sample_li[j] == 0 {
          b.ratio_li[j] = odds_to_ratio(ratio_to_odds(PRIOR_RATIO_TABLE[bidx][j]) * odds_scale);
        }
      }
    }

    for bk in &mut self.bucket_li {
      bk.sync_unsampled_spb(self.hw_scale);
    }
    self.bucket_li[bidx].enforce_monotone(i);
  }

  /// Current estimates summed across buckets (reporting the dominant sampled bucket's
  /// calibrated speed and ratio) ordered as [`Level::ALL`].
  #[must_use]
  pub fn stats(&self) -> [Stat; ALL_CNT] {
    let dom = (0..BUCKET_CNT)
      .max_by_key(|&bi| {
        let sum: u32 = self.bucket_li[bi].sample_li.iter().sum();
        // Prefer `Medium` (index 1) on zero-sample ties.
        (sum, usize::from(bi == 1))
      })
      .unwrap_or(1);
    let b = &self.bucket_li[dom];
    from_fn(|i| {
      let total_cnt: u32 = self.bucket_li.iter().map(|bk| bk.sample_li[i]).sum();
      Stat {
        level: Level::ALL[i],
        speed: 1.0 / self.level_spb(dom, i),
        ratio: b.ratio_li[i],
        sample_cnt: total_cnt,
      }
    })
  }

  /// Current estimates for a specific [`ContentBucket`].
  #[must_use]
  pub fn bucket_stats(&self, bucket: ContentBucket) -> [Stat; ALL_CNT] {
    let bidx = bucket.index().unwrap_or(1);
    let b = &self.bucket_li[bidx];
    from_fn(|i| Stat {
      level: Level::ALL[i],
      speed: 1.0 / b.spb_li[i].max(MIN_SPB),
      ratio: b.ratio_li[i],
      sample_cnt: b.sample_li[i],
    })
  }
}