use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use legit_streams::{GroupBacklog, Streams, Waiting};
use serde::Serialize;
use super::Stats;
use crate::{Definition, Options, Outcome};
pub const STATS_FORMAT: u32 = 1;
pub const BACKLOG_TIMEOUT: Duration = Duration::from_secs(2);
const FIRST_BOUND_NS: u64 = 10_000;
const LAST_BOUND_NS: u64 = 600_000_000_000;
const BUCKET_RATIO: f64 = 1.09;
static BOUNDS: LazyLock<Vec<u64>> = LazyLock::new(|| {
let mut bounds = vec![FIRST_BOUND_NS];
let mut bound = FIRST_BOUND_NS as f64;
while bounds.last().is_some_and(|last| *last < LAST_BOUND_NS) {
bound *= BUCKET_RATIO;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a positive bound under 2^53"
)]
bounds.push(bound.ceil() as u64);
}
bounds
});
#[derive(Debug)]
pub(crate) struct Histogram {
buckets: Box<[AtomicU64]>,
}
impl Default for Histogram {
fn default() -> Self {
Self {
buckets: (0..=BOUNDS.len()).map(|_| AtomicU64::new(0)).collect(),
}
}
}
impl Histogram {
pub(crate) fn record(&self, elapsed: Duration) {
let nanos = u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX);
let bucket = BOUNDS.partition_point(|bound| *bound <= nanos);
self.buckets[bucket].fetch_add(1, Ordering::Relaxed);
}
pub(crate) fn take(&self) -> Vec<u64> {
self.buckets
.iter()
.map(|bucket| bucket.swap(0, Ordering::Relaxed))
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Times {
pub median_ms: f64,
pub p95_ms: f64,
pub count: u64,
}
impl Times {
#[must_use]
pub const fn new(median_ms: f64, p95_ms: f64, count: u64) -> Self {
Self {
median_ms,
p95_ms,
count,
}
}
fn from_counts(counts: &[u64]) -> Option<Self> {
let count: u64 = counts.iter().sum();
if count == 0 {
return None;
}
let at = |quantile: f64| {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a rank within `count`"
)]
let rank = ((quantile * count as f64).ceil() as u64).clamp(1, count);
let mut seen = 0;
let bucket = counts
.iter()
.position(|n| {
seen += n;
seen >= rank
})
.unwrap_or(counts.len() - 1);
bucket_ms(bucket)
};
Some(Self {
median_ms: at(0.5),
p95_ms: at(0.95),
count,
})
}
}
fn bucket_ms(bucket: usize) -> f64 {
let bounds = &*BOUNDS;
let nanos = match (bucket.checked_sub(1).and_then(|n| bounds.get(n)), bounds.get(bucket)) {
(Some(lower), Some(upper)) => (*lower as f64 * *upper as f64).sqrt(),
(None, _) => FIRST_BOUND_NS as f64,
(Some(lower), None) => *lower as f64,
};
nanos / 1e6
}
#[derive(Debug, Default)]
pub(crate) struct DefinitionCounts {
asked: [AtomicBool; Definition::ALL.len()],
computed: [AtomicU64; Definition::ALL.len()],
}
impl DefinitionCounts {
pub(crate) fn ask(&self, options: &Options) {
for entry in &options.definitions {
if let Some(n) = position(&entry.id) {
self.asked[n].store(true, Ordering::Relaxed);
}
}
}
pub(crate) fn count(&self, outcome: &Outcome) {
for hash in outcome.hashes.iter().flatten() {
if let Some(n) = position(&hash.id)
&& hash.error_type.is_none()
{
self.computed[n].fetch_add(1, Ordering::Relaxed);
}
}
}
fn snapshot(&self) -> BTreeMap<&'static str, u64> {
Definition::ALL
.iter()
.zip(self.asked.iter().zip(&self.computed))
.filter(|(_, (asked, _))| asked.load(Ordering::Relaxed))
.map(|(definition, (_, computed))| (definition.id(), computed.load(Ordering::Relaxed)))
.collect()
}
}
fn position(id: &str) -> Option<usize> {
Definition::ALL.iter().position(|definition| definition.id() == id)
}
#[derive(Debug, Clone)]
pub struct Meter {
pub(crate) counters: Arc<super::Counters>,
pub(crate) shared: Arc<super::task::Shared>,
pub(crate) started: Instant,
pub(crate) started_at: u64,
pub(crate) jobs: u64,
pub(crate) fast: bool,
}
impl Meter {
#[must_use]
pub fn stats(&self) -> Stats {
let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
let counters = &self.counters;
let (connections_opened, connections_reused, connect_retries) = self.shared.fetcher.connection_counts();
Stats {
in_flight: load(&counters.in_flight),
done: load(&counters.done),
failed: load(&counters.failed),
fast_done: load(&counters.fast_done),
fast_failed: load(&counters.fast_failed),
fetched: load(&counters.fetched),
fetched_bytes: load(&counters.fetched_bytes),
connections_opened,
connections_reused,
connect_retries,
uptime_s: self.started.elapsed().as_secs(),
}
}
#[must_use]
pub fn sample(&self) -> Sample {
let bulk_counts = self.counters.bulk_times.take();
let fast_counts = self.counters.fast_times.take();
Sample {
stats: self.stats(),
at: unix_seconds(SystemTime::now()),
started_at: self.started_at,
uptime: self.started.elapsed(),
jobs: self.jobs,
fast_lane: self.fast,
bulk_times: Times::from_counts(&bulk_counts),
fast_times: if self.fast {
Times::from_counts(&fast_counts)
} else {
None
},
definitions: self.counters.definitions.snapshot(),
bulk_counts,
fast_counts,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Sample {
pub stats: Stats,
pub at: u64,
pub started_at: u64,
pub uptime: Duration,
pub jobs: u64,
pub fast_lane: bool,
pub bulk_times: Option<Times>,
pub fast_times: Option<Times>,
pub definitions: BTreeMap<&'static str, u64>,
bulk_counts: Vec<u64>,
fast_counts: Vec<u64>,
}
impl Sample {
fn absorb(&mut self, earlier: &Self) {
for (mine, theirs) in [
(&mut self.bulk_counts, &earlier.bulk_counts),
(&mut self.fast_counts, &earlier.fast_counts),
] {
if mine.len() < theirs.len() {
mine.resize(theirs.len(), 0);
}
for (count, earlier) in mine.iter_mut().zip(theirs) {
*count += earlier;
}
}
self.bulk_times = Times::from_counts(&self.bulk_counts);
self.fast_times = if self.fast_lane {
Times::from_counts(&self.fast_counts)
} else {
None
};
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StatsState {
Running,
Stopped,
}
#[must_use]
pub fn stats_document(
sample: &Sample,
previous: Option<&Sample>,
state: StatsState,
backlog: Option<GroupBacklog>,
) -> String {
let interval = previous.map(|previous| sample.uptime.saturating_sub(previous.uptime).as_secs_f64());
let stats = &sample.stats;
let lane = |answered: u64, failed: u64, before: Option<u64>, times: Option<Times>| Lane {
answered,
failed,
rate_per_s: interval
.zip(before)
.filter(|(interval, _)| *interval > 0.0)
.map(|(interval, before)| round(answered.saturating_sub(before) as f64 / interval, 2)),
median_ms: times
.filter(|_| previous.is_some())
.map(|times| significant(times.median_ms)),
p95_ms: times
.filter(|_| previous.is_some())
.map(|times| significant(times.p95_ms)),
};
let document = Document {
format: STATS_FORMAT,
program: crate::RUNNER.name,
version: env!("CARGO_PKG_VERSION"),
state,
at: sample.at,
started_at: sample.started_at,
interval_s: interval.map(|interval| round(interval, 3)),
jobs: sample.jobs,
in_flight: stats.in_flight,
bulk: lane(
stats.done,
stats.failed,
previous.map(|previous| previous.stats.done),
sample.bulk_times,
),
fast: sample.fast_lane.then(|| {
lane(
stats.fast_done,
stats.fast_failed,
previous.map(|previous| previous.stats.fast_done),
sample.fast_times,
)
}),
fetch: Fetch {
fetched: stats.fetched,
fetched_bytes: stats.fetched_bytes,
connections_opened: stats.connections_opened,
connections_reused: stats.connections_reused,
connect_retries: stats.connect_retries,
},
definitions: &sample.definitions,
backlog: backlog.map(|backlog| {
let waiting = backlog.waiting();
Backlog {
waiting: waiting.map(Waiting::count),
waiting_exact: waiting.is_some_and(Waiting::is_exact),
pending: backlog.pending,
length: backlog.length,
}
}),
};
serde_json::to_string(&document).unwrap_or_default()
}
#[derive(Serialize)]
struct Document<'a> {
format: u32,
program: &'static str,
version: &'static str,
state: StatsState,
at: u64,
started_at: u64,
interval_s: Option<f64>,
jobs: u64,
in_flight: u64,
bulk: Lane,
fast: Option<Lane>,
fetch: Fetch,
definitions: &'a BTreeMap<&'static str, u64>,
backlog: Option<Backlog>,
}
#[derive(Serialize)]
struct Lane {
answered: u64,
failed: u64,
rate_per_s: Option<f64>,
median_ms: Option<f64>,
p95_ms: Option<f64>,
}
#[derive(Serialize)]
struct Fetch {
fetched: u64,
fetched_bytes: u64,
connections_opened: u64,
connections_reused: u64,
connect_retries: u64,
}
#[derive(Serialize)]
struct Backlog {
waiting: Option<u64>,
waiting_exact: bool,
pending: u64,
length: Option<u64>,
}
fn round(value: f64, places: i32) -> f64 {
let scale = 10f64.powi(places);
(value * scale).round() / scale
}
fn significant(value: f64) -> f64 {
if value <= 0.0 || !value.is_finite() {
return 0.0;
}
#[expect(clippy::cast_possible_truncation, reason = "the exponent of a finite time")]
let magnitude = value.log10().floor() as i32;
round(value, 2 - magnitude)
}
fn unix_seconds(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs())
}
#[derive(Debug)]
pub struct StatsFile {
path: PathBuf,
temporary: PathBuf,
previous: Option<Sample>,
unwritten: Option<Sample>,
backlog: Option<BacklogReader>,
failure: Option<io::ErrorKind>,
}
impl StatsFile {
pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
let (path, temporary) = beside(path.as_ref())?;
Ok(Self {
path,
temporary,
previous: None,
unwritten: None,
backlog: None,
failure: None,
})
}
#[must_use]
pub fn with_backlog(
mut self,
streams: Arc<dyn Streams>,
stream: impl Into<String>,
group: impl Into<String>,
) -> Self {
self.backlog = Some(BacklogReader {
streams,
stream: stream.into(),
group: group.into(),
running: None,
failure: None,
});
self
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn write(&mut self, mut sample: Sample, state: StatsState) -> io::Result<()> {
if let Some(earlier) = self.unwritten.take() {
sample.absorb(&earlier);
}
let backlog = self.backlog.as_mut().and_then(BacklogReader::read);
let mut document = stats_document(&sample, self.previous.as_ref(), state, backlog);
document.push('\n');
let written = replace(&self.temporary, &self.path, document.as_bytes());
match &written {
Ok(()) => {
self.previous = Some(sample);
self.failure = None;
}
Err(error) => {
self.unwritten = Some(sample);
if self.failure != Some(error.kind()) {
tracing::warn!(path = %self.path.display(), error = %error, "Couldn't write the stats file; the worker carries on");
}
self.failure = Some(error.kind());
}
}
written
}
}
pub(super) fn beside(path: &Path) -> io::Result<(PathBuf, PathBuf)> {
let Some(name) = path.file_name() else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path names no file"));
};
let directory = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
if !directory.is_dir() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"the directory it would be in doesn't exist",
));
}
if path.is_dir() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path is a directory"));
}
let mut temporary = name.to_os_string();
temporary.push(".tmp");
Ok((path.to_path_buf(), directory.join(temporary)))
}
pub(super) fn replace(temporary: &Path, path: &Path, bytes: &[u8]) -> io::Result<()> {
let written = (|| {
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o644);
let mut file = options.open(temporary)?;
#[cfg(unix)]
file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o644))?;
file.write_all(bytes)?;
drop(file);
fs::rename(temporary, path)
})();
if written.is_err() {
let _ = fs::remove_file(temporary);
}
written
}
type BacklogAnswer = legit_streams::Result<Option<GroupBacklog>>;
struct BacklogReader {
streams: Arc<dyn Streams>,
stream: String,
group: String,
running: Option<Receiver<BacklogAnswer>>,
failure: Option<&'static str>,
}
impl std::fmt::Debug for BacklogReader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BacklogReader")
.field("stream", &self.stream)
.field("group", &self.group)
.field("running", &self.running.is_some())
.finish_non_exhaustive()
}
}
impl BacklogReader {
fn read(&mut self) -> Option<GroupBacklog> {
let receiver = match self.running.take() {
Some(receiver) => receiver,
None => match self.start() {
Ok(receiver) => receiver,
Err(error) => {
self.failed("thread", &error);
return None;
}
},
};
match receiver.recv_timeout(BACKLOG_TIMEOUT) {
Ok(Ok(backlog)) => {
self.failure = None;
backlog
}
Ok(Err(error)) => {
self.failed(error_kind(&error), &error);
None
}
Err(RecvTimeoutError::Timeout) => {
self.running = Some(receiver);
self.failed(
"timeout",
&format_args!("no answer within {} s", BACKLOG_TIMEOUT.as_secs()),
);
None
}
Err(RecvTimeoutError::Disconnected) => {
self.failed("thread", &"the reading thread ended without an answer");
None
}
}
}
fn start(&self) -> io::Result<Receiver<BacklogAnswer>> {
let (send, receive) = mpsc::channel();
let streams = Arc::clone(&self.streams);
let (stream, group) = (self.stream.clone(), self.group.clone());
std::thread::Builder::new()
.name("legit-hasher-backlog".to_owned())
.spawn(move || {
let _ = send.send(streams.group_backlog(&stream, &group));
})?;
Ok(receive)
}
fn failed(&mut self, kind: &'static str, error: &dyn std::fmt::Display) {
if self.failure != Some(kind) {
tracing::warn!(error = %error, "Couldn't read the task stream's backlog for the stats file; it's written without");
}
self.failure = Some(kind);
}
}
const fn error_kind(error: &legit_streams::Error) -> &'static str {
match error {
legit_streams::Error::NoGroup { .. } => "no_group",
legit_streams::Error::Redis(_) => "redis",
legit_streams::Error::UnexpectedReply(_) => "unexpected_reply",
_ => "other",
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{BOUNDS, FIRST_BOUND_NS, Histogram, LAST_BOUND_NS, Times, bucket_ms, significant};
#[test]
fn every_bucket_is_at_most_a_tenth_of_its_lower_bound_wide_from_10_us_to_10_minutes() {
let bounds = &*BOUNDS;
assert_eq!(bounds[0], FIRST_BOUND_NS);
assert!(bounds[bounds.len() - 2] < LAST_BOUND_NS && bounds[bounds.len() - 1] >= LAST_BOUND_NS);
for pair in bounds.windows(2) {
assert!(pair[1] > pair[0]);
assert!((pair[1] - pair[0]) * 10 <= pair[0], "{pair:?}");
}
assert!(bounds.len() < 256, "{} buckets", bounds.len());
}
#[test]
fn a_bucket_stands_for_a_time_within_its_bounds() {
let bounds = &*BOUNDS;
for n in 1..bounds.len() {
let ms = bucket_ms(n);
assert!(ms * 1e6 >= bounds[n - 1] as f64 && ms * 1e6 <= bounds[n] as f64, "{n}");
}
assert!((bucket_ms(0) - 0.01).abs() < 1e-12);
assert!(bucket_ms(bounds.len()) * 1e6 >= LAST_BOUND_NS as f64);
}
fn exact(values: &mut [Duration], quantile: f64) -> f64 {
values.sort_unstable();
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a small rank")]
let rank = ((quantile * values.len() as f64).ceil() as usize).max(1);
values[rank - 1].as_secs_f64() * 1e3
}
#[test]
fn the_median_and_95th_percentile_are_within_a_tenth_of_the_exact_ones() {
let mut state = 0x2545_f491_4f6c_dd1d_u64;
for size in [1, 2, 3, 19, 20, 100, 1_000, 10_000] {
let histogram = Histogram::default();
let mut values = Vec::new();
for _ in 0..size {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
#[expect(clippy::cast_precision_loss, reason = "53 random bits")]
let unit = (state >> 11) as f64 / (1_u64 << 53) as f64;
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "under 2^35")]
let nanos = (20_000.0 * 1e6_f64.powf(unit)) as u64;
let elapsed = Duration::from_nanos(nanos);
histogram.record(elapsed);
values.push(elapsed);
}
let times = Times::from_counts(&histogram.take()).expect("times");
assert_eq!(times.count, size);
for (got, quantile) in [(times.median_ms, 0.5), (times.p95_ms, 0.95)] {
let want = exact(&mut values, quantile);
assert!((got - want).abs() <= want * 0.1, "{size}: {got} for {want}");
}
assert_eq!(Times::from_counts(&histogram.take()), None, "a take empties it");
}
}
#[test]
fn times_past_either_end_fall_in_the_end_buckets() {
let histogram = Histogram::default();
histogram.record(Duration::ZERO);
assert_eq!(Times::from_counts(&histogram.take()), Some(Times::new(0.01, 0.01, 1)));
histogram.record(Duration::from_secs(3_600));
let times = Times::from_counts(&histogram.take()).expect("times");
assert!(times.median_ms >= 600_000.0, "{times:?}");
}
#[test]
fn a_time_keeps_three_significant_figures() {
assert!((significant(71.432) - 71.4).abs() < 1e-9);
assert!((significant(0.031_27) - 0.0313).abs() < 1e-12);
assert!((significant(240_712.0) - 241_000.0).abs() < 1e-6);
assert!(significant(0.0).abs() < f64::EPSILON);
}
}