legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! `serve --stats-file`: what a worker has done, as one JSON document a collector beside it reads,
//! rewritten whole at every heartbeat.

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};

/// The version of the stats document: `1`. A change that isn't only a new field raises it.
pub const STATS_FORMAT: u32 = 1;

/// The longest a write waits for the task stream's backlog before it writes `"backlog": null`.
pub const BACKLOG_TIMEOUT: Duration = Duration::from_secs(2);

/// The lower bound of the first timed bucket, in nanoseconds: 0.01 ms. Faster tasks share one
/// bucket below it.
const FIRST_BOUND_NS: u64 = 10_000;

/// The bound from which every time shares one last bucket, in nanoseconds: 10 minutes.
const LAST_BOUND_NS: u64 = 600_000_000_000;

/// How much wider each bucket is than the one before: 9%, so that, rounded up to whole
/// nanoseconds, no bucket is wider than 10% of its lower bound.
const BUCKET_RATIO: f64 = 1.09;

/// The lower bound of every bucket but the first, in nanoseconds, rising: from 0.01 ms to the first
/// bound at or past 10 minutes, where the last bucket starts.
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;
        // A bound is a whole number of nanoseconds well within range...
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "a positive bound under 2^53"
        )]
        bounds.push(bound.ceil() as u64);
    }
    bounds
});

/// How long the tasks of one lane took, in fixed buckets of atomic counts: recording takes no lock,
/// and [`Histogram::take`] empties it for the next interval.
#[derive(Debug)]
pub(crate) struct Histogram {
    /// One count per bucket: below the first bound, then one per bound.
    buckets: Box<[AtomicU64]>,
}

impl Default for Histogram {
    fn default() -> Self {
        Self {
            buckets: (0..=BOUNDS.len()).map(|_| AtomicU64::new(0)).collect(),
        }
    }
}

impl Histogram {
    /// Count one task that took `elapsed`.
    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);
    }

    /// 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(&self) -> Vec<u64> {
        self.buckets
            .iter()
            .map(|bucket| bucket.swap(0, Ordering::Relaxed))
            .collect()
    }
}

/// The median and 95th percentile of the time tasks took over an interval, each accurate to within
/// 10%.
///
/// ```
/// let times = legit_hasher::serve::Times::new(71.0, 240.0, 1_000);
/// assert!(times.median_ms < times.p95_ms);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Times {
    /// The median, in milliseconds.
    pub median_ms: f64,
    /// The 95th percentile, in milliseconds.
    pub p95_ms: f64,
    /// How many tasks the two figures are of.
    pub count: u64,
}

impl Times {
    /// Times with these figures, for a test or a document of your own.
    #[must_use]
    pub const fn new(median_ms: f64, p95_ms: f64, count: u64) -> Self {
        Self {
            median_ms,
            p95_ms,
            count,
        }
    }

    /// The figures of a histogram's counts, by nearest rank: the time of the bucket holding the
    /// task at that rank, taken as the geometric middle of its bounds.
    fn from_counts(counts: &[u64]) -> Option<Self> {
        let count: u64 = counts.iter().sum();
        if count == 0 {
            return None;
        }
        let at = |quantile: f64| {
            // The nearest rank, from 1 to `count`...
            #[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,
        })
    }
}

/// The time a bucket stands for, in milliseconds: the geometric middle of its bounds, the first
/// bound for the bucket below it, and the last bound for the bucket past it.
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
}

/// For each definition the runner offers, whether a task's `options` has asked for it, whatever
/// became of the task, and how many values it has computed without an error. Indexed as
/// [`Definition::ALL`], so no id a task sends is ever kept.
#[derive(Debug, Default)]
pub(crate) struct DefinitionCounts {
    asked: [AtomicBool; Definition::ALL.len()],
    computed: [AtomicU64; Definition::ALL.len()],
}

impl DefinitionCounts {
    /// Note the definitions a task's `options` asks for, before anything can fail: a fetch, a
    /// decode or the definition itself.
    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);
            }
        }
    }

    /// Count the values a hashed request computed without an error.
    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()
    }
}

/// Where a definition id is in [`Definition::ALL`], or `None` for an id the runner doesn't offer.
fn position(id: &str) -> Option<usize> {
    Definition::ALL.iter().position(|definition| definition.id() == id)
}

/// A handle on a [`Server`](super::Server)'s counts that outlives it, so the last stats document
/// can be written after the workers have stopped: see [`Server::meter`](super::Server::meter).
#[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 {
    /// What the server has done so far, as [`Server::stats`](super::Server::stats) gives it.
    #[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(),
        }
    }

    /// Everything the stats document reports. Each call ends an interval: the times it gives are of
    /// the tasks answered since the previous call, and the next call's start from zero. Take one
    /// sample per document.
    #[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,
        }
    }
}

/// What a [`Meter`] read at one moment: the input of [`stats_document`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Sample {
    /// The counts since the server started.
    pub stats: Stats,
    /// When the sample was taken, in Unix seconds.
    pub at: u64,
    /// When the server started, in Unix seconds.
    pub started_at: u64,
    /// How long the server had run, by the monotonic clock: two samples' difference is the length
    /// of the interval between them.
    pub uptime: Duration,
    /// How many bulk tasks the server runs at once.
    pub jobs: u64,
    /// Whether the server serves a fast lane.
    pub fast_lane: bool,
    /// How long the bulk tasks answered since the previous sample took; `None` when there were
    /// none.
    pub bulk_times: Option<Times>,
    /// The same, on the fast lane.
    pub fast_times: Option<Times>,
    /// How many values each definition asked for has computed without an error, both lanes
    /// together. A definition never asked for is absent.
    pub definitions: BTreeMap<&'static str, u64>,
    /// The histogram buckets `bulk_times` and `fast_times` were read from, so a sample whose
    /// document wasn't written can be added to the next.
    bulk_counts: Vec<u64>,
    fast_counts: Vec<u64>,
}

impl Sample {
    /// Add the times of an earlier sample, whose document wasn't written, to this one's, so the
    /// next document's times cover its whole interval.
    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
        };
    }
}

/// Whether the worker is running or has stopped, as the stats document's `state` says.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StatsState {
    /// The workers are running: every document but the last.
    Running,
    /// The workers have stopped: the last document.
    Stopped,
}

/// The stats document, format 1, as one line of JSON without the newline: what `serve
/// --stats-file` writes. `previous` is the sample of the document before, `None` for the first,
/// and `backlog` the task stream's, `None` when it couldn't be read.
///
/// It holds numbers, the program's name and version, `state` and the ids of the definitions the
/// runner offers, and nothing else: no name of a stream, group, consumer, host or application, no
/// URL or address, no error's text and no hash.
///
/// ```
/// use std::sync::Arc;
/// use legit_hasher::serve::{ServeConfig, Server, StatsState, stats_document};
/// use legit_streams::{MemoryStreams, Streams};
///
/// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
/// let server = Server::start(ServeConfig::new("hasher-1", 7), streams, None)?;
/// let meter = server.meter();
/// let first = meter.sample();
/// let document: serde_json::Value = serde_json::from_str(&stats_document(&first, None, StatsState::Running, None))?;
/// assert_eq!(document["format"], 1);
/// assert!(document["interval_s"].is_null());
/// server.stop();
/// server.join()?;
/// let last = meter.sample();
/// let document: serde_json::Value = serde_json::from_str(&stats_document(&last, Some(&first), StatsState::Stopped, None))?;
/// assert_eq!(document["state"], "stopped");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[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,
        // Undefined over an interval of no length...
        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,
            }
        }),
    };
    // Numbers, fixed names and the ids of `Definition::ALL` only, so serializing can't fail...
    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,
}

/// The stats document's `backlog`: `waiting` is the server's lag when it gives one and otherwise
/// the estimate from the stream's length, `waiting_exact` says which, and `length` is the stream's
/// length when it was read.
#[derive(Serialize)]
struct Backlog {
    waiting: Option<u64>,
    waiting_exact: bool,
    pending: u64,
    length: Option<u64>,
}

/// `value` rounded to `places` decimal places.
fn round(value: f64, places: i32) -> f64 {
    let scale = 10f64.powi(places);
    (value * scale).round() / scale
}

/// `value` to three significant figures: a time is accurate to within 10%, and more figures would
/// claim more.
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())
}

/// Where `serve --stats-file` writes, and what it remembers between writes: the sample of the last
/// document written, the samples since whose documents weren't, the task stream whose backlog it
/// reads, and the last failure it logged.
///
/// Each write is whole: the document goes to the file's name plus `.tmp` in the same directory,
/// with mode 0644, and is then renamed over the file, so a reader never sees half of one. A write
/// that fails removes the temporary file, and is logged at warning level when it's the first
/// failure since a success or its error's kind differs from the last one's. It leaves the file as
/// it was, and the next document written covers the interval since the one in the file: its rates
/// and times include the tasks of the failed write's sample. Until a first document is written,
/// the next is a first document, with no interval.
///
/// ```
/// use std::sync::Arc;
/// use legit_hasher::serve::{ServeConfig, Server, StatsFile, StatsState};
/// use legit_streams::{MemoryStreams, Streams};
///
/// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
/// // The worker creates its group as it starts; created here, the first write can read it.
/// streams.xgroup_create("hash_tasks", "hash_workers")?;
/// let server = Server::start(ServeConfig::new("hasher-1", 7), Arc::clone(&streams), None)?;
/// let path = std::env::temp_dir().join(format!("legit-hasher-doc-{}.json", std::process::id()));
/// let mut file = StatsFile::new(&path)?.with_backlog(streams, "hash_tasks", "hash_workers");
/// file.write(server.meter().sample(), StatsState::Running)?;
/// let document: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
/// assert_eq!(document["backlog"]["pending"], 0);
/// # std::fs::remove_file(&path)?;
/// server.stop();
/// server.join()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct StatsFile {
    path: PathBuf,
    temporary: PathBuf,
    /// The sample of the last document written.
    previous: Option<Sample>,
    /// The samples taken since, whose documents failed, added together.
    unwritten: Option<Sample>,
    backlog: Option<BacklogReader>,
    /// The kind of the last failed write, until a write succeeds.
    failure: Option<io::ErrorKind>,
}

impl StatsFile {
    /// A stats file at `path`. Nothing is written until [`StatsFile::write`].
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::NotFound`] when the directory `path` would be in doesn't exist, and
    /// [`io::ErrorKind::InvalidInput`] when `path` names no file, such as one ending in `..`, or
    /// names a directory.
    ///
    /// ```
    /// use legit_hasher::serve::StatsFile;
    ///
    /// assert!(StatsFile::new(std::env::temp_dir().join("stats.json")).is_ok());
    /// assert!(StatsFile::new("/no/such/directory/stats.json").is_err());
    /// ```
    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,
        })
    }

    /// Read the backlog of `group` on the task stream `stream` once per write, with
    /// [`Streams::group_backlog`] on `streams`, waiting at most [`BACKLOG_TIMEOUT`]. Give it a
    /// connection of its own, not the workers': a read that's slow then delays no task, and a read
    /// still running at the next write is waited for rather than started again.
    #[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
    }

    /// The file's path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Write the document of `sample`, against the last document written, and keep `sample` as
    /// the previous one for the next once it's written.
    ///
    /// # Errors
    ///
    /// The error of creating, writing or renaming the temporary file, which is removed. The next
    /// write tries again, covering this one's interval too; the failure is logged as [`StatsFile`]
    /// says.
    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
    }
}

/// `path` and the temporary file beside it, its name plus `.tmp` in the same directory: the
/// errors of [`StatsFile::new`] when the directory doesn't exist or `path` names no file.
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)))
}

/// Write `bytes` to `temporary` and rename it over `path`, removing `temporary` on a failure.
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)?;
        // Whatever the umask, or the mode of a temporary file a crash left behind...
        #[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
}

/// The answer of one backlog read.
type BacklogAnswer = legit_streams::Result<Option<GroupBacklog>>;

/// Reads a task stream's backlog on a thread of its own, so a write waits for it at most
/// [`BACKLOG_TIMEOUT`].
struct BacklogReader {
    streams: Arc<dyn Streams>,
    stream: String,
    group: String,
    /// A read that outlasted its write's wait, still running.
    running: Option<Receiver<BacklogAnswer>>,
    /// What the last failed read failed with, until one succeeds.
    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 {
    /// The backlog, or `None` when it couldn't be read in time or the streams can't tell.
    fn read(&mut self) -> Option<GroupBacklog> {
        let receiver = match self.running.take() {
            // An earlier read still running: wait for it, rather than pile another on...
            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);
    }
}

/// A stable name for the kind of a failed read, to log a failure again only when its kind changes.
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);
    }

    /// The nearest-rank percentile of `values`, in milliseconds.
    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() {
        // A fixed pseudo-random spread from 20 us to 20 s...
        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;
                // Log-uniform over six orders of magnitude...
                #[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);
    }
}