legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! What a server has done, for its heartbeat and its stats file: counts by task and error, queries,
//! candidates, cuts, and latencies by lane.

use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};

use serde::Serialize;

use crate::service::{Counts, ErrorType, Lane};

/// The codes counted besides the service's own.
const OTHER_CODES: [&str; 1] = ["other"];

/// Buckets of the latency histogram: below 8 µs one a microsecond, then eight a power of two.
const BUCKETS: usize = 512;

#[derive(Debug)]
pub(crate) struct Metrics {
    pub(crate) in_flight: AtomicU64,
    /// Quick requests being handled now: the heartbeat's `in_flight` is the bulk lane's alone, the
    /// stats file's both lanes'.
    pub(crate) fast_in_flight: AtomicU64,
    search: AtomicU64,
    stats: AtomicU64,
    append: AtomicU64,
    replace: AtomicU64,
    remove: AtomicU64,
    other: AtomicU64,
    errors: [AtomicU64; ErrorType::ALL.len() + OTHER_CODES.len()],
    queries: AtomicU64,
    candidates: AtomicU64,
    cut_limit: AtomicU64,
    cut_time: AtomicU64,
    cut_size: AtomicU64,
    fast: Histogram,
    bulk: Histogram,
    /// What the stats file reports, kept apart from the heartbeat's so neither empties the other's
    /// histograms.
    pub(crate) file: FileCounts,
}

/// The counts only the stats file reports.
#[derive(Debug, Default)]
pub(crate) struct FileCounts {
    /// Bulk tasks answered, and of them those answered with an error.
    pub(crate) bulk_answered: AtomicU64,
    pub(crate) bulk_failed: AtomicU64,
    /// The same on the fast lane.
    pub(crate) fast_answered: AtomicU64,
    pub(crate) fast_failed: AtomicU64,
    /// Tasks answered with an error, by name, indexed as [`Name::ALL`].
    pub(crate) failed: [AtomicU64; Name::ALL.len()],
    /// Matches returned by searches.
    pub(crate) matches: AtomicU64,
    /// Queries whose reply was cut, by limit, size or time.
    pub(crate) incomplete: AtomicU64,
    /// How long the tasks of each lane took, since the stats file's last sample.
    pub(crate) bulk_times: Histogram,
    pub(crate) fast_times: Histogram,
}

impl Default for Metrics {
    fn default() -> Self {
        Self {
            in_flight: AtomicU64::new(0),
            fast_in_flight: AtomicU64::new(0),
            search: AtomicU64::new(0),
            stats: AtomicU64::new(0),
            append: AtomicU64::new(0),
            replace: AtomicU64::new(0),
            remove: AtomicU64::new(0),
            other: AtomicU64::new(0),
            errors: std::array::from_fn(|_| AtomicU64::new(0)),
            queries: AtomicU64::new(0),
            candidates: AtomicU64::new(0),
            cut_limit: AtomicU64::new(0),
            cut_time: AtomicU64::new(0),
            cut_size: AtomicU64::new(0),
            fast: Histogram::default(),
            bulk: Histogram::default(),
            file: FileCounts::default(),
        }
    }
}

/// Which task a task was, by its `task_name`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Name {
    Search,
    Stats,
    Append,
    Replace,
    Remove,
    Other,
}

impl Name {
    /// Every name a task is counted under, `Other` last.
    pub(crate) const ALL: [Self; 6] = [
        Self::Search,
        Self::Stats,
        Self::Append,
        Self::Replace,
        Self::Remove,
        Self::Other,
    ];

    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Search => "search",
            Self::Stats => "stats",
            Self::Append => "append",
            Self::Replace => "replace",
            Self::Remove => "remove",
            Self::Other => "other",
        }
    }

    /// Whether it changes an index: `append`, `replace` or `remove`.
    pub(crate) const fn is_change(self) -> bool {
        matches!(self, Self::Append | Self::Replace | Self::Remove)
    }
}

impl Metrics {
    pub(crate) fn task(&self, name: Name, lane: Lane, micros: u64, error_type: Option<&str>, counts: Counts) {
        let add = |counter: &AtomicU64, by: u64| counter.fetch_add(by, Ordering::Relaxed);
        add(
            match name {
                Name::Search => &self.search,
                Name::Stats => &self.stats,
                Name::Append => &self.append,
                Name::Replace => &self.replace,
                Name::Remove => &self.remove,
                Name::Other => &self.other,
            },
            1,
        );
        let file = &self.file;
        let (answered, failed, times) = match lane {
            Lane::Fast => (&file.fast_answered, &file.fast_failed, &file.fast_times),
            Lane::Bulk => (&file.bulk_answered, &file.bulk_failed, &file.bulk_times),
        };
        add(answered, 1);
        times.record(micros);
        if error_type.is_some() {
            add(failed, 1);
            if let Some(index) = Name::ALL.iter().position(|known| *known == name) {
                add(&file.failed[index], 1);
            }
        }
        add(&file.matches, counts.matches);
        add(&file.incomplete, counts.cut_limit + counts.cut_time + counts.cut_size);
        if let Some(code) = error_type {
            let index = ErrorType::ALL
                .iter()
                .map(|error| error.as_str())
                .chain(OTHER_CODES)
                .position(|known| known == code)
                .unwrap_or(self.errors.len() - 1);
            add(&self.errors[index], 1);
        }
        add(&self.queries, counts.queries);
        add(&self.candidates, counts.candidates);
        add(&self.cut_limit, counts.cut_limit);
        add(&self.cut_time, counts.cut_time);
        add(&self.cut_size, counts.cut_size);
        match lane {
            Lane::Fast => self.fast.record(micros),
            Lane::Bulk => self.bulk.record(micros),
        }
    }

    /// Tasks answered since the start, by name, indexed as [`Name::ALL`].
    pub(crate) fn answered(&self) -> [u64; Name::ALL.len()] {
        let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
        [
            load(&self.search),
            load(&self.stats),
            load(&self.append),
            load(&self.replace),
            load(&self.remove),
            load(&self.other),
        ]
    }

    /// Query values searched since the start.
    pub(crate) fn queries(&self) -> u64 {
        self.queries.load(Ordering::Relaxed)
    }

    pub(crate) fn heartbeat(&self, uptime_s: u64) -> Heartbeat {
        let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
        let errors = ErrorType::ALL
            .iter()
            .map(|error| error.as_str())
            .chain(OTHER_CODES)
            .zip(&self.errors)
            .map(|(code, count)| (code, load(count)))
            .filter(|&(_, count)| count > 0)
            .collect();
        Heartbeat {
            uptime_s,
            in_flight: load(&self.in_flight),
            tasks: TaskCounts {
                search: load(&self.search),
                stats: load(&self.stats),
                append: load(&self.append),
                replace: load(&self.replace),
                remove: load(&self.remove),
                other: load(&self.other),
            },
            errors,
            queries: load(&self.queries),
            candidates: load(&self.candidates),
            cut_limit: load(&self.cut_limit),
            cut_time: load(&self.cut_time),
            cut_size: load(&self.cut_size),
            fast: self.fast.take(),
            bulk: self.bulk.take(),
        }
    }
}

/// Tasks answered, by `task_name`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct TaskCounts {
    /// `search` tasks.
    pub search: u64,
    /// `stats` tasks.
    pub stats: u64,
    /// `append` tasks.
    pub append: u64,
    /// `replace` tasks.
    pub replace: u64,
    /// `remove` tasks.
    pub remove: u64,
    /// Tasks of any other name, each answered `invalid_task`.
    pub other: u64,
}

/// Latencies of one lane over the interval since the last heartbeat.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
#[non_exhaustive]
pub struct Latency {
    /// Tasks answered in the interval.
    pub count: u64,
    /// The median time a task took in the worker, in milliseconds, to within an eighth.
    pub p50_ms: f64,
    /// The 99th percentile, the same way.
    pub p99_ms: f64,
}

/// What a server has done, as its heartbeat line reports it.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Heartbeat {
    /// Seconds since the server started.
    pub uptime_s: u64,
    /// Bulk tasks being handled now.
    pub in_flight: u64,
    /// Tasks answered since it started, by name.
    pub tasks: TaskCounts,
    /// Error results since it started, by `error_type`; codes never given are left out.
    pub errors: BTreeMap<&'static str, u64>,
    /// Query values searched.
    pub queries: u64,
    /// Candidates read: records compared or table entries read.
    pub candidates: u64,
    /// Queries cut by a caller's `limit`.
    pub cut_limit: u64,
    /// Queries cut by the time budget.
    pub cut_time: u64,
    /// Queries cut by the size budget.
    pub cut_size: u64,
    /// The fast lane's latencies since the last heartbeat.
    pub fast: Latency,
    /// The bulk lane's latencies since the last heartbeat.
    pub bulk: Latency,
}

/// How long tasks took, in buckets of atomic counts: recording takes no lock.
#[derive(Debug)]
pub(crate) struct Histogram {
    buckets: Box<[AtomicU64; BUCKETS]>,
}

impl Default for Histogram {
    fn default() -> Self {
        Self {
            buckets: Box::new(std::array::from_fn(|_| AtomicU64::new(0))),
        }
    }
}

impl Histogram {
    fn record(&self, micros: u64) {
        self.buckets[bucket(micros)].fetch_add(1, Ordering::Relaxed);
    }

    /// The count of each bucket since the last take, emptying it. A task recorded while this runs
    /// is counted in this take or the next.
    pub(crate) fn take_counts(&self) -> Vec<u64> {
        self.buckets
            .iter()
            .map(|bucket| bucket.swap(0, Ordering::Relaxed))
            .collect()
    }

    /// The interval's latencies, starting a new interval.
    fn take(&self) -> Latency {
        let counts: Vec<u64> = self
            .buckets
            .iter()
            .map(|bucket| bucket.swap(0, Ordering::Relaxed))
            .collect();
        let count: u64 = counts.iter().sum();
        let at = |fraction: f64| -> f64 {
            #[expect(
                clippy::cast_precision_loss,
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss
            )]
            let rank = ((count as f64 * fraction).ceil() as u64).max(1);
            let mut seen = 0;
            for (index, &bucket_count) in counts.iter().enumerate() {
                seen += bucket_count;
                if seen >= rank {
                    #[expect(clippy::cast_precision_loss, reason = "a latency for a person to read")]
                    return upper(index) as f64 / 1000.0;
                }
            }
            0.0
        };
        if count == 0 {
            return Latency::default();
        }
        Latency {
            count,
            p50_ms: at(0.5),
            p99_ms: at(0.99),
        }
    }
}

/// The bucket of a latency in microseconds.
fn bucket(micros: u64) -> usize {
    if micros < 8 {
        return micros as usize;
    }
    let power = 63 - micros.leading_zeros() as usize;
    let sub = ((micros >> (power - 3)) & 7) as usize;
    ((power - 2) * 8 + sub).min(BUCKETS - 1)
}

/// The smallest latency a bucket holds, in microseconds.
pub(crate) const fn lower(index: usize) -> u64 {
    if index < 8 {
        return index as u64;
    }
    let (power, sub) = (index / 8 + 2, (index % 8) as u64);
    (8 + sub) << (power - 3)
}

/// The largest latency a bucket holds, in microseconds.
pub(crate) fn upper(index: usize) -> u64 {
    if index < 8 {
        return index as u64;
    }
    let (power, sub) = (index / 8 + 2, (index % 8) as u64);
    ((9 + sub) << (power - 3)).saturating_sub(1)
}

#[cfg(test)]
mod tests {
    use super::{bucket, lower, upper};

    #[test]
    fn each_latency_is_within_its_bucket() {
        for micros in [0, 1, 7, 8, 9, 15, 16, 17, 100, 1_000, 2_047, 2_048, 123_456_789] {
            let index = bucket(micros);
            assert!(upper(index) >= micros, "{micros} is above its bucket's top");
            assert!(lower(index) <= micros, "{micros} is below its bucket's bottom");
            assert!(
                index == 0 || upper(index - 1) < micros,
                "{micros} belongs in an earlier bucket"
            );
        }
    }
}