autozstd 0.2.0

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation
use std::{array::from_fn, cmp::Ordering};

use crate::{
  Encoded, Level, Type,
  encode::{Plan, compress_into_timed, compress_payload_into_timed, plan, raw, raw_into, shrink},
};

/// Number of presets.
const N: usize = Level::ALL.len();
/// Initial compression speed estimates in uncompressed bytes per second.
const PRIOR_SPEED_LI: [f64; N] = [2.5e8, 1.2e8, 5.0e7, 2.0e7, 4.0e6];
/// Initial wire ratio estimates: compressed envelope over raw envelope size.
const PRIOR_RATIO_LI: [f64; N] = [0.60, 0.52, 0.45, 0.40, 0.35];
/// Initial odds `r / (1 - r)` derived from `PRIOR_RATIO_LI` at compile time.
const PRIOR_ODDS_LI: [f64; N] = prior_odds();
/// Steady-state EWMA weight (warm-up observations decay monotonically as `1 / n`).
const ALPHA: f64 = 0.2;
/// A speed sample is clamped to this factor around the current estimate.
const MAX_SHIFT: f64 = 4.0;
/// Lower bound on speed estimates (bytes/s) to prevent underflow.
const MIN_SPEED: f64 = 1.0;
/// Upper bound on speed estimates (bytes/s) to prevent overflow.
const MAX_SPEED: f64 = 1e12;
/// Lower clamp on wire ratio before odds conversion.
const RATIO_MIN: f64 = 1e-6;
/// Upper clamp on wire ratio before odds conversion.
const RATIO_MAX: f64 = 1.0 - RATIO_MIN;
/// Minimum speed-up over sending raw bytes; below it the raw path wins.
const MIN_SPEEDUP: f64 = 1.05;
/// Normalized cost ceiling (`net_speed / speed + ratio <= MAX_COST`) to beat raw.
const MAX_COST: f64 = 1.0 / MIN_SPEEDUP;
/// Observable encodes between exploration probes.
const EXPLORE_INTERVAL: u32 = 64;

const fn prior_odds() -> [f64; N] {
  let mut out = [0.0; N];
  let mut i = 0;
  while i < N {
    let r = PRIOR_RATIO_LI[i];
    out[i] = r / (1.0 - r);
    i += 1;
  }
  out
}

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

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

/// 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 envelope size, both
  /// including the type byte.
  pub ratio: f64,
  /// Number of measurements folded into this estimate.
  pub sample_cnt: u32,
}

/// Network-aware level chooser that learns from previous calls.
///
/// Each call that keeps a compressed frame records the compression speed and
/// wire ratio of the level it chose. [`choice`](Self::choice) minimizes the
/// normalized transfer cost `net_speed / speed + ratio` against `1 / 1.05` and
/// picks the fastest option.
#[derive(Debug, Clone)]
pub struct Adaptive {
  speed_li: [f64; N],
  ratio_li: [f64; N],
  sample_li: [u32; N],
  step: u32,
  explore_up: bool,
}

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

impl Adaptive {
  /// Creates an instance with built-in priors; observations replace them.
  #[must_use]
  pub const fn new() -> Self {
    Self {
      speed_li: PRIOR_SPEED_LI,
      ratio_li: PRIOR_RATIO_LI,
      sample_li: [0; N],
      step: 0,
      explore_up: true,
    }
  }

  /// Returns the mode for a network speed in bytes per second.
  ///
  /// `0` means the network speed is unknown and selects [`Level::Balanced`].
  #[must_use]
  pub fn choice(&self, net_speed: u64) -> Choice {
    if net_speed == 0 {
      return Choice::Level(Level::Balanced);
    }

    let net = net_speed as f64;
    let mut best_cost = MAX_COST;
    let mut best = Choice::Off;

    for ((level, speed), ratio) in Level::ALL.into_iter().zip(self.speed_li).zip(self.ratio_li) {
      // Compression and transfer are treated as serial.
      let cost = net / speed + ratio;
      if cost < best_cost {
        best_cost = cost;
        best = Choice::Level(level);
      }
    }

    best
  }

  /// Picks a level, periodically probing a feasible neighbor or `Fastest` to
  /// prevent stale estimates from locking out better modes.
  fn pick(&mut self, net_speed: u64, observable: bool) -> Choice {
    let base = self.choice(net_speed);
    if net_speed == 0 || !observable {
      return base;
    }

    self.step += 1;
    if self.step < EXPLORE_INTERVAL {
      return base;
    }
    self.step = 0;

    let min_speed = net_speed as f64 * MIN_SPEEDUP;
    let feasible = |idx: usize| self.speed_li[idx] * MAX_SHIFT >= min_speed;

    match base {
      Choice::Off => {
        if feasible(0) {
          Choice::Level(Level::Fastest)
        } else {
          Choice::Off
        }
      }
      Choice::Level(cur) => {
        let i = cur.index();
        let lo = i.checked_sub(1).filter(|&j| feasible(j));
        let hi = (i + 1 < N && feasible(i + 1)).then_some(i + 1);
        let probe = match (lo, hi) {
          (Some(a), Some(b)) => match self.sample_li[a].cmp(&self.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])
      }
    }
  }

  /// Compresses with the level chosen for `net_speed` and records the result.
  ///
  /// `net_speed` is in bytes per second; `0` selects [`Level::Balanced`] and
  /// still records measurements, which is useful for training the model.
  /// Raw fallbacks and inputs below 8 KiB are not recorded.
  #[must_use]
  pub fn encode(&mut self, data: &[u8], net_speed: u64) -> Vec<u8> {
    match plan(data, |observable| self.decide(net_speed, observable)) {
      Plan::Raw => raw(data),
      Plan::Zstd(level) => {
        let mut out = Vec::new();
        let (compressed, elapsed) = compress_into_timed(data, level, &mut out);
        if compressed {
          self.record(level, data.len(), out.len(), elapsed);
        } else {
          raw_into(&mut out, data);
        }
        shrink(&mut out);
        out
      }
    }
  }

  /// Encodes an owned buffer and records the result like [`Self::encode`].
  ///
  /// Raw decisions return the input allocation unchanged, so no payload bytes
  /// are copied. Use [`Encoded::into_parts`] to write the tag and payload as two
  /// owned buffers.
  #[must_use]
  pub fn encode_owned(&mut self, data: Vec<u8>, net_speed: u64) -> Encoded {
    match plan(&data, |observable| self.decide(net_speed, observable)) {
      Plan::Raw => Encoded::raw(data),
      Plan::Zstd(level) => {
        let mut out = Vec::new();
        let (compressed, elapsed) = compress_payload_into_timed(&data, level, &mut out);
        if compressed {
          // `out` is a bare frame; the envelope adds the type byte.
          self.record(level, data.len(), out.len() + 1, elapsed);
          shrink(&mut out);
          Encoded::zstd(out)
        } else {
          Encoded::raw(data)
        }
      }
    }
  }

  /// Encodes into `out` and records the result like [`Self::encode`].
  ///
  /// The buffer is reused across calls; `out` holds a complete envelope on
  /// return.
  pub fn encode_into(&mut self, data: &[u8], net_speed: u64, out: &mut Vec<u8>) -> Type {
    match plan(data, |observable| self.decide(net_speed, observable)) {
      Plan::Raw => {
        raw_into(out, data);
        Type::Raw
      }
      Plan::Zstd(level) => {
        let (compressed, elapsed) = compress_into_timed(data, level, out);
        if compressed {
          self.record(level, data.len(), out.len(), elapsed);
          Type::Zstd
        } else {
          raw_into(out, data);
          Type::Raw
        }
      }
    }
  }

  #[inline]
  fn decide(&mut self, net_speed: u64, observable: bool) -> Option<Level> {
    match self.pick(net_speed, observable) {
      Choice::Off => None,
      Choice::Level(level) => Some(level),
    }
  }

  /// Folds a kept compressed frame into the model; raw fallbacks never reach
  /// here. `wire_len` is the complete envelope length, tag included.
  fn record(&mut self, level: Level, raw_len: usize, wire_len: usize, elapsed: Option<f64>) {
    if let Some(elapsed) = elapsed
      && elapsed > 0.0
    {
      self.observe(
        level,
        raw_len as f64 / elapsed,
        wire_len as f64 / (raw_len + 1) as f64,
      );
    }
  }

  fn scale_unmeasured(
    &mut self,
    range: impl Iterator<Item = usize>,
    speed_scale: f64,
    odds_scale: f64,
  ) {
    for j in range {
      if self.sample_li[j] != 0 {
        break;
      }
      self.speed_li[j] = (PRIOR_SPEED_LI[j] * speed_scale).clamp(MIN_SPEED, MAX_SPEED);
      self.ratio_li[j] = odds_to_ratio(PRIOR_ODDS_LI[j] * odds_scale);
    }
  }

  /// Records a compression measurement for `level` and updates estimates.
  ///
  /// Non-finite or non-positive speeds and non-finite ratios are ignored.
  /// Unmeasured neighbor levels scale proportionally to keep relative priors
  /// calibrated while maintaining monotonic ordering across all presets.
  pub fn observe(&mut self, level: Level, speed: f64, ratio: f64) {
    if !speed.is_finite() || speed <= 0.0 || !ratio.is_finite() {
      return;
    }

    let i = level.index();
    let est = self.speed_li[i];
    // Clamp the sample to a factor of the estimate so one scheduler stall
    // cannot collapse the table while sustained shifts still converge.
    let clamped = speed.clamp(
      (est / MAX_SHIFT).max(MIN_SPEED),
      (est * MAX_SHIFT).min(MAX_SPEED),
    );

    let n = self.sample_li[i].saturating_add(1);
    self.sample_li[i] = n;
    // Smoothly decay warm-up weight from 0.5 down to ALPHA without jumps.
    let weight = (1.0 / f64::from(n)).clamp(ALPHA, 0.5);
    self.speed_li[i] += (clamped - est) * weight;
    self.ratio_li[i] += (ratio.clamp(0.0, 1.0) - self.ratio_li[i]) * weight;

    // Scale contiguous unmeasured neighbors proportionally so calibrating one
    // level (e.g. via net_speed = 0) updates priors across adjacent levels.
    let speed_scale = self.speed_li[i] / PRIOR_SPEED_LI[i];
    let odds_scale = ratio_to_odds(self.ratio_li[i]) / PRIOR_ODDS_LI[i];
    self.scale_unmeasured((0..i).rev(), speed_scale, odds_scale);
    self.scale_unmeasured((i + 1)..N, speed_scale, odds_scale);

    // Enforce global monotonicity outward from `i`: faster levels are never
    // slower and never achieve a lower ratio.
    for j in (0..i).rev() {
      self.speed_li[j] = self.speed_li[j].max(self.speed_li[j + 1]);
      self.ratio_li[j] = self.ratio_li[j].max(self.ratio_li[j + 1]);
    }
    for j in (i + 1)..N {
      self.speed_li[j] = self.speed_li[j].min(self.speed_li[j - 1]);
      self.ratio_li[j] = self.ratio_li[j].min(self.ratio_li[j - 1]);
    }
  }

  /// Current estimates, ordered as [`Level::ALL`].
  ///
  /// Faster levels are never slower and never compress better.
  #[must_use]
  pub fn stats(&self) -> [Stat; N] {
    from_fn(|i| Stat {
      level: Level::ALL[i],
      speed: self.speed_li[i],
      ratio: self.ratio_li[i],
      sample_cnt: self.sample_li[i],
    })
  }
}