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
//! The `legit-hamming` command: `info`, `verify`, `query` and `stats` over snapshots, and with the
//! `serve` feature, `serve` over Redis Streams.

use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::{Duration, Instant};

use legit_hamming::service::{
    self, Catalog, Event, Lane, Limits, LoadConfig, Service, SetSpec, TableMemory, verify_snapshot,
};
use legit_hamming::{Cpu, snapshot};

#[cfg(feature = "serve")]
mod serve_command;

const HELP: &str = "\
legit-hamming: exact Hamming radius search over snapshots of 64-bit and 256-bit hashes

Usage:
  legit-hamming query [options]     search: one options object a line in, one result a line out
  legit-hamming stats [options]     load, measure the neighbour table, print each set's stats
  legit-hamming verify DIR          check a snapshot: manifest, sizes, checksums, ids rising
  legit-hamming info                print the CPU's paths, formats and versions as JSON
  legit-hamming serve [options]     answer search and stats tasks from Redis Streams
                                    (in a build with the `serve` feature)
  legit-hamming help                print this help
  legit-hamming --version           print the version

Indexes (query, stats, serve):
  --index NAME=DIR          serve the index NAME from DIR, which holds snapshot directories
                            and a one-line file CURRENT naming the one to serve; repeatable
  --subset INDEX.NAME=DIR   serve the subset NAME of INDEX from DIR, the same way; repeatable
  --threads N               threads a bulk search, a table build and a neighbour count run on
                            (default: the available cores)
  --state-dir DIR           each index's change log, in DIR/INDEX/: `serve` writes it and takes
                            append, replace and remove tasks, one process an index; `query`
                            and `stats` read it as it is on disk, without the lock
  --table-memory BYTES      build the multi-index tables when they take at most BYTES, with
                            a k, m or g suffix for KiB, MiB or GiB; 0 scans every query;
                            `auto` builds them when they fit in the memory available less a
                            quarter, at least 512 MiB (default: auto)

Limits (query, stats, serve), each checked before a search starts, but the search budgets:
  --max-values-fast N       values a quick request may hold (default: 1)
  --max-values N            values a bulk task may hold (default: 5000)
  --max-options-bytes N     the longest options read (default: 1048576)
  --max-radius-64 N         the largest radius at 64 bits (default: 16)
  --max-radius-256 N        the largest radius at 256 bits (default: 96)
  --max-matches N           matches kept a query, the nearest (default: 10000)
  --fast-query-time S       a quick search's budget: it stops collecting candidates after S
                            seconds, and the reply follows as soon as what was collected is
                            merged and written (default: 2)
  --query-time S            the same for a bulk task, all its values together (default: 30)
  --max-result-bytes N      the largest result object (default: 33554432)
  --max-change-records N    records an append or replace task may hold (default: 1000)
  --max-remove-ids N        ids a remove task may hold (default: 10000)
  --max-log-bytes N         an index's change log; past it, changes are refused with
                            log_full, and a log longer than it and one largest task isn't
                            read: raise it to read one (default: 268435456)

Query:
  --input FILE              read from FILE rather than standard input
  --lane fast|bulk          answer as the quick path or the bulk stream would (default: bulk)

Stats:
  --sample N                records sampled for the neighbour table (default: 2000)
  --max-distance D          the farthest distance counted (default: 16 at 64 bits, 96 at 256)
  --seed S                  the seed the sample is drawn with (default: 0)

Serve:
  --redis URL               the Redis server, such as redis://127.0.0.1:6379; without it,
                            LEGIT_HAMMING_REDIS_URL, which keeps a password off the command line
  --key-prefix PREFIX       a prefix every key on the server carries (default: none)
  --kind KIND               the task kind, which names the streams (default: hamming)
  --consumer NAME           this worker's name in the group (default: legit-hamming-HOST);
                            the process id is added
  --jobs N                  bulk tasks run at once, each across --threads (default: 1)
  --fast-jobs N             quick requests run at once, one thread each (default: 2)
  --no-fast                 serve the bulk lane only
  --reload-seconds S        the wait between the end of one check of each CURRENT, its
                            loads included, and the next (default: 30)
  --stats-sample N          records sampled for each snapshot's neighbour table (default: 2000)
  --stats-max-distance-64 D the farthest distance it counts at 64 bits (default: 16)
  --stats-max-distance-256 D  the same at 256 bits (default: 96)
  --shutdown-grace S        seconds a stop waits for a running task (default: 30)
  --heartbeat S             seconds between heartbeat lines (default: 30)
  --stats-file PATH         write a JSON document of counts and timings to PATH at start, at
                            each heartbeat and at stop, whole each time (via PATH.tmp, then
                            renamed; mode 0644); numbers only, never a name, path or value.
                            Its directory must exist
  --repeat-window S         seconds a change task is still recognised as a repeat once a
                            snapshot covers it and its entries are dropped (default: 3600)
  With --state-dir, --jobs must be 1: changes apply one at a time, in the order taken.
  Log lines and heartbeats are JSON on standard error. SIGTERM or SIGINT stops it
  cleanly; a second one stops it at once.

Exit status: query exits 0 when every request succeeded, 1 when any was answered with
an error (each a line, `not_ready` for a set that didn't load), 2 when it couldn't
run, such as an input it couldn't open.
stats exits 1 when an index or subset has no snapshot loaded. verify exits 0 for a
sound snapshot and 1 otherwise. serve exits 0 after a clean stop on a signal, and 2
when it couldn't run.

The request and result formats are in the crate's README.
";

/// A command-line mistake, printed with a pointer to the help.
struct Usage(String);

/// Every setting a command takes from its command line.
#[derive(Debug)]
struct Arguments {
    specs: Vec<SetSpec>,
    input: Option<PathBuf>,
    lane: Lane,
    load: LoadConfig,
    limits: Limits,
    threads: Option<usize>,
    sample: Option<usize>,
    max_distance: Option<u32>,
    seed: Option<u64>,
    positional: Vec<String>,
    /// `--help` or `-h` was given: the command prints the help instead.
    help: bool,
    #[cfg_attr(not(feature = "serve"), allow(dead_code, reason = "read by `serve` only"))]
    serve: ServeArguments,
}

/// The settings only `serve` takes.
#[derive(Debug)]
#[cfg_attr(not(feature = "serve"), allow(dead_code, reason = "read by `serve` only"))]
struct ServeArguments {
    redis: Option<String>,
    key_prefix: String,
    kind: Option<String>,
    consumer: Option<String>,
    jobs: usize,
    fast_jobs: usize,
    no_fast: bool,
    reload: Duration,
    shutdown_grace: Duration,
    heartbeat: Duration,
    stats_file: Option<PathBuf>,
}

/// The flags every command that loads indexes takes.
const SET_FLAGS: [&str; 17] = [
    "--index",
    "--subset",
    "--threads",
    "--state-dir",
    "--max-change-records",
    "--max-remove-ids",
    "--max-log-bytes",
    "--table-memory",
    "--max-values-fast",
    "--max-values",
    "--max-options-bytes",
    "--max-radius-64",
    "--max-radius-256",
    "--max-matches",
    "--fast-query-time",
    "--query-time",
    "--max-result-bytes",
];

/// The flags `serve` takes besides those.
#[cfg(feature = "serve")]
const SERVE_FLAGS: [&str; 15] = [
    "--stats-file",
    "--redis",
    "--repeat-window",
    "--key-prefix",
    "--kind",
    "--consumer",
    "--jobs",
    "--fast-jobs",
    "--no-fast",
    "--reload-seconds",
    "--stats-sample",
    "--stats-max-distance-64",
    "--stats-max-distance-256",
    "--shutdown-grace",
    "--heartbeat",
];

fn main() -> ExitCode {
    let mut arguments = std::env::args().skip(1);
    let command = arguments.next();
    let rest: Vec<String> = arguments.collect();
    let flags = |extra: &[&'static str]| -> Vec<&'static str> { SET_FLAGS.iter().chain(extra).copied().collect() };
    // A command's `--help` prints the help rather than run it...
    let run = |allowed: &[&str], positional: bool, command: &dyn Fn(&Arguments) -> Result<ExitCode, Usage>| {
        parse(&rest, allowed, positional).and_then(|arguments| {
            if arguments.help {
                Ok(help())
            } else {
                command(&arguments)
            }
        })
    };
    let result = match command.as_deref() {
        Some("query") => run(&flags(&["--input", "--lane"]), false, &query),
        Some("stats") => run(&flags(&["--sample", "--max-distance", "--seed"]), false, &stats),
        Some("verify") => run(&[], true, &verify),
        Some("info") => run(&[], false, &|_| info()),
        #[cfg(feature = "serve")]
        Some("serve") => run(&flags(&SERVE_FLAGS), false, &serve_command::serve),
        #[cfg(not(feature = "serve"))]
        Some("serve") if rest.iter().any(|argument| is_help(argument)) => Ok(help()),
        #[cfg(not(feature = "serve"))]
        Some("serve") => Err(Usage(
            "this build has no `serve`; build it with `--features serve`".to_owned(),
        )),
        Some("help" | "--help" | "-h") | None => Ok(help()),
        Some("--version" | "-V") => {
            println!("legit-hamming {}", env!("CARGO_PKG_VERSION"));
            Ok(ExitCode::SUCCESS)
        }
        Some(other) => Err(Usage(format!("there's no command `{}`", service::shorten(other, 64)))),
    };
    result.unwrap_or_else(|Usage(message)| {
        eprintln!("legit-hamming: {message}; see `legit-hamming help`");
        ExitCode::from(2)
    })
}

/// Print the help to standard output.
fn help() -> ExitCode {
    print!("{HELP}");
    ExitCode::SUCCESS
}

/// Whether an argument asks for the help: `--help` or `-h`.
fn is_help(argument: &str) -> bool {
    matches!(argument, "--help" | "-h")
}

/// Read a command's arguments. `--help` or `-h` in place of a flag stops the reading: the
/// command prints the help, whatever follows it.
fn parse(rest: &[String], allowed: &[&str], positional: bool) -> Result<Arguments, Usage> {
    let mut arguments = Arguments {
        specs: Vec::new(),
        input: None,
        lane: Lane::Bulk,
        load: LoadConfig::default(),
        limits: Limits::default(),
        threads: None,
        sample: None,
        max_distance: None,
        seed: None,
        positional: Vec::new(),
        help: false,
        serve: ServeArguments {
            redis: None,
            key_prefix: String::new(),
            kind: None,
            consumer: None,
            jobs: 1,
            fast_jobs: 2,
            no_fast: false,
            reload: Duration::from_secs(30),
            shutdown_grace: Duration::from_secs(30),
            heartbeat: Duration::from_secs(30),
            stats_file: None,
        },
    };
    let mut iter = rest.iter();
    while let Some(argument) = iter.next() {
        if is_help(argument) {
            arguments.help = true;
            return Ok(arguments);
        }
        if positional && !argument.starts_with("--") {
            arguments.positional.push(argument.clone());
            continue;
        }
        let (flag, inline) = match argument.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
            _ => (argument.as_str(), None),
        };
        if !allowed.contains(&flag) {
            return Err(Usage(format!("`{}` isn't an option here", service::shorten(flag, 64))));
        }
        let mut value = || {
            inline
                .clone()
                .or_else(|| iter.next().cloned())
                .ok_or_else(|| Usage(format!("`{flag}` needs a value")))
        };
        let limits = &mut arguments.limits;
        let serve = &mut arguments.serve;
        match flag {
            "--index" => arguments.specs.push(SetSpec::parse_index(&value()?).map_err(Usage)?),
            "--subset" => arguments.specs.push(SetSpec::parse_subset(&value()?).map_err(Usage)?),
            "--threads" => arguments.threads = Some(number(flag, &value()?, 1)?),
            "--table-memory" => arguments.load.table_memory = table_memory(&value()?)?,
            "--state-dir" => arguments.load.state_dir = Some(PathBuf::from(value()?)),
            "--max-change-records" => limits.max_change_records = number(flag, &value()?, 1)?,
            "--max-remove-ids" => limits.max_remove_ids = number(flag, &value()?, 1)?,
            "--max-log-bytes" => limits.max_log_bytes = number(flag, &value()?, 1)?,
            "--repeat-window" => {
                arguments.load.repeat_window = Duration::from_millis(millis(flag, &value()?)?);
            }
            "--max-values-fast" => limits.max_values_fast = number(flag, &value()?, 1)?,
            "--max-values" => limits.max_values = number(flag, &value()?, 1)?,
            "--max-options-bytes" => limits.max_options_bytes = number(flag, &value()?, 1)?,
            "--max-radius-64" => limits.max_radius_64 = number(flag, &value()?, 0)?,
            "--max-radius-256" => limits.max_radius_256 = number(flag, &value()?, 0)?,
            "--max-matches" => limits.max_matches = number(flag, &value()?, 1)?,
            "--fast-query-time" => limits.query_time_fast_ms = millis(flag, &value()?)?,
            "--query-time" => limits.query_time_ms = millis(flag, &value()?)?,
            "--max-result-bytes" => limits.max_result_bytes = number(flag, &value()?, 1)?,
            "--input" => arguments.input = Some(PathBuf::from(value()?)),
            "--lane" => {
                arguments.lane = match value()?.as_str() {
                    "fast" => Lane::Fast,
                    "bulk" => Lane::Bulk,
                    _ => return Err(Usage("`--lane` is `fast` or `bulk`".to_owned())),
                };
            }
            "--sample" => arguments.sample = Some(number(flag, &value()?, 1)?),
            "--max-distance" => arguments.max_distance = Some(number(flag, &value()?, 0)?),
            "--seed" => arguments.seed = Some(number(flag, &value()?, 0)?),
            "--stats-sample" => arguments.load.sample = number(flag, &value()?, 0)?,
            "--stats-max-distance-64" => arguments.load.max_distance_64 = number(flag, &value()?, 0)?,
            "--stats-max-distance-256" => arguments.load.max_distance_256 = number(flag, &value()?, 0)?,
            "--redis" => serve.redis = Some(value()?),
            "--key-prefix" => serve.key_prefix = value()?,
            "--kind" => serve.kind = Some(value()?),
            "--consumer" => serve.consumer = Some(value()?),
            "--jobs" => serve.jobs = number(flag, &value()?, 1)?,
            "--fast-jobs" => serve.fast_jobs = number(flag, &value()?, 1)?,
            "--no-fast" => serve.no_fast = true,
            "--reload-seconds" => serve.reload = Duration::from_millis(millis(flag, &value()?)?),
            "--shutdown-grace" => serve.shutdown_grace = Duration::from_millis(millis(flag, &value()?)?),
            "--stats-file" => serve.stats_file = Some(PathBuf::from(value()?)),
            _ => serve.heartbeat = Duration::from_millis(millis(flag, &value()?)?),
        }
    }
    if let Some(threads) = arguments.threads {
        arguments.load.threads = threads;
    }
    if let Some(seed) = arguments.seed {
        arguments.load.seed = seed;
    }
    if let Some(sample) = arguments.sample {
        arguments.load.sample = sample;
    }
    if let Some(distance) = arguments.max_distance {
        arguments.load.max_distance_64 = distance;
        arguments.load.max_distance_256 = distance;
    }
    arguments
        .limits
        .validate()
        .map_err(|message| Usage(format!("the limits don't fit together: {message}")))?;
    arguments.load.max_log_read_bytes = arguments.limits.log_read_bound();
    Ok(arguments)
}

fn number<T: std::str::FromStr + PartialOrd + From<u8>>(flag: &str, text: &str, least: u8) -> Result<T, Usage> {
    match text.parse::<T>() {
        Ok(value) if value >= T::from(least) => Ok(value),
        _ => Err(Usage(format!(
            "`{flag}` takes a whole number of at least {least}, not `{}`",
            service::shorten(text, 32)
        ))),
    }
}

/// Seconds, decimals allowed, as whole milliseconds: at least 1 ms and at most a day.
fn millis(flag: &str, text: &str) -> Result<u64, Usage> {
    match text.parse::<f64>() {
        Ok(seconds) if seconds.is_finite() && (0.001..=86_400.0).contains(&seconds) =>
        {
            #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "checked above")]
            Ok((seconds * 1000.0).round() as u64)
        }
        _ => Err(Usage(format!(
            "`{flag}` takes seconds from 0.001 to 86400, not `{}`",
            service::shorten(text, 32)
        ))),
    }
}

fn table_memory(text: &str) -> Result<TableMemory, Usage> {
    if text == "auto" {
        return Ok(TableMemory::Auto);
    }
    let (digits, shift) = match text.char_indices().last() {
        Some((at, 'k' | 'K')) => (&text[..at], 10),
        Some((at, 'm' | 'M')) => (&text[..at], 20),
        Some((at, 'g' | 'G')) => (&text[..at], 30),
        _ => (text, 0),
    };
    digits
        .parse::<u64>()
        .ok()
        .and_then(|bytes| bytes.checked_mul(1 << shift))
        .map(TableMemory::Bytes)
        .ok_or_else(|| {
            Usage(format!(
                "`--table-memory` is `auto` or bytes with an optional k, m or g, not `{}`",
                service::shorten(text, 32)
            ))
        })
}

/// The catalog of the sets on the command line, loaded once, each event told on standard error.
fn load(arguments: &Arguments, neighbours: bool) -> Result<Arc<Catalog>, Usage> {
    let mut config = arguments.load.clone();
    config.neighbours = neighbours;
    let catalog = Catalog::new(arguments.specs.clone(), config).map_err(Usage)?;
    catalog.refresh(&mut |event| match event {
        Event::Refused { set, reason } => eprintln!("legit-hamming: `{set}`: {reason}"),
        Event::Failed {
            set, snapshot, reason, ..
        } => {
            eprintln!("legit-hamming: `{set}`: snapshot `{snapshot}` failed to load: {reason}");
        }
        Event::LogRefused { set, reason } => eprintln!("legit-hamming: `{set}`: its change log is refused: {reason}"),
        _ => {}
    });
    Ok(Arc::new(catalog))
}

fn service(arguments: &Arguments, catalog: Arc<Catalog>) -> Service {
    Service::new(catalog, arguments.limits, arguments.load.threads)
}

fn query(arguments: &Arguments) -> Result<ExitCode, Usage> {
    let reader: Box<dyn BufRead> = match &arguments.input {
        Some(path) if path.as_os_str() != "-" => Box::new(BufReader::with_capacity(
            1 << 16,
            File::open(path).map_err(|error| Usage(format!("couldn't open `{}`: {error}", path.display())))?,
        )),
        _ => Box::new(BufReader::with_capacity(1 << 16, io::stdin())),
    };
    // A set that didn't load is told on standard error, and its searches are answered
    // `not_ready`, line by line, as the stream answers them...
    let catalog = load(arguments, false)?;
    for (set, why) in catalog.unready() {
        eprintln!("legit-hamming: `{set}` can't be searched: {why}");
    }
    let service = service(arguments, catalog);
    let mut out = BufWriter::new(io::stdout().lock());
    let mut failed = false;
    let result = each_line(reader, arguments.limits.max_options_bytes, |line| {
        let json = match line {
            Ok(options) => service.search(options, arguments.lane).map(|answer| answer.json),
            Err(error) => Err(error),
        }
        .unwrap_or_else(|error| {
            failed = true;
            error.to_json()
        });
        writeln!(out, "{json}")
    })
    .and_then(|()| out.flush());
    match result {
        Err(error) if error.kind() != io::ErrorKind::BrokenPipe => {
            eprintln!("legit-hamming: {error}");
            Ok(ExitCode::from(2))
        }
        _ if failed => Ok(ExitCode::from(1)),
        _ => Ok(ExitCode::SUCCESS),
    }
}

/// Call `each` with every line that isn't blank, or with the error a line too long or not UTF-8
/// is answered with. A line is read at most `most` bytes at a time: the rest of a longer one is
/// skipped, not held.
fn each_line(
    mut reader: impl BufRead,
    most: usize,
    mut each: impl FnMut(Result<&str, service::ServiceError>) -> io::Result<()>,
) -> io::Result<()> {
    let mut line = Vec::new();
    loop {
        line.clear();
        let read = Read::by_ref(&mut reader)
            .take(u64::try_from(most).unwrap_or(u64::MAX).saturating_add(2))
            .read_until(b'\n', &mut line)?;
        if read == 0 {
            return Ok(());
        }
        let ended = line.last() == Some(&b'\n');
        if ended {
            line.pop();
            if line.last() == Some(&b'\r') {
                line.pop();
            }
        }
        if line.len() > most {
            if !ended {
                reader.skip_until(b'\n')?;
            }
            each(Err(service::ServiceError::new(
                service::ErrorType::InvalidOptions,
                format!("the line is more than {most} bytes of `options`"),
            )))?;
            continue;
        }
        if line.iter().all(u8::is_ascii_whitespace) {
            continue;
        }
        match std::str::from_utf8(&line) {
            Ok(text) => each(Ok(text))?,
            Err(_) => each(Err(service::ServiceError::new(
                service::ErrorType::InvalidOptions,
                "the line isn't UTF-8",
            )))?,
        }
    }
}

fn stats(arguments: &Arguments) -> Result<ExitCode, Usage> {
    let catalog = load(arguments, true)?;
    let ready = catalog.unready().is_empty();
    let service = service(arguments, catalog);
    let mut out = io::stdout().lock();
    for line in service.all_stats() {
        if writeln!(out, "{line}").is_err() {
            return Ok(ExitCode::from(2));
        }
    }
    Ok(if ready { ExitCode::SUCCESS } else { ExitCode::from(1) })
}

fn verify(arguments: &Arguments) -> Result<ExitCode, Usage> {
    let [dir] = arguments.positional.as_slice() else {
        return Err(Usage("`verify` takes one snapshot directory".to_owned()));
    };
    let started = Instant::now();
    let (sound, object) = match verify_snapshot(dir.as_ref()) {
        Ok(verified) => (
            true,
            serde_json::json!({"snapshot": dir, "sound": true, "seconds": started.elapsed().as_secs_f64(), "holds": verified}),
        ),
        Err(error) => (
            false,
            serde_json::json!({"snapshot": dir, "sound": false, "error": error}),
        ),
    };
    println!("{object}");
    Ok(if sound { ExitCode::SUCCESS } else { ExitCode::from(1) })
}

fn info() -> Result<ExitCode, Usage> {
    let cpu = Cpu::detect();
    let object = serde_json::json!({
        "program": "legit-hamming",
        "version": env!("CARGO_PKG_VERSION"),
        "format": service::FORMAT,
        "snapshot": {"format": snapshot::FORMAT, "version": snapshot::VERSION},
        "serve": cfg!(feature = "serve"),
        "cpu": {
            "arch": cpu.arch,
            "features": cpu.features,
            "paths": cpu.paths.iter().map(|isa| isa.name()).collect::<Vec<_>>(),
            "path_64": cpu.best64.name(),
            "path_256": cpu.best256.name(),
            "threads": cpu.threads,
        },
        "memory": {"available": service::available_memory()},
        "limits": Limits::default(),
    });
    let json = serde_json::to_string_pretty(&object).map_err(|error| Usage(error.to_string()))?;
    if writeln!(io::stdout().lock(), "{json}").is_err() {
        return Ok(ExitCode::from(2));
    }
    Ok(ExitCode::SUCCESS)
}