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
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
//! `serve --stats-file`: what a worker has done and what it serves, as one JSON document of numbers
//! a collector beside it reads, rewritten whole at start, at every heartbeat and at stop.

use std::fs::{self, OpenOptions};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use legit_streams::{GroupBacklog, Streams};
use serde::Serialize;

use super::metrics::{self, Metrics, Name};
use crate::service::{Service, Totals};

/// 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 bulk group's backlog before it writes `"backlog": null`.
pub const BACKLOG_TIMEOUT: Duration = Duration::from_secs(2);

/// The median, 95th and 99th percentiles of the time the worker took over tasks of one lane, over
/// an interval, in microseconds.
///
/// Each is the middle of the histogram bucket holding the task at that rank, by nearest rank. A
/// task's time is measured in whole microseconds; below 8 µs each microsecond has its bucket, and
/// above, each power of two is split into eight, so a figure is within a sixteenth (6.25%) of the
/// time of a task in its bucket.
///
/// ```
/// let times = legit_hamming::serve::Times::new(180, 420, 910, 1_000);
/// assert!(times.median_us < times.p95_us && times.p95_us < times.p99_us);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Times {
    /// The median, in microseconds.
    pub median_us: u64,
    /// The 95th percentile, in microseconds.
    pub p95_us: u64,
    /// The 99th percentile, in microseconds.
    pub p99_us: u64,
    /// How many tasks the 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_us: u64, p95_us: u64, p99_us: u64, count: u64) -> Self {
        Self {
            median_us,
            p95_us,
            p99_us,
            count,
        }
    }

    /// The figures of a histogram's counts, or `None` when it counted no task.
    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,
                clippy::cast_precision_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);
            middle(bucket)
        };
        Some(Self {
            median_us: at(0.5),
            p95_us: at(0.95),
            p99_us: at(0.99),
            count,
        })
    }
}

/// The time a bucket stands for, in whole microseconds: the middle of its bounds, rounded.
fn middle(bucket: usize) -> u64 {
    let (lower, upper) = (metrics::lower(bucket), metrics::upper(bucket));
    lower + (upper - lower).div_ceil(2)
}

/// The tasks one lane answered since the server started, and how long those since the previous
/// sample took.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct LaneSample {
    /// Tasks the service answered, errors included: counted when the reply is handed to the
    /// transport, before its result is written. A task whose result write fails is counted again
    /// when it is delivered and answered again; what the transport answers itself, such as an
    /// envelope it can't read, isn't counted.
    pub answered: u64,
    /// Of those, the tasks answered with an error.
    pub failed: u64,
    /// How long the tasks answered since the previous sample took in the worker; `None` when
    /// there were none.
    pub times: Option<Times>,
}

/// The tasks of one `task_name` answered since the server started.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct TaskSample {
    /// Tasks the service answered, errors included, counted as [`LaneSample::answered`] is.
    pub answered: u64,
    /// Of those, the tasks answered with an error.
    pub failed: u64,
}

/// What the searches answered since the server started returned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SearchSample {
    /// Query values looked up.
    pub values: u64,
    /// Matches returned, over every value.
    pub matches: u64,
    /// Values whose matches were cut, by the caller's `limit`, the size bound or the time bound.
    pub incomplete: u64,
}

/// A handle on a [`Server`](super::Server)'s counts and service 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) metrics: Arc<Metrics>,
    pub(crate) service: Arc<Service>,
    pub(crate) started: Instant,
    pub(crate) started_at: u64,
    pub(crate) fast_lane: bool,
}

impl Meter {
    /// 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 metrics = &self.metrics;
        let file = &metrics.file;
        let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
        let bulk_counts = file.bulk_times.take_counts();
        let fast_counts = file.fast_times.take_counts();
        let answered = metrics.answered();
        let task = |name: Name| {
            let index = Name::ALL.iter().position(|known| *known == name).unwrap_or(0);
            TaskSample {
                answered: answered[index],
                failed: load(&file.failed[index]),
            }
        };
        Sample {
            at: unix_seconds(SystemTime::now()),
            started_at: self.started_at,
            uptime: self.started.elapsed(),
            in_flight: load(&metrics.in_flight) + load(&metrics.fast_in_flight),
            fast_lane: self.fast_lane,
            bulk: LaneSample {
                answered: load(&file.bulk_answered),
                failed: load(&file.bulk_failed),
                times: Times::from_counts(&bulk_counts),
            },
            fast: LaneSample {
                answered: load(&file.fast_answered),
                failed: load(&file.fast_failed),
                times: Times::from_counts(&fast_counts),
            },
            search: task(Name::Search),
            stats: task(Name::Stats),
            append: task(Name::Append),
            replace: task(Name::Replace),
            remove: task(Name::Remove),
            searched: SearchSample {
                values: metrics.queries(),
                matches: load(&file.matches),
                incomplete: load(&file.incomplete),
            },
            totals: self.service.catalog().totals(),
            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 {
    /// 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,
    /// Tasks being handled now, on both lanes.
    pub in_flight: u64,
    /// Whether the server serves a fast lane.
    pub fast_lane: bool,
    /// The bulk lane.
    pub bulk: LaneSample,
    /// The fast lane: all zero without one.
    pub fast: LaneSample,
    /// `search` tasks, both lanes, an empty `task_name` and `default` included.
    pub search: TaskSample,
    /// `stats` tasks, both lanes.
    pub stats: TaskSample,
    /// `append` tasks.
    pub append: TaskSample,
    /// `replace` tasks.
    pub replace: TaskSample,
    /// `remove` tasks.
    pub remove: TaskSample,
    /// What the searches returned.
    pub searched: SearchSample,
    /// What the service serves at the moment of the sample.
    pub totals: Totals,
    /// The histogram buckets the lanes' 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 = Times::from_counts(&self.fast_counts);
    }
}

/// 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 bulk group's, `None` when it couldn't be read.
///
/// It holds numbers, the program's name and version, `state`, and fixed field names, and nothing
/// else: no name of an index or subset, no path, no stream, group, consumer, key prefix, host or
/// application, no task id, value or record id, and no error's text.
///
/// ```
/// use std::sync::Arc;
/// use legit_hamming::serve::{ServeConfig, Server, StatsState, stats_document};
/// use legit_hamming::service::{Catalog, Limits, LoadConfig, Service, SetSpec};
/// use legit_streams::{MemoryStreams, Streams};
///
/// let dir = std::env::temp_dir().join(format!("legit-hamming-document-doc-{}", std::process::id()));
/// std::fs::create_dir_all(&dir)?;
/// let catalog = Arc::new(Catalog::new(vec![SetSpec::index("images", &dir)], LoadConfig::default())?);
/// let service = Arc::new(Service::new(catalog, Limits::default(), 1));
/// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
/// let server = Server::start(ServeConfig::new("hamming-1", 7), service, 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");
/// # std::fs::remove_dir_all(&dir)?;
/// # 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 lane = |now: &LaneSample, before: Option<&LaneSample>| Lane {
        answered: now.answered,
        failed: now.failed,
        // Undefined over an interval of no length...
        #[expect(clippy::cast_precision_loss, reason = "a rate for a person or a collector to read")]
        rate_per_s: interval
            .zip(before)
            .filter(|(interval, _)| *interval > 0.0)
            .map(|(interval, before)| round(now.answered.saturating_sub(before.answered) as f64 / interval, 2)),
        // The times of the first sample cover the server's start, not an interval...
        median_us: now.times.filter(|_| previous.is_some()).map(|times| times.median_us),
        p95_us: now.times.filter(|_| previous.is_some()).map(|times| times.p95_us),
        p99_us: now.times.filter(|_| previous.is_some()).map(|times| times.p99_us),
    };
    let tally = |task: TaskSample| Tally {
        answered: task.answered,
        failed: task.failed,
    };
    let document = Document {
        format: STATS_FORMAT,
        program: "legit-hamming",
        version: env!("CARGO_PKG_VERSION"),
        state,
        started_at: sample.started_at,
        at: sample.at,
        uptime_s: sample.uptime.as_secs(),
        interval_s: interval.map(|interval| round(interval, 3)),
        in_flight: sample.in_flight,
        bulk: lane(&sample.bulk, previous.map(|previous| &previous.bulk)),
        fast: sample
            .fast_lane
            .then(|| lane(&sample.fast, previous.map(|previous| &previous.fast))),
        tasks: Tasks {
            search: SearchTally {
                answered: sample.search.answered,
                failed: sample.search.failed,
                values: sample.searched.values,
                matches: sample.searched.matches,
                incomplete: sample.searched.incomplete,
            },
            stats: tally(sample.stats),
            append: tally(sample.append),
            replace: tally(sample.replace),
            remove: tally(sample.remove),
        },
        totals: TotalsObject {
            sets: sample.totals.sets,
            records: sample.totals.records,
            changes_held: sample.totals.changes_held,
            ready: sample.totals.ready,
            not_ready: sample.totals.not_ready,
        },
        backlog: backlog.map(|backlog| Backlog {
            waiting: backlog.lag,
            pending: backlog.pending,
        }),
    };
    // Numbers and fixed words only, so serializing can't fail...
    serde_json::to_string(&document).unwrap_or_default()
}

#[derive(Serialize)]
struct Document {
    format: u32,
    program: &'static str,
    version: &'static str,
    state: StatsState,
    started_at: u64,
    at: u64,
    uptime_s: u64,
    interval_s: Option<f64>,
    in_flight: u64,
    bulk: Lane,
    fast: Option<Lane>,
    tasks: Tasks,
    totals: TotalsObject,
    backlog: Option<Backlog>,
}

#[derive(Serialize)]
struct Lane {
    answered: u64,
    failed: u64,
    rate_per_s: Option<f64>,
    median_us: Option<u64>,
    p95_us: Option<u64>,
    p99_us: Option<u64>,
}

#[derive(Serialize)]
struct Tasks {
    search: SearchTally,
    stats: Tally,
    append: Tally,
    replace: Tally,
    remove: Tally,
}

#[derive(Serialize)]
struct SearchTally {
    answered: u64,
    failed: u64,
    values: u64,
    matches: u64,
    incomplete: u64,
}

#[derive(Serialize)]
struct Tally {
    answered: u64,
    failed: u64,
}

#[derive(Serialize)]
struct TotalsObject {
    sets: u64,
    records: u64,
    changes_held: u64,
    ready: u64,
    not_ready: u64,
}

#[derive(Serialize)]
struct Backlog {
    waiting: Option<u64>,
    pending: u64,
}

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

pub(crate) 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 bulk group 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_hamming::serve::{ServeConfig, Server, StatsFile, StatsState};
/// use legit_hamming::service::{Catalog, Limits, LoadConfig, Service, SetSpec};
/// use legit_streams::{MemoryStreams, Streams};
///
/// let dir = std::env::temp_dir().join(format!("legit-hamming-stats-file-doc-{}", std::process::id()));
/// std::fs::create_dir_all(&dir)?;
/// let catalog = Arc::new(Catalog::new(vec![SetSpec::index("images", &dir)], LoadConfig::default())?);
/// let service = Arc::new(Service::new(catalog, Limits::default(), 1));
/// 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("hamming_tasks", "hamming_workers")?;
/// let server = Server::start(ServeConfig::new("hamming-1", 7), service, Arc::clone(&streams), None)?;
/// let path = dir.join("stats.json");
/// let mut file = StatsFile::new(&path)?.with_backlog(streams, "hamming_tasks", "hamming_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);
/// server.stop();
/// server.join()?;
/// # std::fs::remove_dir_all(&dir)?;
/// # 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_hamming::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 bulk 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.
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.
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 the bulk group'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("hamming-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 bulk group'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 super::super::metrics::{lower, upper};
    use super::{Times, middle};

    /// The bucket of a time, as the histogram files it: the time's own below 8 µs, then eight a
    /// power of two.
    fn bucket_of(micros: u64) -> usize {
        (0..512)
            .find(|&index| lower(index) <= micros && micros <= upper(index))
            .expect("a bucket")
    }

    #[test]
    fn a_bucket_stands_for_a_time_within_a_sixteenth_of_every_time_it_holds() {
        for micros in (0..5_000).chain([65_535, 65_536, 1_000_000, 123_456_789, 600_000_000]) {
            let stands_for = middle(bucket_of(micros));
            assert!(
                stands_for.abs_diff(micros) * 16 <= micros.max(1),
                "{micros} µs stands as {stands_for}"
            );
        }
    }

    /// The nearest-rank percentile of `values`.
    fn exact(values: &mut [u64], quantile: f64) -> u64 {
        values.sort_unstable();
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            clippy::cast_precision_loss,
            reason = "a small rank"
        )]
        let rank = ((quantile * values.len() as f64).ceil() as usize).max(1);
        values[rank - 1]
    }

    #[test]
    fn the_percentiles_are_within_a_sixteenth_of_the_exact_ones() {
        // A fixed pseudo-random spread from 1 µs to 10 s, log-uniform...
        let mut state = 0x2545_f491_4f6c_dd1d_u64;
        for size in [1, 2, 3, 19, 20, 100, 1_000, 10_000] {
            let mut counts = vec![0_u64; 512];
            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^34")]
                let micros = 1e7_f64.powf(unit) as u64;
                counts[bucket_of(micros)] += 1;
                values.push(micros);
            }
            let times = Times::from_counts(&counts).expect("times");
            assert_eq!(times.count, size);
            for (got, quantile) in [(times.median_us, 0.5), (times.p95_us, 0.95), (times.p99_us, 0.99)] {
                let want = exact(&mut values, quantile);
                assert!(got.abs_diff(want) * 16 <= want.max(1), "{size}: {got} for {want}");
            }
        }
        assert_eq!(Times::from_counts(&[0; 512]), None);
    }
}