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
//! `legit-hamming serve`: the [`service`](crate::service) as a worker on the Redis Streams work
//! contract of [`legit_streams`], with the task kind `hamming`.
//!
//! A task's `task_name` is `search` (or `default`) or `stats`, and its `options` field
//! holds the JSON object [`Service::search`] or [`Service::stats`] reads; its result's `result`
//! field holds the object they write, the same bytes `legit-hamming query` writes for the same
//! options and snapshot. An error result carries the contract's `error_type`, and `result` holds
//! the error object. The crate's README states every field.
//!
//! [`Server`] runs a bulk [`Worker`] on `hamming_tasks`, a [`FastWorker`] on
//! `hamming_tasks:fast` unless it's turned off, and a thread that reads each index's `CURRENT`
//! at an interval and swaps in a new snapshot when it changes.
//!
//! ```
//! use std::sync::Arc;
//! use std::time::Duration;
//!
//! use legit_hamming::serve::{ServeConfig, Server};
//! use legit_hamming::service::{Catalog, Limits, LoadConfig, Service, SetSpec};
//! use legit_hamming::{Records, snapshot};
//! use legit_streams::{MemoryStreams, Producer, ResultReader, Streams, Task};
//!
//! let dir = std::env::temp_dir().join(format!("legit-hamming-serve-doc-{}", std::process::id()));
//! snapshot::write(&dir.join("first"), &Records::from_records([(7, 0xffu64)])?, 1_000)?;
//! std::fs::write(dir.join("CURRENT"), "first\n")?;
//! let catalog = Catalog::new(vec![SetSpec::index("images", &dir)], LoadConfig::default())?;
//! // Loaded before the worker joins its group...
//! catalog.load_changed(&mut |_| {});
//! let service = Arc::new(Service::new(Arc::new(catalog), Limits::default(), 1));
//!
//! // The in-memory double here; `RedisStreams::open(url)` on a server...
//! let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
//! let mut config = ServeConfig::new("hamming-1", 7);
//! config.worker.read_block = Duration::from_millis(50);
//! let server = Server::start(config, service, Arc::clone(&streams), None)?;
//!
//! let task = Task::builder("app", "photo", "42")
//!     .task_name("search")
//!     .reply_to(legit_streams::reply_to("app", "hamming"))
//!     .field("options", r#"{"format":1,"index":"images","width":64,"radius":2,"values":["00000000000000fe"]}"#)
//!     .build()?;
//! Producer::new(Arc::clone(&streams), "hamming_tasks").send(&task)?;
//!
//! let reader = ResultReader::new(Arc::clone(&streams), "results:app:hamming", "app", "app-1");
//! let result = loop {
//!     let received = reader.read(10, Some(Duration::from_millis(50)))?;
//!     if let Some(received) = received.into_iter().next() {
//!         break received.result.expect("a result");
//!     }
//! };
//! assert!(result.is_success());
//! assert!(result.get("result").expect("`result`").contains(r#"{"id":7,"value":"00000000000000ff","distance":1}"#));
//!
//! server.stop();
//! server.join()?;
//! # std::fs::remove_dir_all(&dir).ok();
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

mod metrics;
mod stats;
mod task;

use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use legit_streams::{
    Clock, FastWorker, FastWorkerConfig, Report, Running, Streams, Worker, WorkerConfig, fast_consumer_name,
};

pub use metrics::{Heartbeat, Latency, TaskCounts};
pub use stats::{
    BACKLOG_TIMEOUT, LaneSample, Meter, STATS_FORMAT, Sample, SearchSample, StatsFile, StatsState, TaskSample, Times,
    stats_document,
};
pub use task::CHANGE_RESULT_BYTES;

use crate::service::{Event, Service};

/// The kind of task served, `hamming`, which names the streams, the group and the fast lane's
/// reply keys.
pub const KIND: &str = "hamming";

/// The `model_name` a task may give, besides none: this program's name. Any other is
/// `unsupported_model`.
pub const MODEL_NAME: &str = crate::service::SUPPORTED_MODELS[0];

/// The bytes of a result entry kept for the envelope's own fields, besides `result` and what the
/// task echoes: `task_id`, `status`, the identities, `worker_id`, `processing_ms`, and an error's
/// message and fields. A search is sized to the entry's bound less this, less the bytes of the
/// fields the task echoes (`model_type`, `model_id`, `task_name`, `model_name`, `metadata` and
/// `embedder_key`), so its result never makes the entry too large after the search has run.
pub const ENVELOPE_ROOM: usize = 64 << 10;

/// The longest consumer name a worker takes, in bytes: its `worker_id` is in every result, inside
/// [`ENVELOPE_ROOM`].
pub const CONSUMER_MAX: usize = 256;

/// The most fields a result of this worker has: the envelope's ten (`task_id`, the four
/// identities, `status`, `error_type`, `error`, `worker_id`, `processing_ms`), the two optional
/// echoes (`metadata`, `embedder_key`), and `result` with at most two fields of its error.
pub const RESULT_FIELDS: usize = 15;

/// The longest field name a result of this worker has: `supported_models`.
pub const RESULT_FIELD_NAME: usize = 16;

/// Why a lane's transport limits can't carry every result this worker writes, if they can't: too
/// few fields, too short a field name, or an entry with no room for a change's result beside the
/// envelope. A worker refuses them at start, so no change is applied whose result the transport
/// would then refuse.
fn result_room(limits: &legit_streams::Limits) -> Option<String> {
    let least = ENVELOPE_ROOM + task::CHANGE_RESULT_BYTES;
    if limits.max_fields < RESULT_FIELDS {
        Some(format!(
            "the transport's limits allow {} fields an entry; a result of this worker has up to {RESULT_FIELDS}",
            limits.max_fields
        ))
    } else if limits.max_field_name < RESULT_FIELD_NAME {
        Some(format!(
            "the transport's limits allow field names of {} bytes; a result of this worker has names of up to \
             {RESULT_FIELD_NAME}",
            limits.max_field_name
        ))
    } else if limits.max_entry_bytes < least {
        Some(format!(
            "the transport's limits allow entries of {} bytes; a result of this worker needs at least {least}",
            limits.max_entry_bytes
        ))
    } else {
        None
    }
}

/// The wait between one check of each `CURRENT` and the next by default: 30 seconds.
pub const DEFAULT_RELOAD: Duration = Duration::from_secs(30);

/// How long the heartbeat waits between lines by default.
pub const DEFAULT_HEARTBEAT: Duration = Duration::from_secs(30);

/// The bulk task stream of a kind: `{kind}_tasks`.
#[must_use]
pub fn task_stream(kind: &str) -> String {
    format!("{kind}_tasks")
}

/// The consumer group of a kind: `{kind}_workers`, which reads both lanes.
#[must_use]
pub fn group(kind: &str) -> String {
    format!("{kind}_workers")
}

/// The default result stream of a kind: `{kind}_results`.
#[must_use]
pub fn result_stream(kind: &str) -> String {
    format!("{kind}_results")
}

/// The fast task stream of a kind: `{kind}_tasks:fast`.
#[must_use]
pub fn fast_stream(kind: &str) -> String {
    format!("{kind}_tasks:fast")
}

/// How a [`Server`] runs: its two workers' settings, and how often it reads each `CURRENT`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ServeConfig {
    /// The bulk worker on `{kind}_tasks`: one task at a time by default, since each task's search
    /// already runs across the service's threads.
    pub worker: WorkerConfig,
    /// The fast worker on `{kind}_tasks:fast`, or `None` to serve the bulk lane only: two requests
    /// at once by default, each on one thread.
    pub fast: Option<FastWorkerConfig>,
    /// The wait between the end of one check of each `CURRENT` and the start of the next:
    /// [`DEFAULT_RELOAD`]. A check that loads a snapshot includes its load, its tables and its
    /// neighbour table.
    pub reload: Duration,
}

impl ServeConfig {
    /// The contract's names for the kind `hamming`, with consumer names made from `prefix` and
    /// the process id: `{prefix}_{pid}` on the bulk lane, `{prefix}-fast_{pid}` on the fast lane.
    ///
    /// ```
    /// let config = legit_hamming::serve::ServeConfig::new("search-host1", 4242);
    /// assert_eq!(config.worker.stream, "hamming_tasks");
    /// assert_eq!(config.worker.consumer, "search-host1_4242");
    /// assert_eq!(config.fast.as_ref().map(|fast| fast.stream.as_str()), Some("hamming_tasks:fast"));
    /// ```
    #[must_use]
    pub fn new(prefix: &str, pid: u32) -> Self {
        Self::for_kind(KIND, prefix, pid)
    }

    /// The same, for another kind's names, such as a second deployment kept apart from the first.
    #[must_use]
    pub fn for_kind(kind: &str, prefix: &str, pid: u32) -> Self {
        let worker = WorkerConfig::new(
            task_stream(kind),
            group(kind),
            format!("{prefix}_{pid}"),
            result_stream(kind),
        );
        let mut fast = FastWorkerConfig::new(fast_stream(kind), group(kind), fast_consumer_name(prefix, pid), kind);
        fast.concurrency = 2;
        Self {
            worker,
            fast: Some(fast),
            reload: DEFAULT_RELOAD,
        }
    }
}

/// What each worker of a [`Server`] did before it stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reports {
    /// The bulk worker's report.
    pub bulk: Report,
    /// The fast worker's report, when it ran.
    pub fast: Option<Report>,
}

/// The thread that reads each `CURRENT` and loads what changed. It returns why it stopped when it
/// stopped on its own: a panic in a load, which stops the server.
#[derive(Debug)]
struct Reloader {
    stop: Arc<(Mutex<bool>, Condvar)>,
    handle: JoinHandle<Option<String>>,
}

/// A worker for the task kind `hamming`: a bulk [`Worker`], a [`FastWorker`] when configured, and
/// a reloader, each on threads of its own.
#[derive(Debug)]
pub struct Server {
    bulk: Running,
    fast: Option<Running>,
    reloader: Reloader,
    service: Arc<Service>,
    metrics: Arc<metrics::Metrics>,
    started: Instant,
    /// When it started, in Unix seconds.
    started_at: u64,
}

impl Server {
    /// Start the reloader and the workers on `streams`, on `clock` when given (a manual clock in
    /// tests) or the system clock. The reloader reads each `CURRENT` at once, loads and measures
    /// each new snapshot's neighbour table, and checks again [`ServeConfig::reload`] after that
    /// check ended.
    ///
    /// The workers join their group at once, and a search of a set with no snapshot loaded is
    /// answered `not_ready`. Load the catalog first, with [`Catalog::load_changed`], so a worker
    /// doesn't take tasks from a group whose other workers could answer them: `legit-hamming
    /// serve` does.
    ///
    /// [`Catalog::load_changed`]: crate::service::Catalog::load_changed
    ///
    /// # Errors
    ///
    /// [`legit_streams::Error::InvalidConfig`] for settings either worker refuses, transport
    /// limits that can't carry every result this worker writes (at least [`RESULT_FIELDS`] fields,
    /// names of [`RESULT_FIELD_NAME`] bytes, and entries of [`ENVELOPE_ROOM`] and
    /// [`CHANGE_RESULT_BYTES`]), a consumer name over [`CONSUMER_MAX`] bytes, or a bulk
    /// worker running more than one task at once for a service that takes changes, and
    /// [`legit_streams::Error::Thread`] when a thread can't be started. A server that can't reach
    /// Redis starts, and its workers stop with the error: see [`Server::join`].
    pub fn start(
        config: ServeConfig,
        service: Arc<Service>,
        streams: Arc<dyn Streams>,
        clock: Option<Clock>,
    ) -> legit_streams::Result<Self> {
        let consumers = [
            Some(&config.worker.consumer),
            config.fast.as_ref().map(|fast| &fast.consumer),
        ];
        if consumers
            .into_iter()
            .flatten()
            .any(|consumer| consumer.len() > CONSUMER_MAX)
        {
            return Err(legit_streams::Error::InvalidConfig(format!(
                "a consumer name is at most {CONSUMER_MAX} bytes: it is in every result"
            )));
        }
        let lanes = [
            Some(&config.worker.limits),
            config.fast.as_ref().map(|fast| &fast.limits),
        ];
        if let Some(problem) = lanes.into_iter().flatten().find_map(result_room) {
            return Err(legit_streams::Error::InvalidConfig(problem));
        }
        if service.takes_changes() && config.worker.concurrency > 1 {
            // Tasks taken together run on threads of their own, in no order between them: two
            // changes to one id could be applied the other way round...
            return Err(legit_streams::Error::InvalidConfig(
                "with changes on, the bulk worker runs one task at a time, so changes apply in the order they \
                 were taken: set its concurrency to 1"
                    .to_owned(),
            ));
        }
        let metrics = Arc::new(metrics::Metrics::default());
        let handler =
            |lane, entry_bytes| task::Handler::new(Arc::clone(&service), Arc::clone(&metrics), lane, entry_bytes);
        let fast = match config.fast {
            Some(fast_config) => {
                let mut worker = {
                    let entry_bytes = fast_config.limits.max_entry_bytes;
                    FastWorker::new(
                        fast_config,
                        Arc::clone(&streams),
                        handler(crate::service::Lane::Fast, entry_bytes),
                    )?
                };
                if let Some(clock) = &clock {
                    worker = worker.clock(clock.clone());
                }
                Some(worker)
            }
            None => None,
        };
        let entry_bytes = config.worker.limits.max_entry_bytes;
        let mut bulk = Worker::new(config.worker, streams, handler(crate::service::Lane::Bulk, entry_bytes))?;
        if let Some(clock) = clock {
            bulk = bulk.clock(clock);
        }
        let reloader = spawn_reloader(Arc::clone(&service), config.reload)?;
        let stop_reloader = || {
            let (stopped, wake) = &*reloader.stop;
            *stopped.lock().unwrap_or_else(PoisonError::into_inner) = true;
            wake.notify_all();
        };
        let fast = match fast.map(FastWorker::spawn).transpose() {
            Ok(fast) => fast,
            Err(error) => {
                stop_reloader();
                return Err(error);
            }
        };
        let bulk = match bulk.spawn() {
            Ok(bulk) => bulk,
            Err(error) => {
                stop_reloader();
                if let Some(fast) = fast {
                    fast.stop();
                    let _ = fast.join();
                }
                return Err(error);
            }
        };
        tracing::info!(kind = KIND, fast = fast.is_some(), "Hamming search worker started");
        Ok(Self {
            bulk,
            fast,
            reloader,
            service,
            metrics,
            started: Instant::now(),
            started_at: stats::unix_seconds(std::time::SystemTime::now()),
        })
    }

    /// The service it answers with.
    #[must_use]
    pub const fn service(&self) -> &Arc<Service> {
        &self.service
    }

    /// What the server has done since it started, and its latencies since the last heartbeat,
    /// which this call starts afresh.
    #[must_use]
    pub fn heartbeat(&self) -> Heartbeat {
        self.metrics.heartbeat(self.started.elapsed().as_secs())
    }

    /// A handle on the server's counts and service for the stats file: [`Meter::sample`] gives
    /// what [`stats_document`] reports, and the handle can still be read after [`Server::join`],
    /// for the last document. Its samples and [`Server::heartbeat`] keep separate times, so
    /// neither empties the other's.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use legit_hamming::serve::{ServeConfig, Server};
    /// use legit_hamming::service::{Catalog, Limits, LoadConfig, Service, SetSpec};
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// // An index with no `CURRENT` yet...
    /// let dir = std::env::temp_dir().join(format!("legit-hamming-meter-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();
    /// server.stop();
    /// server.join()?;
    /// let sample = meter.sample();
    /// assert_eq!((sample.bulk.answered, sample.totals.not_ready), (0, 1));
    /// # std::fs::remove_dir_all(&dir)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn meter(&self) -> Meter {
        Meter {
            metrics: Arc::clone(&self.metrics),
            service: Arc::clone(&self.service),
            started: self.started,
            started_at: self.started_at,
            fast_lane: self.fast.is_some(),
        }
    }

    /// Ask the workers and the reloader to stop: the workers take no new task, the bulk worker
    /// waits up to its shutdown grace for the task it runs and releases the rest to other workers,
    /// and the fast worker answers what it has read. A load in progress isn't waited for.
    pub fn stop(&self) {
        self.bulk.stop();
        if let Some(fast) = &self.fast {
            fast.stop();
        }
        let (stopped, wake) = &*self.reloader.stop;
        *stopped.lock().unwrap_or_else(PoisonError::into_inner) = true;
        wake.notify_all();
    }

    /// Whether either worker or the reloader has stopped: all of them after [`Server::stop`], or
    /// one on its own when it couldn't start, such as when Redis can't be reached, or when a load
    /// panicked. Stop the server and join it then.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.bulk.is_finished()
            || self.fast.as_ref().is_some_and(Running::is_finished)
            || self.reloader.handle.is_finished()
    }

    /// Wait for both workers to stop, and for the reloader unless a load is still running, which
    /// ends with the process.
    ///
    /// # Errors
    ///
    /// The first error either worker stopped with, such as [`legit_streams::Error::Redis`] when
    /// its group couldn't be created at the start; then [`legit_streams::Error::Thread`] when the
    /// reloader stopped on a panic, which a snapshot load or a swap can't recover from in place.
    ///
    /// # Panics
    ///
    /// When a worker's thread panicked, with its panic.
    pub fn join(self) -> legit_streams::Result<Reports> {
        let bulk = self.bulk.join();
        let fast = self.fast.map(Running::join).transpose();
        let reloader = if self.reloader.handle.is_finished() {
            match self.reloader.handle.join() {
                Ok(failed) => failed,
                Err(_) => Some("the reloader's thread panicked".to_owned()),
            }
        } else {
            tracing::info!("A snapshot load is still running; it ends with the process");
            None
        };
        let reports = Reports {
            bulk: bulk?,
            fast: fast?,
        };
        if let Some(reason) = reloader {
            return Err(legit_streams::Error::Thread(format!("the reloader stopped: {reason}")));
        }
        tracing::info!(
            results = reports.bulk.results,
            released = reports.bulk.released.len(),
            fast_results = reports.fast.as_ref().map_or(0, |fast| fast.results),
            "Hamming search worker stopped"
        );
        Ok(reports)
    }
}

fn spawn_reloader(service: Arc<Service>, every: Duration) -> legit_streams::Result<Reloader> {
    let stop = Arc::new((Mutex::new(false), Condvar::new()));
    let flag = Arc::clone(&stop);
    let handle = std::thread::Builder::new()
        .name("hamming-reload".to_owned())
        .spawn(move || {
            let (stopped, wake) = &*flag;
            loop {
                let refreshed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    service.catalog().refresh(&mut log_event);
                }));
                if let Err(panic) = refreshed {
                    let reason = panic_message(panic.as_ref());
                    tracing::error!(reason = %reason, "A snapshot load panicked; the server stops");
                    return Some(reason);
                }
                let guard = stopped.lock().unwrap_or_else(PoisonError::into_inner);
                let (guard, _) = wake
                    .wait_timeout_while(guard, every, |stopped| !*stopped)
                    .unwrap_or_else(PoisonError::into_inner);
                if *guard {
                    return None;
                }
            }
        })
        .map_err(|error| legit_streams::Error::Thread(error.to_string()))?;
    Ok(Reloader { stop, handle })
}

/// What a panic said, when it said it in text.
pub fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
    panic
        .downcast_ref::<&str>()
        .map(|text| (*text).to_owned())
        .or_else(|| panic.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "a panic without a message".to_owned())
}

/// One log line for a catalog event.
pub fn log_event(event: &Event) {
    match event {
        Event::Refused { set, reason } => {
            tracing::warn!(set = %set, reason = %reason, "A CURRENT was refused; the snapshot served stays");
        }
        Event::Loading { set, snapshot, bytes } => {
            tracing::info!(set = %set, snapshot = %snapshot, bytes, "Loading a snapshot");
        }
        Event::Loaded {
            set,
            snapshot,
            records,
            width,
            tables,
            load_ms,
            build_ms,
            replaced,
            replayed,
            replay_ms,
            seq,
        } => {
            tracing::info!(
                set = %set,
                snapshot = %snapshot,
                records,
                width,
                tables,
                load_ms,
                build_ms,
                replaced = replaced.as_deref().unwrap_or(""),
                replayed,
                replay_ms,
                seq,
                "A snapshot is served"
            );
        }
        Event::LogOpened {
            set,
            tasks,
            entries,
            seq,
            cut_bytes,
            cut_entries,
        } => {
            tracing::info!(
                set = %set,
                tasks,
                entries,
                seq,
                cut_bytes,
                cut_entries,
                "Change log read; an unfinished task at its end, if any, was cut"
            );
        }
        Event::LogRefused { set, reason } => {
            tracing::error!(set = %set, reason = %reason, "A change log was refused; its index serves nothing");
        }
        Event::LogShortened {
            set,
            covers_seq,
            entries,
            bytes_before,
            bytes_after,
        } => {
            tracing::info!(
                set = %set,
                covers_seq,
                entries,
                bytes_before,
                bytes_after,
                "Change log shortened"
            );
        }
        Event::LogFailed { set, reason } => {
            tracing::error!(set = %set, reason = %reason, "Writing a change log failed");
        }
        Event::Failed {
            set,
            snapshot,
            code,
            reason,
        } => {
            tracing::warn!(
                set = %set,
                snapshot = %snapshot,
                code,
                reason = %reason,
                "A snapshot failed to load; the snapshot served stays"
            );
        }
        Event::Measured {
            set,
            snapshot,
            sample,
            ms,
        } => {
            tracing::info!(set = %set, snapshot = %snapshot, sample, ms, "Neighbour table measured");
        }
    }
}

/// The log subscriber `legit-hamming serve` writes with: one JSON object a line, its fields at the
/// top level, at `level` and above, to `writer`. Set it with
/// [`tracing::subscriber::set_global_default`].
pub fn subscriber<W>(level: tracing::Level, writer: W) -> impl tracing::Subscriber + Send + Sync + 'static
where
    W: for<'writer> tracing_subscriber::fmt::MakeWriter<'writer> + Send + Sync + 'static,
{
    tracing_subscriber::fmt()
        .json()
        .flatten_event(true)
        .with_current_span(false)
        .with_span_list(false)
        .with_writer(writer)
        .with_max_level(level)
        .finish()
}

#[cfg(test)]
mod tests {
    use legit_streams::{MemoryStreams, Producer, ResultReader, Task};

    use super::*;
    use crate::service::{Catalog, Limits, LoadConfig, SetSpec};
    use crate::{Records, snapshot};

    /// A server over one small index, its catalog failing at `fault`, and its streams.
    fn start(name: &str, fault: &'static str) -> (Server, Arc<dyn Streams>, std::path::PathBuf) {
        let dir = std::env::temp_dir().join(format!("legit-hamming-serve-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        snapshot::write(
            &dir.join("s"),
            &Records::from_records([(7, 0xffu64)]).expect("records"),
            10,
        )
        .expect("written");
        std::fs::write(dir.join("CURRENT"), "s\n").expect("written");
        let config = LoadConfig {
            neighbours: false,
            threads: 1,
            ..LoadConfig::default()
        };
        let catalog = Catalog::new(vec![SetSpec::index("m", &dir)], config).expect("a catalog");
        catalog.load_changed(&mut |_| {});
        catalog.faults.lock().expect("faults").push(fault);
        let service = Arc::new(Service::new(Arc::new(catalog), Limits::default(), 1));
        let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
        let mut config = ServeConfig::new("unit", 1);
        config.worker.read_block = Duration::from_millis(20);
        config.fast = None;
        config.reload = Duration::from_millis(20);
        let server = Server::start(config, service, Arc::clone(&streams), None).expect("starts");
        (server, streams, dir)
    }

    #[test]
    fn a_panic_in_the_reloader_stops_the_server_with_its_reason() {
        let (server, _streams, dir) = start("reload", "refresh");
        let started = Instant::now();
        while !server.is_finished() {
            assert!(started.elapsed() < Duration::from_secs(10), "the server didn't stop");
            std::thread::sleep(Duration::from_millis(10));
        }
        server.stop();
        let error = server.join().expect_err("the reloader failed");
        assert!(error.to_string().contains("a fault injected at `refresh`"), "{error}");
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn a_task_that_panics_leaves_nothing_in_flight() {
        let (server, streams, dir) = start("in-flight", "handle");
        let task = Task::builder("app", "photo", "1")
            .task_id("app_p1")
            .task_name("stats")
            .field("options", r#"{"format":1,"index":"m"}"#)
            .build()
            .expect("a task");
        Producer::new(Arc::clone(&streams), "hamming_tasks")
            .send(&task)
            .expect("sent");
        let reader = ResultReader::new(Arc::clone(&streams), "hamming_results", "readers", "reader");
        let started = Instant::now();
        let result = loop {
            assert!(started.elapsed() < Duration::from_secs(10), "no result");
            if let Some(received) = reader.read(10, Some(Duration::from_millis(20))).expect("read").pop() {
                break received.result.expect("a result");
            }
        };
        assert!(!result.is_success());
        assert_eq!(server.heartbeat().in_flight, 0);
        server.stop();
        let _ = server.join();
        let _ = std::fs::remove_dir_all(dir);
    }
}