legit-hamming 0.1.3

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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
//! Changes to an index through its log, against a model: random interleavings of `append`,
//! `replace` and `remove`, repeats of earlier tasks, snapshot swaps with and without `covers_seq`
//! (each one read row by row at different moments after the position it covers), refused
//! snapshots, restarts, and searches with limits, after every step compared with a plain map and a
//! brute-force search. Then the log cut at every byte and damaged at every byte, the lock, the
//! bound, the repeat window, and a change on a service that takes none.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use legit_hamming::service::{
    Catalog, ErrorType, Lane, Limits, LoadConfig, Service, ServiceError, SetSpec, log as change_log,
};
use legit_hamming::{Records, Value, snapshot};
use serde_json::{Value as Json, json};

use crate::service::SetDir;
use crate::support::{Rng, TempDir};

const INDEX: &str = "images";

/// A service over one index with a state directory, which it writes as `serve` does.
pub struct Harness {
    pub set: SetDir,
    pub state: TempDir,
    pub limits: Limits,
    pub repeat_window: Duration,
    pub service: Option<Service>,
    pub events: Vec<String>,
}

impl Harness {
    pub fn new(limits: Limits) -> Self {
        let state = TempDir::new();
        fs::create_dir_all(&state.0).expect("a state directory");
        Self {
            set: SetDir::new(),
            state,
            limits,
            repeat_window: Duration::from_secs(3600),
            service: None,
            events: Vec::new(),
        }
    }

    pub fn config(&self, write: bool) -> LoadConfig {
        let mut config = crate::service::load_config(false);
        config.state_dir = Some(self.state.0.clone());
        config.write_changes = write;
        config.repeat_window = self.repeat_window;
        config.max_log_read_bytes = self.limits.log_read_bound();
        config
    }

    /// Open the service again, as a restarted program does, and load `CURRENT`.
    pub fn open(&mut self) {
        self.service = None;
        let catalog =
            Catalog::new(vec![SetSpec::index(INDEX, self.set.path())], self.config(true)).expect("the catalog opens");
        let service = Service::new(Arc::new(catalog), self.limits, 2);
        self.service = Some(service);
        self.refresh();
    }

    pub fn refresh(&mut self) {
        let mut events = Vec::new();
        self.service()
            .catalog()
            .refresh(&mut |event| events.push(format!("{event:?}")));
        self.events.extend(events);
    }

    pub fn service(&self) -> &Service {
        self.service.as_ref().expect("open")
    }

    pub fn log_path(&self) -> PathBuf {
        self.state.0.join(INDEX).join(change_log::LOG_FILE)
    }

    pub fn change(&self, task_id: &str, name: &str, options: &Json) -> Result<Json, ServiceError> {
        self.service()
            .change(task_id, name, &options.to_string())
            .map(|json| serde_json::from_str(&json).expect("a result is JSON"))
    }

    pub fn stats(&self) -> Json {
        let options = json!({"format": 1, "index": INDEX}).to_string();
        serde_json::from_str(&self.service().stats(&options).expect("stats")).expect("JSON")
    }

    pub fn search(&self, options: &Json) -> Result<Json, ServiceError> {
        crate::service::search(self.service(), options, Lane::Bulk)
    }
}

fn records_options<V: Value>(records: &[(u64, V)]) -> Json {
    json!({
        "format": 1, "index": INDEX, "width": V::BITS,
        "records": records.iter().map(|(id, value)| json!([id, value.to_hex()])).collect::<Vec<_>>(),
    })
}

fn remove_options<V: Value>(ids: &[u64]) -> Json {
    json!({"format": 1, "index": INDEX, "width": V::BITS, "ids": ids})
}

/// A change task's name and records, a removal's values `None`.
type Task<V> = (&'static str, Vec<(u64, Option<V>)>);

/// What a log held once read: every record and the position, or `None` for a refused index.
type Held<V> = Option<(BTreeMap<u64, V>, u64)>;

/// What a change answered: its result, or a conflict's ids and count, or another error's code.
#[derive(Debug, Clone, PartialEq)]
enum Answer {
    Applied(Json),
    Conflict(Vec<u64>, u64),
}

fn answer(result: Result<Json, ServiceError>) -> Answer {
    match result {
        Ok(json) => Answer::Applied(json),
        Err(error) if error.error_type == ErrorType::Conflict => {
            Answer::Conflict(error.ids.clone().expect("ids"), error.count.expect("a count"))
        }
        Err(error) => panic!("a change was refused: {error}"),
    }
}

/// The plain model: the first snapshot, every change applied since, in order, and the state they
/// make.
struct Model<V> {
    origin: BTreeMap<u64, V>,
    /// Each id's changes, `(seq, value)`, in order.
    history: BTreeMap<u64, Vec<(u64, Option<V>)>>,
    truth: BTreeMap<u64, V>,
    position: u64,
    /// The position the service's log has dropped changes to.
    base: u64,
    /// Every change task sent, with its answer.
    sent: Vec<(String, &'static str, Json, Answer)>,
}

impl<V: Value> Model<V> {
    /// Each id's state once every change to `seq` is applied.
    fn at(&self, id: u64, seq: u64) -> Option<V> {
        match self
            .history
            .get(&id)
            .and_then(|changes| changes.iter().rev().find(|(at, _)| *at <= seq))
        {
            Some((_, value)) => *value,
            None => self.origin.get(&id).copied(),
        }
    }

    /// The answer a change task gets, and the changes it makes: the rules, done again plainly.
    fn apply(&mut self, name: &'static str, records: &[(u64, Option<V>)]) -> Answer {
        let mut conflicts = Vec::new();
        let (mut added, mut changed, mut removed, mut unchanged) = (0, 0, 0, 0);
        for &(id, value) in records {
            match (self.truth.get(&id), value) {
                (Some(held), Some(value)) if *held == value => unchanged += 1,
                (Some(_), Some(_)) if name == "append" => conflicts.push(id),
                (Some(_), Some(_)) => changed += 1,
                (None, Some(_)) => added += 1,
                (Some(_), None) => removed += 1,
                (None, None) => unchanged += 1,
            }
        }
        if !conflicts.is_empty() {
            let count = conflicts.len() as u64;
            conflicts.truncate(100);
            return Answer::Conflict(conflicts, count);
        }
        for &(id, value) in records {
            self.position += 1;
            self.history.entry(id).or_default().push((self.position, value));
            match value {
                Some(value) => self.truth.insert(id, value),
                None => self.truth.remove(&id),
            };
        }
        Answer::Applied(json!({
            "format": 1, "index": INDEX, "seq": self.position,
            "added": added, "changed": changed, "removed": removed, "unchanged": unchanged,
        }))
    }
}

/// Every record of `truth` within `radius` of `query`, by distance then id, cut as `limit` and the
/// size bound cut it: what one plain search over the snapshot with every change applied gives.
fn reference<V: Value>(
    truth: &BTreeMap<u64, V>,
    query: V,
    radius: u32,
    limit: Option<usize>,
    max_matches: usize,
    exclude_zero: bool,
) -> (Vec<Json>, Option<&'static str>) {
    let mut found: Vec<(u32, u64, V)> = truth
        .iter()
        .map(|(&id, &value)| (value.distance(&query), id, value))
        .filter(|&(distance, _, value)| distance <= radius && !(exclude_zero && value.is_zero()))
        .collect();
    found.sort_unstable_by_key(|&(distance, id, _)| (distance, id));
    let keep = match limit {
        Some(limit) if limit <= max_matches => (limit, "limit"),
        _ => (max_matches, "size"),
    };
    let cut = (found.len() > keep.0).then_some(keep.1);
    found.truncate(keep.0);
    let matches = found
        .into_iter()
        .map(|(distance, id, value)| json!({"id": id, "value": value.to_hex(), "distance": distance}))
        .collect();
    (matches, cut)
}

/// A value near one of a few centres, so searches find several, and now and then all zeros.
fn value<V: Value>(rng: &mut Rng, centres: &[V]) -> V {
    if rng.below(40) == 0 {
        return V::from_words(&[0; 4][..V::WORDS]);
    }
    let centre = centres[rng.below(centres.len())];
    let flips = rng.below(V::BITS as usize / 10) as u32;
    rng.flip(centre, flips)
}

/// An id from a small universe, so changes meet the same ids again, and a few at the top of the
/// range.
fn id(rng: &mut Rng) -> u64 {
    if rng.below(20) == 0 {
        u64::MAX - rng.below(4) as u64
    } else {
        rng.below(240) as u64
    }
}

fn ids(rng: &mut Rng, most: usize) -> Vec<u64> {
    let mut ids: Vec<u64> = (0..1 + rng.below(most)).map(|_| id(rng)).collect();
    ids.sort_unstable();
    ids.dedup();
    ids
}

fn records_of<V: Value>(map: &BTreeMap<u64, V>) -> Records<V> {
    Records::from_records(map.iter().map(|(&id, &value)| (id, value))).expect("ids rise")
}

/// Run the model for `steps` steps at `V`'s width.
fn model<V: Value>(seed: u64, steps: usize, limits: Limits) {
    let mut rng = Rng::new(seed);
    let centres: Vec<V> = (0..6).map(|_| rng.value()).collect();
    let max_radius = if V::BITS == 64 { 12 } else { 40 };
    let mut origin = BTreeMap::new();
    for _ in 0..150 {
        origin.insert(id(&mut rng), value(&mut rng, &centres));
    }
    let mut harness = Harness::new(limits);
    harness.set.publish("s0", &records_of(&origin));
    harness.open();
    let mut model = Model {
        truth: origin.clone(),
        origin,
        history: BTreeMap::new(),
        position: 0,
        base: 0,
        sent: Vec::new(),
    };
    let mut snapshot = "s0".to_owned();
    let mut snapshots = 0;
    let mut counts = BTreeMap::<&str, usize>::new();
    for step in 0..steps {
        let roll = rng.below(100);
        let what = match roll {
            0..=19 => {
                let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12)
                    .into_iter()
                    .map(|id| {
                        let same = model.truth.get(&id).copied().filter(|_| rng.below(2) == 0);
                        (id, Some(same.unwrap_or_else(|| value(&mut rng, &centres))))
                    })
                    .collect();
                send(&harness, &mut model, "append", &records, step)
            }
            20..=37 => {
                let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12)
                    .into_iter()
                    .map(|id| {
                        let same = model.truth.get(&id).copied().filter(|_| rng.below(4) == 0);
                        (id, Some(same.unwrap_or_else(|| value(&mut rng, &centres))))
                    })
                    .collect();
                send(&harness, &mut model, "replace", &records, step)
            }
            38..=49 => {
                let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12).into_iter().map(|id| (id, None)).collect();
                send(&harness, &mut model, "remove", &records, step)
            }
            50..=57 if !model.sent.is_empty() => {
                // A task delivered again, perhaps after later changes to its ids: answered as the
                // first time, and changing nothing...
                let (task_id, name, options, first) = model.sent[rng.below(model.sent.len())].clone();
                assert_eq!(
                    answer(harness.change(&task_id, name, &options)),
                    first,
                    "step {step}: a repeat"
                );
                "repeat"
            }
            58..=61 => {
                snapshots += 1;
                let name = format!("s{snapshots}");
                let refused = swap(&mut harness, &mut model, &mut rng, &name);
                if refused {
                    // As an operator would: `CURRENT` back to the snapshot served...
                    harness.set.point(&snapshot);
                } else {
                    snapshot = name;
                }
                if refused { "refused snapshot" } else { "swap" }
            }
            62..=63 => {
                harness.open();
                "restart"
            }
            _ => "search",
        };
        *counts.entry(what).or_default() += 1;
        check(&harness, &model, &mut rng, &centres, &snapshot, max_radius, step);
    }
    // Every kind of step happened, many times...
    for what in [
        "append",
        "replace",
        "remove",
        "repeat",
        "swap",
        "refused snapshot",
        "restart",
    ] {
        assert!(
            counts.get(what).copied().unwrap_or(0) >= 3,
            "too few `{what}` steps: {counts:?}"
        );
    }
}

fn send<V: Value>(
    harness: &Harness,
    model: &mut Model<V>,
    name: &'static str,
    records: &[(u64, Option<V>)],
    step: usize,
) -> &'static str {
    let task_id = format!("app_{step}");
    let options = if name == "remove" {
        remove_options::<V>(&records.iter().map(|&(id, _)| id).collect::<Vec<_>>())
    } else {
        let records: Vec<(u64, V)> = records
            .iter()
            .map(|&(id, value)| (id, value.expect("a value")))
            .collect();
        records_options(&records)
    };
    let expected = model.apply(name, records);
    let got = answer(harness.change(&task_id, name, &options));
    assert_eq!(got, expected, "step {step}: `{name}`");
    model.sent.push((task_id, name, options, expected));
    name
}

/// Write a snapshot as an exporter would, and swap it in. Most cover a position the service has
/// logged, each row read at its own moment at or after it; some name no position while the log
/// is whole; and some are wrong, which the service must refuse: past the log's last change, short
/// of what it dropped, or naming none once it has dropped any. Returns whether it was refused.
fn swap<V: Value>(harness: &mut Harness, model: &mut Model<V>, rng: &mut Rng, name: &str) -> bool {
    let roll = rng.below(10);
    let (covers, from, bad) = match roll {
        0 => (Some(model.position + 1 + rng.below(3) as u64), model.position, true),
        1 if model.base > 0 => (Some(model.base - 1), model.position, true),
        2 if model.base > 0 => (None, model.position, true),
        2..=3 if model.base == 0 => (None, 0, false),
        _ => {
            let covers = model.base + rng.below((model.position - model.base + 1) as usize) as u64;
            (Some(covers), covers, false)
        }
    };
    let mut ids: Vec<u64> = model.origin.keys().chain(model.history.keys()).copied().collect();
    ids.sort_unstable();
    ids.dedup();
    let mut rows = BTreeMap::new();
    for id in ids {
        let read_at = from + rng.below((model.position - from + 1) as usize) as u64;
        if let Some(value) = model.at(id, read_at) {
            rows.insert(id, value);
        }
    }
    snapshot::write_covering(&harness.set.path().join(name), &records_of(&rows), 61, covers).expect("written");
    harness.set.point(name);
    harness.refresh();
    let stats = harness.stats();
    if let Ok(metadata) = fs::metadata(harness.log_path()) {
        assert_eq!(stats["changes"]["log"]["bytes"], metadata.len(), "{stats}");
    }
    if bad {
        assert_eq!(stats["last_failure"]["snapshot"], name, "{stats}");
        assert_eq!(stats["last_failure"]["code"], "covers_seq", "{stats}");
        assert!(stats["last_failure"]["reason"].is_string());
        assert_ne!(stats["snapshot"]["name"], name);
    } else {
        assert_eq!(stats["snapshot"]["name"], name, "{stats}");
        assert_eq!(stats["seq"], model.position);
        if let Some(covers) = covers {
            model.base = model.base.max(covers);
        }
        assert_eq!(stats["changes"]["log"]["base_seq"], model.base, "{stats}");
    }
    bad
}

/// Search the service and the model alike, and compare.
fn check<V: Value>(
    harness: &Harness,
    model: &Model<V>,
    rng: &mut Rng,
    centres: &[V],
    snapshot: &str,
    max_radius: usize,
    step: usize,
) {
    for _ in 0..2 {
        let query: V = value(rng, centres);
        let radius = rng.below(max_radius + 1) as u32;
        let limit = (rng.below(3) == 0).then(|| 1 + rng.below(8));
        let exclude_zero = rng.below(4) == 0;
        let mut options = json!({
            "format": 1, "index": INDEX, "width": V::BITS, "radius": radius,
            "values": [query.to_hex()], "exclude_zero": exclude_zero,
        });
        if let Some(limit) = limit {
            options["limit"] = json!(limit);
        }
        let result = harness.search(&options).expect("a search is answered");
        let (matches, cut) = reference(
            &model.truth,
            query,
            radius,
            limit,
            harness.limits.max_matches,
            exclude_zero,
        );
        let entry = &result["queries"][0];
        assert_eq!(result["snapshot"], snapshot, "step {step}");
        assert_eq!(result["seq"], model.position, "step {step}");
        assert_eq!(
            entry["matches"],
            Json::Array(matches),
            "step {step}: radius {radius}, limit {limit:?}"
        );
        assert_eq!(entry["complete"], cut.is_none(), "step {step}");
        assert_eq!(entry["cut_by"], cut.map_or(Json::Null, |cut| json!(cut)), "step {step}");
    }
}

#[test]
fn the_model_at_64_bits() {
    model::<u64>(1, 3_000, Limits::default());
}

#[test]
fn the_model_at_256_bits() {
    model::<[u64; 4]>(2, 3_000, Limits::default());
}

#[test]
fn the_model_with_a_small_size_bound() {
    // A size bound below some limits: a list cut by size, by limit, and neither...
    let mut limits = Limits::default();
    limits.max_matches = 4;
    model::<u64>(3, 1_500, limits);
}

/// A history of change tasks of each kind, a conflict and a repeat among them, over a small
/// snapshot: the log's bytes, and after each whole task the log's length, the records held and the
/// position.
struct History<V> {
    harness: Harness,
    bytes: Vec<u8>,
    /// `(end, records, seq)`: the log's length after the header and after each whole task.
    whole: Vec<(usize, BTreeMap<u64, V>, u64)>,
}

fn wide_limits() -> Limits {
    let mut limits = Limits::default();
    limits.max_radius_64 = 64;
    limits.max_radius_256 = 256;
    limits
}

fn history<V: Value>(seed: u64) -> History<V> {
    let mut rng = Rng::new(seed);
    let mut harness = Harness::new(wide_limits());
    let mut truth: BTreeMap<u64, V> = (0..6).map(|id| (id * 10, rng.value())).collect();
    harness.set.publish("s0", &records_of(&truth));
    harness.open();
    let mut model = Model {
        origin: truth.clone(),
        history: BTreeMap::new(),
        truth: truth.clone(),
        position: 0,
        base: 0,
        sent: Vec::new(),
    };
    let mut whole = Vec::new();
    let tasks: Vec<Task<V>> = vec![
        ("append", vec![(5, Some(rng.value())), (60, Some(rng.value()))]),
        (
            "replace",
            vec![(0, Some(rng.value())), (5, Some(rng.value())), (99, Some(rng.value()))],
        ),
        ("append", vec![(10, Some(rng.value()))]),
        ("remove", vec![(20, None), (21, None), (60, None)]),
        ("append", vec![(20, Some(rng.value()))]),
        ("replace", vec![(30, Some(truth[&30]))]),
    ];
    for (step, (name, records)) in tasks.iter().enumerate() {
        send(&harness, &mut model, name, records, step);
        let bytes = fs::read(harness.log_path()).expect("the log");
        if whole.is_empty() {
            // The header ends where the first entry begins...
            let header = bytes[4..]
                .windows(4)
                .position(|window| window == change_log::MAGIC)
                .expect("a second record")
                + 4;
            whole.push((header, model.origin.clone(), 0));
        }
        whole.push((bytes.len(), model.truth.clone(), model.position));
    }
    assert!(
        matches!(model.sent[2].3, Answer::Conflict(..)),
        "the history holds a conflict"
    );
    // A repeat writes nothing...
    let (task_id, name, options, first) = model.sent[1].clone();
    assert_eq!(answer(harness.change(&task_id, name, &options)), first);
    truth.clone_from(&model.truth);
    let bytes = fs::read(harness.log_path()).expect("the log");
    assert_eq!(bytes.len(), whole.last().expect("tasks").0);
    History { harness, bytes, whole }
}

/// Open a service over `history`'s snapshot with `bytes` as its log, and say what it holds: every
/// record and the position, or `None` when the index is refused.
fn reopen<V: Value>(history: &History<V>, bytes: &[u8]) -> (Held<V>, Harness) {
    let mut harness = Harness::new(wide_limits());
    fs::remove_dir_all(harness.set.path()).expect("an empty set directory");
    copy_dir(history.harness.set.path(), harness.set.path());
    let dir = harness.state.0.join(INDEX);
    fs::create_dir_all(&dir).expect("the index's state");
    fs::write(dir.join(change_log::LOG_FILE), bytes).expect("the log");
    harness.open();
    let stats = harness.stats();
    if stats["state"] == "refused" {
        assert!(stats["refused"].is_string());
        return (None, harness);
    }
    let options = json!({
        "format": 1, "index": INDEX, "width": V::BITS, "radius": V::BITS,
        "values": [V::from_words(&[0; 4][..V::WORDS]).to_hex()],
    });
    let result = harness.search(&options).expect("searched");
    let held = result["queries"][0]["matches"]
        .as_array()
        .expect("matches")
        .iter()
        .map(|found| {
            let id = found["id"].as_u64().expect("an id");
            (id, V::from_hex(found["value"].as_str().expect("hex")).expect("hex"))
        })
        .collect();
    (Some((held, result["seq"].as_u64().expect("seq"))), harness)
}

fn copy_dir(from: &Path, to: &Path) {
    fs::create_dir_all(to).expect("a directory");
    for entry in fs::read_dir(from).expect("a directory") {
        let entry = entry.expect("an entry");
        if entry.file_type().expect("a type").is_dir() {
            copy_dir(&entry.path(), &to.join(entry.file_name()));
        } else {
            fs::copy(entry.path(), to.join(entry.file_name())).expect("copied");
        }
    }
}

fn cut_at_every_byte<V: Value>(seed: u64) {
    let history = history::<V>(seed);
    let header = history.whole[0].0;
    for cut in 0..=history.bytes.len() {
        let (held, harness) = reopen(&history, &history.bytes[..cut]);
        if cut < header {
            assert!(held.is_none(), "a log cut inside its header, at {cut}, is refused");
            continue;
        }
        // Exactly the whole tasks before the cut, and the rest cut from the file...
        let (end, records, seq) = history
            .whole
            .iter()
            .rev()
            .find(|(end, _, _)| *end <= cut)
            .expect("the header is whole");
        assert_eq!(held.as_ref(), Some(&(records.clone(), *seq)), "cut at {cut}");
        assert_eq!(
            fs::read(harness.log_path()).expect("the log").len(),
            *end,
            "cut at {cut}"
        );
        if cut % 7 == 0 {
            // ...and the next change follows the last whole one: no seq given twice.
            let next = harness
                .change("next", "replace", &records_options(&[(3, rng_value::<V>(cut))]))
                .expect("applied");
            assert_eq!(next["seq"], *seq + 1, "cut at {cut}");
        }
    }
}

fn rng_value<V: Value>(seed: usize) -> V {
    Rng::new(seed as u64).value()
}

fn damaged_at_every_byte<V: Value>(seed: u64) {
    let history = history::<V>(seed);
    let (last_start, before, seq) = history.whole[history.whole.len() - 2].clone();
    for at in 0..history.bytes.len() {
        let mut bytes = history.bytes.clone();
        bytes[at] ^= 1 << (at % 8);
        let (held, _) = reopen(&history, &bytes);
        if at >= last_start {
            // The last task can't be told from one that never finished: it is cut...
            assert_eq!(held, Some((before.clone(), seq)), "damaged at {at}");
        } else {
            assert!(
                held.is_none(),
                "damage at {at}, before the last task, refuses the index"
            );
        }
    }
}

#[test]
fn a_log_cut_at_every_byte_keeps_exactly_its_whole_tasks() {
    cut_at_every_byte::<u64>(10);
    cut_at_every_byte::<[u64; 4]>(11);
}

#[test]
fn a_log_damaged_at_any_byte_is_cut_in_its_last_task_and_refused_before() {
    damaged_at_every_byte::<u64>(12);
    damaged_at_every_byte::<[u64; 4]>(13);
}

#[test]
fn zeros_and_a_stray_whole_record_after_the_last_task() {
    let history = history::<u64>(14);
    // Blocks of zeros, as a file extended by a crash before its data was written...
    let mut bytes = history.bytes.clone();
    bytes.extend_from_slice(&[0; 4096]);
    let (held, _) = reopen(&history, &bytes);
    let (_, records, seq) = history.whole.last().expect("tasks").clone();
    assert_eq!(held, Some((records, seq)));
    // ...but a whole record of an earlier task after them is damage, not an unfinished task.
    let mut bytes = history.bytes.clone();
    let (first_end, second_end) = (history.whole[0].0, history.whole[1].0);
    bytes.extend_from_slice(&[0; 100]);
    bytes.extend_from_slice(&history.bytes[first_end..second_end]);
    assert_eq!(reopen(&history, &bytes).0, None);
}

#[test]
fn a_task_logged_but_not_answered_is_answered_as_the_first_time_after_later_changes() {
    let mut harness = Harness::new(Limits::default());
    harness
        .set
        .publish("s0", &records_of(&BTreeMap::from([(1u64, 0xffu64)])));
    harness.open();
    let first = harness
        .change("t1", "append", &records_options(&[(7, 0x0fu64)]))
        .expect("applied");
    // The worker dies after the log and before the result is read: a restart...
    harness.open();
    let later = harness
        .change("t2", "replace", &records_options(&[(7, 0xf0u64)]))
        .expect("applied");
    assert_eq!(later["seq"], 2);
    // ...then the task is delivered again: its first answer, and the later value stands.
    let again = harness
        .change("t1", "append", &records_options(&[(7, 0x0fu64)]))
        .expect("answered");
    assert_eq!(again, first);
    let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["00000000000000f0"]});
    let found = harness.search(&options).expect("searched");
    assert_eq!(
        found["queries"][0]["matches"],
        json!([{"id": 7, "value": "00000000000000f0", "distance": 0}])
    );
    assert_eq!(found["seq"], 2);
    // A conflict is remembered the same way: the answer doesn't change when the id is gone...
    let conflict = harness
        .change("t3", "append", &records_options(&[(7, 0x01u64)]))
        .expect_err("a conflict");
    assert_eq!(
        (conflict.error_type, conflict.ids.clone(), conflict.count),
        (ErrorType::Conflict, Some(vec![7]), Some(1))
    );
    harness
        .change("t4", "remove", &remove_options::<u64>(&[7]))
        .expect("removed");
    let again = harness
        .change("t3", "append", &records_options(&[(7, 0x01u64)]))
        .expect_err("the same conflict");
    assert_eq!(again, conflict);
}

/// The README's feeder, after a refusal that may pass later: `not_ready` applies nothing and isn't
/// remembered, so a copy of the same task still in the stream (one sent again after no answer,
/// say) is applied when it comes, whatever came between.
#[test]
fn a_refusal_that_may_pass_later_keeps_its_task_id_or_a_stale_copy_lands_an_older_value() {
    let search = |harness: &Harness| {
        let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 4, "values": ["0000000000000000"]});
        let found = harness.search(&options).expect("searched");
        found["queries"][0]["matches"]
            .as_array()
            .expect("matches")
            .iter()
            .find(|found| found["id"] == 7)
            .map(|found| found["value"].as_str().expect("a value").to_owned())
    };
    let (a, b) = (records_options(&[(7, 0x0au64)]), records_options(&[(7, 0x0bu64)]));
    for keeps_its_task in [false, true] {
        let mut harness = Harness::new(Limits::default());
        harness.open();
        // Record 7 is written as A, and its task refused: the index has no snapshot yet...
        let refused = harness.change("t1", "replace", &a).expect_err("not ready");
        assert_eq!(refused.error_type, ErrorType::NotReady);
        harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
        harness.refresh();
        let first = if keeps_its_task {
            // ...the feeder keeps the marks claimed and sends `t1` again, and only once it is
            // applied does B, written since, go in a new task...
            let first = harness.change("t1", "replace", &a).expect("applied");
            harness.change("t2", "replace", &b).expect("applied");
            Some(first)
        } else {
            // ...or it frees them, and B goes at once in a new task.
            harness.change("t2", "replace", &b).expect("applied");
            None
        };
        // Then a copy of `t1` still in the stream is delivered.
        let late = harness.change("t1", "replace", &a).expect("answered");
        if let Some(first) = first {
            assert_eq!(late, first, "a repeat, answered as the first time");
            assert_eq!(search(&harness).as_deref(), Some("000000000000000b"), "B stands");
        } else {
            assert_eq!(late["seq"], 2, "applied for the first time, after B");
            assert_eq!(
                search(&harness).as_deref(),
                Some("000000000000000a"),
                "A, the older value, landed last"
            );
        }
    }
}

#[test]
fn a_repeat_is_recognised_after_its_entries_are_dropped_within_the_window_only() {
    for (window, recognised) in [(Duration::from_secs(3600), true), (Duration::ZERO, false)] {
        let mut harness = Harness::new(Limits::default());
        harness.repeat_window = window;
        harness
            .set
            .publish("s0", &records_of(&BTreeMap::from([(1u64, 0xffu64)])));
        harness.open();
        let first = harness
            .change("t1", "replace", &records_options(&[(7, 0x0fu64)]))
            .expect("applied");
        harness
            .change("t2", "replace", &records_options(&[(7, 0xf0u64)]))
            .expect("applied");
        // A snapshot covering both: the log drops their entries...
        let rows = BTreeMap::from([(1u64, 0xffu64), (7, 0xf0)]);
        snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(2)).expect("written");
        harness.set.point("s1");
        harness.refresh();
        let stats = harness.stats();
        assert_eq!(stats["changes"]["log"]["entries"], 0, "{stats}");
        assert_eq!(
            stats["changes"]["log"]["tasks"],
            if recognised { 2 } else { 0 },
            "{stats}"
        );
        let again = harness
            .change("t1", "replace", &records_options(&[(7, 0x0fu64)]))
            .expect("answered");
        if recognised {
            assert_eq!(again, first);
        } else {
            // Forgotten: applied again, as a new change, which puts its old value back...
            assert_eq!(again["seq"], 3);
            assert_eq!(again["changed"], 1);
        }
        // Either way the log's position never goes back, across a restart too.
        harness.open();
        let next = harness
            .change("t9", "remove", &remove_options::<u64>(&[1]))
            .expect("removed");
        assert_eq!(next["seq"], if recognised { 3 } else { 4 });
    }
}

#[test]
fn a_change_that_changes_nothing_is_still_replayed_over_a_snapshot_read_before_it() {
    // The service holds 7 = a. The application sets 7 to b and back to a, and removes 8 it had just
    // added; its feeder sends the current values: a replace that changes nothing, and a remove of
    // an id the service never held. An export that noted position 0 had read 7 = b and 8 meanwhile.
    let mut harness = Harness::new(wide_limits());
    harness
        .set
        .publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
    harness.open();
    let unchanged = harness
        .change("t1", "replace", &records_options(&[(7, 0xaau64)]))
        .expect("applied");
    assert_eq!(
        (unchanged["seq"].clone(), unchanged["unchanged"].clone()),
        (json!(1), json!(1))
    );
    let unheld = harness
        .change("t2", "remove", &remove_options::<u64>(&[8]))
        .expect("applied");
    assert_eq!(
        (unheld["seq"].clone(), unheld["unchanged"].clone()),
        (json!(2), json!(1))
    );
    let rows = BTreeMap::from([(7u64, 0xbbu64), (8, 0xcc)]);
    snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(0)).expect("written");
    harness.set.point("s1");
    harness.refresh();
    let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 64, "values": ["0000000000000000"]});
    let found = harness.search(&options).expect("searched");
    assert_eq!(found["snapshot"], "s1");
    assert_eq!(
        found["queries"][0]["matches"],
        json!([{"id": 7, "value": "00000000000000aa", "distance": 4}])
    );
}

#[test]
fn a_second_writer_of_an_index_is_refused_and_a_reader_is_not() {
    let mut harness = Harness::new(Limits::default());
    harness
        .set
        .publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
    harness.open();
    harness
        .change("t1", "append", &records_options(&[(9, 0x01u64)]))
        .expect("applied");
    let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
    let error = Catalog::new(spec(), harness.config(true)).expect_err("the lock is held");
    assert!(error.contains("another process holds"), "{error}");
    // A reader takes no lock, and sees the change...
    let reader = Catalog::new(spec(), harness.config(false)).expect("a reader opens");
    reader.refresh(&mut |_| {});
    let service = Service::new(Arc::new(reader), Limits::default(), 1);
    let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["0000000000000001"]});
    let found = crate::service::search(&service, &options, Lane::Bulk).expect("searched");
    assert_eq!(found["seq"], 1);
    assert_eq!(found["queries"][0]["matches"][0]["id"], 9);
    // ...and takes no change.
    let refused = service
        .change("t2", "append", &records_options(&[(10, 0x01u64)]).to_string())
        .expect_err("a reader takes no change");
    assert_eq!(refused.error_type, ErrorType::InvalidTask);
}

#[cfg(unix)]
#[test]
fn a_state_directory_that_is_a_symbolic_link_is_refused_by_a_reader_and_a_writer() {
    // Another state directory holds a valid log of the index...
    let mut other = Harness::new(Limits::default());
    other.set.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
    other.open();
    other
        .change("t1", "append", &records_options(&[(9, 0x01u64)]))
        .expect("applied");
    other.service = None;
    // ...and this one's directory for the index is a link to it.
    let harness = Harness::new(Limits::default());
    harness
        .set
        .publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
    std::os::unix::fs::symlink(other.state.0.join(INDEX), harness.state.0.join(INDEX)).expect("a link");
    // Each refusal says it is a link, and where to.
    let linked_to = format!(
        "`{}` is a symbolic link to `{}`; it must be a directory, not a link",
        harness.state.0.join(INDEX).display(),
        other.state.0.join(INDEX).display()
    );
    let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
    // A reader refuses the index, and replays nothing through the link...
    let reader = Catalog::new(spec(), harness.config(false)).expect("a reader opens");
    reader.refresh(&mut |_| {});
    let service = Service::new(Arc::new(reader), Limits::default(), 1);
    let options = json!({"format": 1, "index": INDEX}).to_string();
    let stats: Json = serde_json::from_str(&service.stats(&options).expect("stats")).expect("JSON");
    assert_eq!(stats["state"], "refused", "{stats}");
    assert!(
        stats["refused"]
            .as_str()
            .is_some_and(|reason| reason.contains(&linked_to)),
        "{stats}"
    );
    let search = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["0000000000000001"]});
    let error = crate::service::search(&service, &search, Lane::Bulk).expect_err("refused");
    assert_eq!(error.error_type, ErrorType::NotReady);
    // ...and a writer doesn't open.
    let error = Catalog::new(spec(), harness.config(true)).expect_err("refused");
    assert!(error.contains(&linked_to), "{error}");
}

#[cfg(unix)]
#[test]
fn a_reader_refuses_a_log_that_is_a_dangling_link_or_a_pipe_and_reads_an_absent_one_as_empty() {
    let harness = Harness::new(Limits::default());
    harness
        .set
        .publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
    fs::create_dir_all(harness.state.0.join(INDEX)).expect("the state directory");
    let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
    // The index's state as a reader sees it, read on another thread so a read that blocks fails
    // the test instead of hanging it: `ready` or `refused`, and why.
    let read = || {
        let (sender, received) = std::sync::mpsc::channel();
        let (spec, config) = (spec(), harness.config(false));
        std::thread::spawn(move || {
            let reader = Catalog::new(spec, config).expect("a reader opens");
            reader.refresh(&mut |_| {});
            let service = Service::new(Arc::new(reader), Limits::default(), 1);
            let options = json!({"format": 1, "index": INDEX}).to_string();
            let stats: Json = serde_json::from_str(&service.stats(&options).expect("stats")).expect("JSON");
            let _ = sender.send(stats);
        });
        received.recv_timeout(Duration::from_secs(10))
    };
    // No log yet: the snapshot is served...
    let stats = read().expect("read");
    assert_eq!(
        (&stats["state"], &stats["seq"]),
        (&json!("ready"), &json!(0)),
        "{stats}"
    );
    // ...a link to a log that isn't there is a link, refused, not an absent log...
    let log = harness.log_path();
    std::os::unix::fs::symlink(harness.state.0.join("missing.log"), &log).expect("a link");
    let stats = read().expect("read");
    assert_eq!(stats["state"], "refused", "{stats}");
    assert!(
        stats["refused"]
            .as_str()
            .is_some_and(|reason| reason.contains("symbolic link")),
        "{stats}"
    );
    // ...and a pipe is refused before it is opened, which would wait for a writer.
    fs::remove_file(&log).expect("removed");
    let made = std::process::Command::new("mkfifo")
        .arg(&log)
        .status()
        .expect("mkfifo runs");
    assert!(made.success());
    let stats = read();
    if stats.is_err() {
        // Let the blocked reader go before failing.
        drop(fs::OpenOptions::new().write(true).open(&log));
    }
    let stats = stats.expect("a pipe is refused, not waited on");
    assert_eq!(stats["state"], "refused", "{stats}");
    assert!(
        stats["refused"]
            .as_str()
            .is_some_and(|reason| reason.contains("not a file")),
        "{stats}"
    );
}

#[test]
fn a_change_past_the_log_bound_is_refused_until_a_snapshot_covers_the_log() {
    let mut limits = Limits::default();
    limits.max_change_records = 10;
    limits.max_remove_ids = 10;
    // Room for the header and one task of ten 64-bit records (about 590 bytes), not two...
    limits.max_log_bytes = 1_000;
    let mut harness = Harness::new(limits);
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    let records: Vec<(u64, u64)> = (10..20).map(|id| (id, id)).collect();
    harness
        .change("t1", "append", &records_options(&records))
        .expect("applied");
    let full = harness
        .change("t2", "replace", &records_options(&records))
        .expect_err("past the bound");
    assert_eq!(full.error_type, ErrorType::LogFull);
    assert_eq!(harness.stats()["seq"], 10);
    let mut rows: BTreeMap<u64, u64> = records.iter().copied().collect();
    rows.insert(1, 1);
    snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(10)).expect("written");
    harness.set.point("s1");
    harness.refresh();
    let applied = harness
        .change("t2", "replace", &records_options(&records))
        .expect("room again");
    assert_eq!(applied["seq"], 20);
}

#[test]
fn a_change_with_too_many_records_is_named_with_its_article() {
    let mut limits = Limits::default();
    limits.max_change_records = 1;
    limits.max_remove_ids = 1;
    let mut harness = Harness::new(limits);
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    let records = json!({"format": 1, "index": INDEX, "width": 64,
                         "records": [[2, "0000000000000001"], [3, "0000000000000001"]]});
    let ids = json!({"format": 1, "index": INDEX, "width": 64, "ids": [2, 3]});
    for (name, options, message) in [
        (
            "append",
            &records,
            "the task holds 2 records; an `append` task takes at most 1",
        ),
        (
            "replace",
            &records,
            "the task holds 2 records; a `replace` task takes at most 1",
        ),
        ("remove", &ids, "the task holds 2 ids; a `remove` task takes at most 1"),
    ] {
        let error = harness.change("t", name, options).expect_err("refused");
        assert_eq!(
            (error.error_type, error.message.as_str()),
            (ErrorType::TooManyValues, message)
        );
    }
}

#[test]
fn change_tasks_are_checked_before_any_work() {
    let mut limits = Limits::default();
    limits.max_change_records = 3;
    limits.max_remove_ids = 4;
    let mut harness = Harness::new(limits);
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    let refused = |name: &str, options: Json| harness.change("t", name, &options).expect_err("refused").error_type;
    let pair = |id: u64| json!([id, "0000000000000001"]);
    let options = |records: Json| json!({"format": 1, "index": INDEX, "width": 64, "records": records});
    assert_eq!(refused("append", options(json!([]))), ErrorType::InvalidOptions);
    assert_eq!(
        refused("append", options(json!([pair(2), pair(2)]))),
        ErrorType::InvalidOptions
    );
    assert_eq!(
        refused("append", options(json!([pair(3), pair(2)]))),
        ErrorType::InvalidOptions
    );
    assert_eq!(
        refused("append", options(json!([[2, "zz"]]))),
        ErrorType::InvalidOptions
    );
    assert_eq!(
        refused("append", options(json!([[-2, "0000000000000001"]]))),
        ErrorType::InvalidOptions
    );
    assert_eq!(
        refused("append", options(json!([pair(1), pair(2), pair(3), pair(4)]))),
        ErrorType::TooManyValues
    );
    let remove = |ids: Json| json!({"format": 1, "index": INDEX, "width": 64, "ids": ids});
    assert_eq!(
        refused("remove", remove(json!([1, 2, 3, 4, 5]))),
        ErrorType::TooManyValues
    );
    assert_eq!(refused("remove", remove(json!(["1"]))), ErrorType::InvalidOptions);
    assert_eq!(refused("remove", options(json!([pair(1)]))), ErrorType::InvalidOptions);
    let subset = json!({"format": 1, "index": INDEX, "subset": "flagged", "width": 64, "records": [pair(1)]});
    assert_eq!(refused("append", subset), ErrorType::InvalidOptions);
    let wrong = json!({"format": 1, "index": INDEX, "width": 256, "records": [[1, "0".repeat(64)]]});
    assert_eq!(refused("replace", wrong), ErrorType::WidthMismatch);
    let unknown = json!({"format": 1, "index": "other", "width": 64, "records": [pair(1)]});
    assert_eq!(refused("replace", unknown), ErrorType::UnknownIndex);
    assert_eq!(refused("rename", options(json!([pair(1)]))), ErrorType::InvalidTask);
    // Nothing above was logged, and three records, the bound, are taken...
    assert_eq!(harness.stats()["seq"], 0);
    let taken = harness
        .change("t", "append", &options(json!([pair(1), pair(2), pair(3)])))
        .expect("applied");
    assert_eq!(
        taken,
        json!({"format": 1, "index": INDEX, "seq": 3, "added": 2, "changed": 0, "removed": 0, "unchanged": 1})
    );
}

#[test]
fn a_service_without_a_state_directory_takes_no_change() {
    let set = SetDir::new();
    set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    let service = crate::service::service(vec![SetSpec::index(INDEX, set.path())], Limits::default());
    assert!(!service.takes_changes());
    let error = service
        .change("t", "append", &records_options(&[(2, 2u64)]).to_string())
        .expect_err("no log");
    assert_eq!(error.error_type, ErrorType::InvalidTask);
    assert!(error.message.contains("--state-dir"));
}

#[test]
fn snapshots_an_index_with_changes_refuses() {
    let mut harness = Harness::new(Limits::default());
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    harness
        .change("t1", "append", &records_options(&[(2, 2u64)]))
        .expect("applied");
    let failure = |harness: &mut Harness, name: &str| {
        harness.set.point(name);
        harness.refresh();
        let stats = harness.stats();
        assert_eq!(stats["snapshot"]["name"], "s0", "{stats}");
        stats["last_failure"]["code"].as_str().expect("a code").to_owned()
    };
    // Values without ids...
    snapshot::write(
        &harness.set.path().join("bare"),
        &Records::from_values([1u64, 2]).expect("values"),
        10,
    )
    .expect("written");
    assert_eq!(failure(&mut harness, "bare"), "ids");
    // ...another width than the log's...
    let wide = Records::from_records([(1u64, [1u64, 0, 0, 0])]).expect("records");
    snapshot::write(&harness.set.path().join("wide"), &wide, 10).expect("written");
    assert_eq!(failure(&mut harness, "wide"), "width");
    // ...and claiming changes never logged.
    let rows = BTreeMap::from([(1u64, 1u64), (2, 2)]);
    snapshot::write_covering(&harness.set.path().join("ahead"), &records_of(&rows), 10, Some(5)).expect("written");
    assert_eq!(failure(&mut harness, "ahead"), "covers_seq");
    let stats = harness.stats();
    assert!(
        stats["last_failure"]["reason"]
            .as_str()
            .is_some_and(|reason| reason.contains("never saw")),
        "{stats}"
    );
}

#[test]
fn a_log_damaged_in_the_middle_refuses_its_index_and_says_why() {
    let history = history::<u64>(15);
    let mut bytes = history.bytes.clone();
    let middle = history.whole[2].0 + 20;
    bytes[middle] ^= 0xff;
    let (held, harness) = reopen(&history, &bytes);
    assert_eq!(held, None);
    let stats = harness.stats();
    assert_eq!(stats["state"], "refused");
    assert!(
        stats["refused"]
            .as_str()
            .is_some_and(|reason| reason.contains("damaged")),
        "{stats}"
    );
    let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 1, "values": ["0000000000000001"]});
    let error = harness.search(&options).expect_err("refused");
    assert_eq!((error.error_type, error.state), (ErrorType::NotReady, Some("refused")));
    assert!(harness.events.iter().any(|event| event.contains("LogRefused")));
    // The file is left as it was, for a person to look at...
    assert_eq!(fs::read(harness.log_path()).expect("the log"), bytes);
}

/// Whether `task_id` is one the log takes, said plainly: 1 to 64 of `A-Z`, `a-z`, `0-9`, `_`, `-`.
fn task_id_taken(task_id: &str) -> bool {
    (1..=64).contains(&task_id.len())
        && task_id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

#[test]
fn every_task_id_the_writer_takes_reads_back_and_every_other_leaves_the_log_as_it_was() {
    let mut harness = Harness::new(Limits::default());
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    let mut rng = Rng::new(31);
    let valid: Vec<char> = "abzAZ09_-".chars().collect();
    let invalid: Vec<char> = ":./ é\u{0}\u{1f600}".chars().collect();
    let mut task_ids: Vec<String> = [0, 1, 64, 65, 255, 256]
        .iter()
        .map(|&length| "a".repeat(length))
        .chain([
            "é".repeat(10),
            "\u{1f600}".repeat(16),
            "a".repeat(63) + "é",
            "task:1".to_owned(),
        ])
        .collect();
    for _ in 0..300 {
        let length = rng.below(80);
        let odd = rng.below(4) == 0;
        task_ids.push(
            (0..length)
                .map(|_| {
                    if odd && rng.below(8) == 0 {
                        invalid[rng.below(invalid.len())]
                    } else {
                        valid[rng.below(valid.len())]
                    }
                })
                .collect(),
        );
    }
    let mut taken = Vec::new();
    for (step, task_id) in task_ids.iter().enumerate() {
        let before = fs::read(harness.log_path()).unwrap_or_default();
        let seq = harness.stats()["seq"].clone();
        let id = step as u64 + 2;
        match harness.change(task_id, "replace", &records_options(&[(id, id)])) {
            Ok(answer) => {
                assert!(task_id_taken(task_id), "{task_id:?} was taken");
                if !taken.iter().any(|(taken, _)| taken == task_id) {
                    taken.push((task_id.clone(), answer));
                }
            }
            Err(error) => {
                assert!(!task_id_taken(task_id), "{task_id:?} was refused: {error}");
                assert_eq!(error.error_type, ErrorType::InvalidTask, "{task_id:?}");
                assert_eq!(fs::read(harness.log_path()).unwrap_or_default(), before, "{task_id:?}");
                assert_eq!(harness.stats()["seq"], seq, "{task_id:?}");
            }
        }
    }
    assert!(taken.len() > 20, "the property took enough task ids to mean something");
    // Every task taken reads back from the log: a restart answers each repeat as the first time.
    harness.open();
    assert_eq!(harness.stats()["state"], "ready");
    for (task_id, answer) in &taken {
        let id = 9_999;
        assert_eq!(
            &harness
                .change(task_id, "replace", &records_options(&[(id, id)]))
                .expect("answered"),
            answer
        );
    }
}

/// What a live writer's log can suffer under it before a swap.
#[derive(Debug, Clone, Copy)]
enum Mishap {
    Deleted,
    CutAtATask,
    CutInATask,
    Replaced,
}

#[test]
fn a_swap_never_steps_behind_what_the_live_writer_made_durable() {
    for mishap in [
        Mishap::Deleted,
        Mishap::CutAtATask,
        Mishap::CutInATask,
        Mishap::Replaced,
    ] {
        let mut harness = Harness::new(wide_limits());
        let origin = BTreeMap::from([(1u64, 0x1u64), (2, 0x3)]);
        harness.set.publish("s0", &records_of(&origin));
        harness.open();
        harness
            .change("t1", "replace", &records_options(&[(7, 0x7u64)]))
            .expect("applied");
        let after_first = fs::read(harness.log_path()).expect("the log").len();
        harness
            .change("t2", "remove", &remove_options::<u64>(&[1]))
            .expect("removed");
        let path = harness.log_path();
        match mishap {
            Mishap::Deleted => fs::remove_file(&path).expect("deleted"),
            Mishap::CutAtATask => fs::OpenOptions::new()
                .write(true)
                .open(&path)
                .and_then(|file| file.set_len(after_first as u64))
                .expect("cut"),
            Mishap::CutInATask => fs::OpenOptions::new()
                .write(true)
                .open(&path)
                .and_then(|file| file.set_len(after_first as u64 + 20))
                .expect("cut"),
            Mishap::Replaced => {
                // The same bytes under a new file: appends to the old one would be lost...
                let copy = path.with_extension("copy");
                fs::copy(&path, &copy).expect("copied");
                fs::rename(&copy, &path).expect("renamed");
            }
        }
        // A snapshot without covers_seq: everything the log holds is replayed over it.
        harness.set.publish("s1", &records_of(&origin));
        harness.set.point("s1");
        harness.refresh();
        let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 64, "values": ["0000000000000000"]});
        let found = harness.search(&options).expect("searched");
        let ids: Vec<u64> = found["queries"][0]["matches"]
            .as_array()
            .expect("matches")
            .iter()
            .map(|found| found["id"].as_u64().expect("an id"))
            .collect();
        assert_eq!(
            (found["snapshot"].clone(), found["seq"].clone()),
            (json!("s0"), json!(2)),
            "{mishap:?}"
        );
        assert_eq!(ids, [2, 7], "{mishap:?}: no confirmed change is lost");
        let stats = harness.stats();
        let code = match mishap {
            Mishap::Deleted => "log_missing",
            Mishap::CutAtATask => "log_changed",
            Mishap::CutInATask => "log_cut",
            Mishap::Replaced => "log_replaced",
        };
        assert_eq!(stats["changes"]["writer"], "broken", "{mishap:?}: {stats}");
        assert_eq!(stats["changes"]["writer_reason"], code, "{mishap:?}: {stats}");
        assert_eq!(stats["last_failure"]["code"], "log", "{mishap:?}: {stats}");
        assert!(stats["last_failure"]["reason"].is_string(), "{mishap:?}: {stats}");
        // No further change is taken, so none can go to a file the directory no longer names.
        let refused = harness
            .change("t3", "replace", &records_options(&[(8, 0x8u64)]))
            .expect_err("refused");
        assert_eq!(refused.error_type, ErrorType::Internal, "{mishap:?}");
    }
}

#[test]
fn a_log_longer_than_the_bound_read_is_refused_unread_until_the_bound_is_raised() {
    let mut harness = Harness::new(Limits::default());
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    harness.open();
    for task in 0..5u64 {
        let records: Vec<(u64, u64)> = (0..100).map(|id| (task * 1_000 + id + 10, id)).collect();
        harness
            .change(&format!("t{task}"), "append", &records_options(&records))
            .expect("applied");
    }
    let bytes = fs::metadata(harness.log_path()).expect("the log").len();
    // A lowered bound: the log is more than it reads...
    harness.limits.max_change_records = 10;
    harness.limits.max_remove_ids = 10;
    harness.limits.max_log_bytes = 2_000;
    assert!(harness.limits.log_read_bound() < bytes);
    harness.open();
    let stats = harness.stats();
    assert_eq!(
        (stats["state"].clone(), stats["refused_code"].clone()),
        (json!("refused"), json!("too_large"))
    );
    assert!(
        stats["refused"]
            .as_str()
            .is_some_and(|reason| reason.contains("--max-log-bytes")),
        "{stats}"
    );
    assert_eq!(
        fs::metadata(harness.log_path()).expect("the log").len(),
        bytes,
        "left as it was"
    );
    // ...and raising it again reads it.
    harness.limits = Limits::default();
    harness.open();
    assert_eq!(harness.stats()["seq"], 500);
}

#[test]
fn a_writer_dropped_and_opened_again_takes_its_lock_every_time_while_the_process_spawns_children() {
    // A child process holds a copy of every open file from its fork to its exec, the lock's
    // included: a writer opened again at once must still take it...
    let mut harness = Harness::new(Limits::default());
    harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
    let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let spawner = {
        let stop = Arc::clone(&stop);
        std::thread::spawn(move || {
            let mut spawned = 0;
            while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                if std::process::Command::new("true").status().is_ok() {
                    spawned += 1;
                }
            }
            spawned
        })
    };
    for round in 0..1_000 {
        harness.service = None;
        let catalog = Catalog::new(vec![SetSpec::index(INDEX, harness.set.path())], harness.config(true));
        let catalog = catalog.unwrap_or_else(|error| panic!("round {round}: {error}"));
        harness.service = Some(Service::new(Arc::new(catalog), harness.limits, 1));
    }
    stop.store(true, std::sync::atomic::Ordering::Relaxed);
    assert!(
        spawner.join().expect("the spawner") > 0,
        "children were spawned meanwhile"
    );
}