tickvault 0.1.1

Full-depth crypto order book recorder and archive that publishes its own gap statistics
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
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
//! The recorder CLI.
//!
//! Four commands. `record` captures raw frames from a live venue, `replay`
//! feeds a tape back through the identical ingest path with messages optionally
//! removed, `capabilities` prints what each venue can and cannot prove, and
//! `plan` shows how symbols would be laid out across sockets and why.

use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use tickvault::clock::{Clock, ManualClock, MonotonicClock};
use tickvault::pipeline::{BackpressurePolicy, Pipeline, PipelineConfig};
use tickvault::query::Query;
use tickvault::query::replay::Speed;
use tickvault::reconstruct::{Reconstructor, Request, checkpoint};
use tickvault::recorder::{RawRecorder, RawTape};
use tickvault::session::{BookSession, RunSinks, StopAfter};
use tickvault::store::reader::ArchiveReader;
use tickvault::store::{recovery, writer::WriterConfig};
use tickvault::transport::ReqwestFetch;
use tickvault::types::{Symbol, VenueId};
use tickvault::venue::kraken::Precision;
use tickvault::venue::registry::{self, VenueConfig};

#[derive(Parser)]
#[command(
    name = "tickvault",
    about = "Full-depth crypto order book recorder",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// Options shared by every command that has to build a venue.
#[derive(clap::Args, Clone)]
struct VenueArgs {
    #[arg(long)]
    venue: VenueId,
    /// Canonical symbols, e.g. BTC-USD. Defaults to the pair this venue
    /// actually lists against the dollar, which is USDT on half of them.
    #[arg(long, value_delimiter = ',')]
    symbols: Vec<String>,
    /// Kraken book depth. Ten is the only depth at which its checksum covers
    /// every level the feed can touch.
    #[arg(long, default_value_t = 10)]
    kraken_depth: usize,
    #[arg(long, default_value_t = 50)]
    bybit_depth: usize,
    /// Kraken price,quantity precision, skipping the REST metadata lookup.
    #[arg(long)]
    precision: Option<String>,
    /// Record order by order rather than by price level, where the venue
    /// exposes it. Only Bitstamp does, keylessly.
    #[arg(long, default_value_t = 2)]
    book_level: u8,
}

impl VenueArgs {
    fn resolve(&self) -> Result<VenueConfig> {
        let symbols: Vec<Symbol> = if self.symbols.is_empty() {
            vec![VenueConfig::default_symbol(self.venue)]
        } else {
            self.symbols
                .iter()
                .map(|s| Symbol::parse(s).map_err(anyhow::Error::msg))
                .collect::<Result<_>>()?
        };
        for symbol in &symbols {
            if !VenueConfig::quotes_supported(self.venue, symbol) {
                bail!(
                    "{} does not list {symbol}; it quotes the other dollar. Try {} instead.",
                    self.venue,
                    VenueConfig::default_symbol(self.venue)
                );
            }
        }
        let precision = match self.precision.as_deref() {
            Some(spec) => {
                let (p, q) = spec
                    .split_once(',')
                    .context("--precision expects price,quantity")?;
                Some(Precision {
                    price: p.trim().parse()?,
                    qty: q.trim().parse()?,
                })
            }
            None => None,
        };
        let book_level = match self.book_level {
            2 => tickvault::types::BookLevel::L2,
            3 => tickvault::types::BookLevel::L3,
            other => bail!("--book-level must be 2 or 3, got {other}"),
        };
        if book_level == tickvault::types::BookLevel::L3 && self.venue != VenueId::Bitstamp {
            bail!(
                "{} publishes no keyless order-by-order feed. Coinbase, Kraken, and OKX all \
                 require authentication for theirs; only bitstamp is open.",
                self.venue
            );
        }
        Ok(VenueConfig {
            symbols,
            kraken_depth: self.kraken_depth,
            kraken_precision: precision,
            bybit_depth: self.bybit_depth,
            binance_rest_depth: 1000,
            bitstamp_book_level: book_level,
        })
    }
}

#[derive(Subcommand)]
enum Command {
    /// Record raw frames from a live venue and print the gap report.
    Record {
        #[command(flatten)]
        venue: VenueArgs,
        /// Where to write the raw tape.
        #[arg(long)]
        out: Option<String>,
        #[arg(long, default_value_t = 30)]
        seconds: u64,
        /// Write a partitioned Parquet archive here as well.
        #[arg(long)]
        archive: Option<String>,
        /// What to do when the writer cannot keep up: block the reader and
        /// risk a venue disconnect, or drop rows and record the drop. There is
        /// no default, because doing one silently is the thing to avoid.
        #[arg(long, default_value = "block")]
        backpressure: BackpressurePolicy,
        /// Batches the ingest-to-writer channel will hold.
        #[arg(long, default_value_t = 1024)]
        queue: usize,
        /// Rotate an archive file after this long. This is the bound on how
        /// much a crash can cost per partition.
        #[arg(long, default_value_t = 60)]
        rotate_secs: u64,
    },
    /// Replay a recorded raw tape, optionally with messages removed.
    ///
    /// A debugging tool for the ingest path. To replay the archive, see
    /// `replay`.
    #[command(name = "replay-tape")]
    ReplayTape {
        #[command(flatten)]
        venue: VenueArgs,
        #[arg(long)]
        tape: String,
        /// Frame indices to delete before replaying.
        #[arg(long, value_delimiter = ',')]
        drop: Vec<usize>,
        /// Delete one in every N book messages instead of naming indices.
        #[arg(long)]
        drop_every: Option<usize>,
        /// Treat each line as a bare venue payload rather than a recorded frame.
        ///
        /// The tapes under `tests/fixtures` are captured this way, and so is
        /// anything pasted out of a venue's docs or a browser's network tab.
        /// Receipt stamps do not exist in such a file, so they are synthesised
        /// one millisecond apart from `--start`, which keeps a replay of the
        /// same file byte-identical from one run to the next.
        #[arg(long)]
        payloads: bool,
        /// Receipt time of the first payload, RFC 3339. Only with --payloads.
        #[arg(long, default_value = "2020-01-01T00:00:00Z")]
        start: String,
        /// Also write the replayed frames to an archive here.
        ///
        /// A tape plus this flag is a reproducible archive: the same frames in,
        /// the same Parquet out, no network. That is what the Python tests read,
        /// so they do not need a live venue or a committed binary blob.
        #[arg(long)]
        archive: Option<String>,
    },
    /// Check an archive: recover if needed, then read every file back.
    Verify {
        #[arg(long)]
        archive: String,
        /// Only report; do not quarantine or adopt anything.
        #[arg(long)]
        read_only: bool,
    },
    /// Merge a day's many small files into one.
    Compact {
        #[arg(long)]
        archive: String,
        /// Leave this date alone, for the day still being recorded.
        #[arg(long)]
        exclude_date: Option<String>,
    },
    /// Write synthetic rows continuously, to be killed and restarted.
    ///
    /// This exists for the phase 3 crash gate: a process that can be SIGKILLed
    /// at a randomised offset and restarted, so recovery is exercised against a
    /// real kill rather than a simulated one.
    Soak {
        #[arg(long)]
        archive: String,
        /// First sequence number to write. Each run of the gate uses its own
        /// range, so a duplicated row is detectable rather than plausible.
        #[arg(long, default_value_t = 0)]
        start_seq: u64,
        /// Rotate a file after this many milliseconds.
        #[arg(long, default_value_t = 250)]
        rotate_ms: u64,
        /// Rows per batch handed to the writer.
        #[arg(long, default_value_t = 500)]
        batch_rows: usize,
        /// Stop after this long. Zero runs until killed.
        #[arg(long, default_value_t = 0)]
        seconds: u64,
        /// Pause this many microseconds between batches, to keep the volume
        /// sane when the point is crash behaviour rather than throughput.
        #[arg(long, default_value_t = 0)]
        pace_us: u64,
        /// What to do when the writer cannot keep up.
        #[arg(long, default_value = "block")]
        backpressure: BackpressurePolicy,
    },
    /// Rebuild a book as it stood at an instant.
    Reconstruct {
        #[arg(long)]
        archive: String,
        #[arg(long)]
        venue: VenueId,
        #[arg(long)]
        symbol: String,
        /// RFC 3339 (`2026-08-25T12:00:00Z`) or raw nanoseconds since the epoch.
        #[arg(long)]
        at: String,
        /// Keep only this many levels a side.
        #[arg(long)]
        depth: Option<usize>,
        /// Replay from the beginning rather than from a checkpoint.
        #[arg(long)]
        no_checkpoints: bool,
        /// Print the top levels.
        #[arg(long, default_value_t = 5)]
        show: usize,
    },
    /// Query a range: bars, spread, imbalance, all from the real book.
    Query {
        #[arg(long)]
        archive: String,
        #[arg(long)]
        venue: VenueId,
        #[arg(long)]
        symbol: String,
        /// RFC 3339 or raw nanoseconds. Defaults to the archive's own start.
        #[arg(long)]
        from: Option<String>,
        /// Defaults to the archive's own end.
        #[arg(long)]
        to: Option<String>,
        /// Bar width in seconds.
        #[arg(long, default_value_t = 60.0)]
        bar_secs: f64,
        /// Levels a side to use for imbalance.
        #[arg(long, default_value_t = 10)]
        depth: usize,
    },
    /// Replay a range, at wall-clock speed or as fast as it reads.
    Replay {
        #[arg(long)]
        archive: String,
        #[arg(long)]
        venue: VenueId,
        #[arg(long)]
        symbol: String,
        #[arg(long)]
        from: Option<String>,
        #[arg(long)]
        to: Option<String>,
        /// Speed multiplier. Zero replays as fast as the archive reads.
        #[arg(long, default_value_t = 0.0)]
        speed: f64,
        /// Print every Nth message.
        #[arg(long, default_value_t = 100)]
        every: u64,
    },
    /// Write periodic checkpoints so late queries stay cheap.
    Checkpoint {
        #[arg(long)]
        archive: String,
        /// Seconds between checkpoints.
        #[arg(long, default_value_t = 300)]
        every_secs: u64,
    },
    /// Print what each venue can and cannot tell us.
    Capabilities {
        /// Restrict to one venue.
        #[arg(long)]
        venue: Option<VenueId>,
    },
    /// Record every venue in a config file, in one process, until stopped.
    ///
    /// The difference between a tool and a service. `record` captures one venue
    /// for a fixed time and prints a report when it stops; this keeps every
    /// configured venue running, restarts one that fails, and answers for its
    /// own health while it does.
    Serve {
        #[arg(long, default_value = "tickvault.toml")]
        config: String,
        /// Check the config and print what would run, then exit.
        #[arg(long)]
        dry_run: bool,
    },
    /// Measure how fast the book applies and the archive writes.
    ///
    /// The README quotes a throughput number, and a quoted number with no way
    /// to reproduce it is not a measurement. This is the way to reproduce it.
    Bench {
        /// Messages to apply, and rows to write.
        #[arg(long, default_value_t = 500_000)]
        messages: usize,
        /// Levels changed per message, which is what makes a row.
        #[arg(long, default_value_t = 4)]
        levels: usize,
    },
    /// Apply a retention window to an archive.
    ///
    /// What it removes is recorded in the manifest as a retention, which is a
    /// different thing from a truncation: one is data we chose to stop keeping
    /// on a stated policy, the other is data we lost.
    Retention {
        #[arg(long)]
        archive: String,
        /// Drop files whose newest row is older than this many days.
        #[arg(long)]
        max_age_days: Option<u32>,
        /// Drop the oldest files until the archive fits in this many bytes.
        #[arg(long)]
        max_bytes: Option<u64>,
        /// Say what would go, and remove nothing.
        #[arg(long)]
        dry_run: bool,
    },
    /// Copy an archive, re-encoding every file with a different codec.
    ///
    /// zstd ships hand-written amd64 assembly and cannot be compiled to wasm at
    /// all, so an archive meant to be read in a browser has to be snappy. The
    /// rows are untouched: this changes how the bytes are packed, not what they
    /// say.
    Transcode {
        #[arg(long)]
        archive: String,
        #[arg(long)]
        out: String,
        /// snappy or zstd.
        #[arg(long, default_value = "snappy")]
        compression: String,
    },
    /// Emit per-venue coverage over time as JSON.
    ///
    /// This is the gap report bucketed by wall clock, which is what the
    /// published dataset leads with and what the viewer's heatmap draws.
    Coverage {
        /// Repeatable. One archive per venue is how a multi-venue recording
        /// actually lands on disk, since six writers cannot share a manifest.
        #[arg(long, required = true)]
        archive: Vec<String>,
        /// Bucket width in seconds.
        #[arg(long, default_value_t = 300)]
        bucket_secs: i64,
        /// Write here instead of standard output.
        #[arg(long)]
        out: Option<String>,
    },
    /// Show how symbols would be spread across sockets, and why.
    Plan {
        #[command(flatten)]
        venue: VenueArgs,
    },
}

/// Accept either an RFC 3339 instant or raw nanoseconds since the epoch.
fn parse_instant(raw: &str) -> Result<i64> {
    if let Some(nanos) = tickvault::clock::parse_rfc3339_nanos(raw) {
        return Ok(nanos);
    }
    raw.parse::<i64>().map_err(|_| {
        anyhow::anyhow!("{raw:?} is neither an RFC 3339 instant nor a nanosecond count")
    })
}

/// The wall-clock span an archive covers for one partition.
fn archive_span(
    reconstructor: &Reconstructor,
    venue: VenueId,
    symbol: &Symbol,
) -> Result<(i64, i64)> {
    let files: Vec<_> = reconstructor
        .reader()
        .files()
        .iter()
        .filter(|f| f.venue == venue && f.symbol == *symbol)
        .collect();
    let first = files.iter().map(|f| f.first_recv_wall).min();
    let last = files.iter().map(|f| f.last_recv_wall).max();
    match (first, last) {
        (Some(a), Some(b)) => Ok((a, b)),
        _ => bail!("the archive holds nothing for {venue} {symbol}"),
    }
}

fn wall_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as i64)
        .unwrap_or(0)
}

/// Write synthetic rows as fast as the writer will take them, until killed.
///
/// Deliberately not a venue: the gate is about the storage layer surviving a
/// kill, and a live feed would make the test depend on an exchange being up and
/// on how busy the market happens to be.
async fn soak(
    archive: String,
    start_seq: u64,
    rotate_ms: u64,
    batch_rows: usize,
    seconds: u64,
    pace_us: u64,
    backpressure: BackpressurePolicy,
) -> Result<()> {
    use tickvault::book::{BookDelta, LevelChange};
    use tickvault::clock::{Stamp, Timestamps};
    use tickvault::fixed::Fixed;
    use tickvault::store::schema::RowBuilder;
    use tickvault::store::writer::PartitionKey;
    use tickvault::types::Side;

    // Always recover first. A soak run that wrote around the wreckage of the
    // previous one would defeat the point of the exercise.
    let recovered = recovery::recover(&archive, wall_now())?;
    println!("recovery: {recovered}");

    let pipeline = Pipeline::start(PipelineConfig {
        capacity: 64,
        ..PipelineConfig::new(
            WriterConfig {
                max_file_age: Duration::from_millis(rotate_ms),
                max_rows_per_file: 100_000,
                row_group_size: 8_192,
                ..WriterConfig::new(&archive)
            },
            backpressure,
        )
    })?;

    let symbol = Symbol::parse("BTC-USD").map_err(anyhow::Error::msg)?;
    let deadline =
        (seconds > 0).then(|| tokio::time::Instant::now() + Duration::from_secs(seconds));
    println!("soak: writing from seq {start_seq}");

    let mut seq = start_seq;
    loop {
        if deadline.is_some_and(|d| tokio::time::Instant::now() >= d) {
            break;
        }
        let wall = wall_now();
        let mut builder = RowBuilder::new();
        for _ in 0..batch_rows {
            let delta = BookDelta {
                symbol: symbol.clone(),
                changes: vec![LevelChange::new(
                    Side::Bid,
                    Fixed::from_mantissa(78_000_000_000_000 + (seq as i64 % 1_000)),
                    Fixed::from_mantissa(500_000_000),
                )],
                // The gate reads this back: one row per seq, no repeats, and
                // any hole confined to the tail of the run.
                seq: Some(seq),
                checksum: None,
                stamps: Timestamps::recv_only(Stamp {
                    mono_nanos: seq,
                    wall_nanos: wall,
                }),
                prev_seq: None,
                first_seq: None,
            };
            builder.push_delta(VenueId::Kraken, &delta, seq, false);
            seq += 1;
        }
        let Some(span) = builder.wall_span() else {
            continue;
        };
        let Some(batch) = builder.finish() else {
            continue;
        };
        let key = PartitionKey::new(VenueId::Kraken, &symbol, span.0);
        pipeline.submit(key, batch, span).await;
        // Let the runtime breathe so a kill can land anywhere, including
        // mid-write, rather than only between batches.
        if pace_us > 0 {
            tokio::time::sleep(Duration::from_micros(pace_us)).await;
        } else {
            tokio::task::yield_now().await;
        }
    }

    let stats = pipeline.stats();
    let writer = pipeline.shutdown().await?;
    println!(
        "soak: wrote up to seq {seq}, {} ({} files)",
        stats,
        writer.manifest().files().len()
    );
    Ok(())
}

/// Hand batches to the writer, refusing to lose any.
///
/// The live recorder has a real choice to make when the writer lags, and it
/// records whichever way it went. A tape replay has no such pressure: every
/// frame is already on disk, so anything short of writing all of them would be
/// a hole this tool invented.
async fn submit_all(
    pipeline: &Arc<Pipeline>,
    batches: Vec<(
        tickvault::store::writer::PartitionKey,
        arrow::array::RecordBatch,
        (i64, i64),
    )>,
) {
    for (key, batch, span) in batches {
        match pipeline.submit(key.clone(), batch, span).await {
            tickvault::pipeline::Submitted::Accepted
            | tickvault::pipeline::Submitted::Blocked(_) => {}
            other => {
                eprintln!("archive refused a batch for {}: {other:?}", key.symbol);
            }
        }
    }
}

/// Bucket an archive's own record of itself into a coverage grid.
///
/// Nothing here is computed for the demo. `suspect` is the verdict the recorder
/// reached live, against whatever that venue gave it to validate with, and it
/// was written into every row at capture time. This only counts.
///
/// The distinction the grid has to carry is between three different things,
/// because flattening them is exactly the dishonesty the project exists to
/// avoid. A bucket with no rows is absent. A bucket whose rows are marked is
/// suspect. And a bucket on a venue that publishes nothing to validate against
/// is unverifiable, which is neither clean nor broken: there is no reason to
/// think it is wrong and no way to know.
fn coverage_json(archives: &[String], bucket_secs: i64) -> Result<String> {
    use std::collections::BTreeMap;

    let bucket_nanos = bucket_secs * 1_000_000_000;

    // Which venues can prove anything at all, read from the capability matrix
    // rather than restated here.
    let clock: Arc<dyn Clock> = Arc::new(ManualClock::default());
    let http = ReqwestFetch::shared()?;
    let mut verifiable: BTreeMap<VenueId, bool> = BTreeMap::new();
    for id in VenueId::ALL {
        let config = VenueConfig {
            symbols: vec![VenueConfig::default_symbol(*id)],
            kraken_precision: Some(Precision { price: 1, qty: 8 }),
            ..VenueConfig::default()
        };
        if let Ok(v) = registry::build_offline(*id, &config, Arc::clone(&http), Arc::clone(&clock))
        {
            verifiable.insert(*id, v.capabilities().can_detect_loss());
        }
    }

    #[derive(Default)]
    struct Bucket {
        rows: u64,
        suspect_rows: u64,
        messages: u64,
    }

    struct Series {
        venue: VenueId,
        symbol: Symbol,
        book_level: u8,
        buckets: BTreeMap<i64, Bucket>,
    }

    let mut series: BTreeMap<(VenueId, String, String), Series> = BTreeMap::new();
    let mut earliest = i64::MAX;
    let mut latest = i64::MIN;

    for archive in archives {
        let reader = ArchiveReader::open(archive)?;
        for record in reader.files() {
            let key = (record.venue, record.symbol.to_string(), record.date.clone());
            let entry = series.entry(key).or_insert_with(|| Series {
                venue: record.venue,
                symbol: record.symbol.clone(),
                book_level: match record.book_level {
                    tickvault::types::BookLevel::L3 => 3,
                    _ => 2,
                },
                buckets: BTreeMap::new(),
            });

            for batch in tickvault::store::reader::read_batches(reader.path_of(record))? {
                let rows = tickvault::store::rows::decode(&batch)?;
                for message in tickvault::store::rows::split_messages(&rows) {
                    let Some(first) = message.first() else {
                        continue;
                    };
                    let at = first.recv_wall;
                    earliest = earliest.min(at);
                    latest = latest.max(at);
                    let bucket = entry
                        .buckets
                        .entry(at.div_euclid(bucket_nanos) * bucket_nanos)
                        .or_default();
                    bucket.messages += 1;
                    bucket.rows += message.len() as u64;
                    bucket.suspect_rows += message.iter().filter(|r| r.suspect).count() as u64;
                }
            }
        }
    }

    if series.is_empty() {
        bail!("no files across {} archive(s)", archives.len());
    }

    // Every series spans the same grid, so an absent bucket on one venue lines
    // up with a present one on another. That comparison is the point of putting
    // them side by side.
    let first_bucket = earliest.div_euclid(bucket_nanos) * bucket_nanos;
    let last_bucket = latest.div_euclid(bucket_nanos) * bucket_nanos;

    let mut out = String::from("{\n");
    out.push_str(&format!("  \"bucket_seconds\": {bucket_secs},\n"));
    out.push_str(&format!("  \"from_ns\": \"{first_bucket}\",\n"));
    out.push_str(&format!(
        "  \"to_ns\": \"{}\",\n",
        last_bucket + bucket_nanos
    ));
    out.push_str("  \"series\": [\n");

    let mut rendered: Vec<String> = Vec::new();
    for s in series.values() {
        let can_verify = verifiable.get(&s.venue).copied().unwrap_or(false) || s.book_level == 3;
        let mut cells: Vec<String> = Vec::new();
        let mut at = first_bucket;
        while at <= last_bucket {
            let b = s.buckets.get(&at);
            let (rows, suspect, messages) = b
                .map(|b| (b.rows, b.suspect_rows, b.messages))
                .unwrap_or((0, 0, 0));
            let state =
                tickvault::gap::CoverageState::classify(messages, suspect, can_verify).as_str();
            cells.push(format!(
                "        {{\"at_ns\": \"{at}\", \"state\": \"{state}\", \"messages\": {messages}, \"rows\": {rows}, \"suspect_rows\": {suspect}}}"
            ));
            at += bucket_nanos;
        }
        rendered.push(format!(
            "    {{\n      \"venue\": \"{}\",\n      \"symbol\": \"{}\",\n      \"book_level\": {},\n      \"verifiable\": {},\n      \"buckets\": [\n{}\n      ]\n    }}",
            s.venue.as_str(),
            s.symbol,
            s.book_level,
            can_verify,
            cells.join(",\n")
        ));
    }
    out.push_str(&rendered.join(",\n"));
    out.push_str("\n  ]\n}\n");
    Ok(out)
}

/// Re-encode an archive under a different compression codec.
///
/// Reads with whatever the source used and writes with the requested codec,
/// batch for batch, so the rows and the schema come through untouched. The
/// manifest is rewritten because the byte counts change and nothing else does.
fn transcode(archive: &str, out: &str, compression: &str) -> Result<(u64, usize, u64, u64)> {
    use parquet::arrow::ArrowWriter;
    use parquet::basic::{Compression, ZstdLevel};
    use parquet::file::properties::WriterProperties;

    let codec = match compression {
        "snappy" => Compression::SNAPPY,
        "zstd" => Compression::ZSTD(ZstdLevel::try_new(3).map_err(|e| anyhow::anyhow!("{e}"))?),
        other => bail!("unknown compression {other:?}, expected snappy or zstd"),
    };

    let reader = ArchiveReader::open(archive)?;
    let out_root = std::path::Path::new(out);
    std::fs::create_dir_all(out_root)?;
    let mut manifest = tickvault::store::manifest::Manifest::open(out_root)?;

    let (mut rows, mut before, mut after) = (0u64, 0u64, 0u64);
    let mut files = 0usize;
    for record in reader.files() {
        let batches = tickvault::store::reader::read_batches(reader.path_of(record))?;
        let target = out_root.join(&record.path);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let props = WriterProperties::builder()
            .set_compression(codec)
            .set_created_by(format!("tickvault {} transcode", env!("CARGO_PKG_VERSION")))
            .build();
        let sink = std::fs::File::create(&target)?;
        let mut writer =
            ArrowWriter::try_new(sink, tickvault::store::schema::book_schema(), Some(props))
                .map_err(|e| anyhow::anyhow!("{e}"))?;
        for batch in &batches {
            writer.write(batch).map_err(|e| anyhow::anyhow!("{e}"))?;
        }
        writer.close().map_err(|e| anyhow::anyhow!("{e}"))?;

        let bytes = std::fs::metadata(&target)?.len();
        rows += record.rows;
        before += record.bytes;
        after += bytes;
        files += 1;
        manifest.record_file(tickvault::store::manifest::FileRecord {
            bytes,
            ..record.clone()
        })?;
    }
    manifest.sync_dir()?;
    Ok((rows, files, before, after))
}

/// Measure the two stages that decide throughput, and say where they run.
///
/// Deliberately synthetic. Real feeds arrive at whatever rate the venue sends,
/// which measures the venue rather than this, so the book is fed as fast as it
/// will go and the writer is given rows as fast as it will take them.
async fn bench(messages: usize, levels: usize) -> Result<()> {
    use std::time::Instant;
    use tickvault::book::{BookDelta, L2Book, LevelChange};
    use tickvault::clock::{Stamp, Timestamps};
    use tickvault::fixed::Fixed;
    use tickvault::store::schema::RowBuilder;
    use tickvault::store::writer::PartitionKey;
    use tickvault::types::Side;

    let symbol = Symbol::parse("BTC-USD").map_err(anyhow::Error::msg)?;
    let rows = messages * levels;
    println!(
        "{} messages x {} levels = {} rows, on {} {}",
        messages,
        levels,
        rows,
        std::env::consts::OS,
        std::env::consts::ARCH
    );

    let make = |i: usize| {
        let base = 80_000_000_000_000i64 + ((i % 2_000) as i64) * 1_000_000;
        BookDelta {
            symbol: symbol.clone(),
            changes: (0..levels)
                .map(|l| LevelChange {
                    side: if (i + l).is_multiple_of(2) {
                        Side::Bid
                    } else {
                        Side::Ask
                    },
                    price: Fixed::from_mantissa(base + (l as i64) * 100_000),
                    qty: Fixed::from_mantissa(((i + l) % 97 + 1) as i64 * 1_000_000),
                })
                .collect(),
            seq: Some(i as u64),
            first_seq: None,
            prev_seq: None,
            checksum: None,
            stamps: Timestamps::recv_only(Stamp {
                mono_nanos: i as u64,
                wall_nanos: 1_787_000_000_000_000_000 + i as i64,
            }),
        }
    };

    // 1. The book. Pure CPU: no allocation of a writer, no disk.
    let mut book = L2Book::new(symbol.clone());
    let deltas: Vec<BookDelta> = (0..messages).map(make).collect();
    let started = Instant::now();
    for delta in &deltas {
        book.apply_delta(delta);
    }
    let apply = started.elapsed();
    println!(
        "  book apply     {:>10.0} msg/s   {:>10.0} rows/s   ({:.2}s)",
        messages as f64 / apply.as_secs_f64(),
        rows as f64 / apply.as_secs_f64(),
        apply.as_secs_f64()
    );

    // 2. Building Arrow rows, which is the cost before anything touches disk.
    let key = PartitionKey::new(VenueId::Kraken, &symbol, 1_787_000_000_000_000_000);
    let started = Instant::now();
    let mut builder = RowBuilder::default();
    let mut batches = Vec::new();
    for (i, delta) in deltas.iter().enumerate() {
        builder.push_delta(VenueId::Kraken, delta, i as u64, false);
        if builder.len() >= 8_192 {
            batches.push(builder.finish().expect("batch"));
        }
    }
    if let Some(last) = builder.finish() {
        batches.push(last);
    }
    let encode = started.elapsed();
    println!(
        "  arrow encode   {:>10.0} msg/s   {:>10.0} rows/s   ({:.2}s)",
        messages as f64 / encode.as_secs_f64(),
        rows as f64 / encode.as_secs_f64(),
        encode.as_secs_f64()
    );

    // 3. The writer, through the same bounded channel the recorder uses, onto
    //    whatever disk this is. Block rather than drop: a benchmark that sheds
    //    rows when it falls behind measures nothing.
    // Its own directory under the system temp dir, cleaned up at the end. A
    // benchmark that wrote into the user's archive would be a poor guest.
    let dir = std::env::temp_dir().join(format!("tickvault-bench-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir)?;
    let pipeline = Pipeline::start(PipelineConfig {
        capacity: 64,
        ..PipelineConfig::new(
            WriterConfig {
                max_rows_per_file: 500_000,
                row_group_size: 8_192,
                ..WriterConfig::new(&dir)
            },
            BackpressurePolicy::Block,
        )
    })?;
    let started = Instant::now();
    for batch in batches {
        let n = batch.num_rows();
        pipeline.submit(key.clone(), batch, (0, n as i64)).await;
    }
    let writer = pipeline.shutdown().await?;
    let write = started.elapsed();
    let bytes: u64 = writer.manifest().files().iter().map(|f| f.bytes).sum();
    println!(
        "  archive write  {:>10.0} rows/s   {:>10.2} MB/s   ({:.2}s, {:.1} MB of parquet)",
        rows as f64 / write.as_secs_f64(),
        bytes as f64 / 1e6 / write.as_secs_f64(),
        write.as_secs_f64(),
        bytes as f64 / 1e6
    );

    let _ = std::fs::remove_dir_all(&dir);

    let slowest = apply.max(encode).max(write);
    let name = if slowest == write {
        "the writer"
    } else if slowest == encode {
        "Arrow encoding"
    } else {
        "the book"
    };
    println!(
        "\nbottleneck: {name}, at {:.0} rows/s end to end",
        rows as f64 / (apply + encode + write).as_secs_f64()
    );
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "tickvault=info".into()),
        )
        .init();

    match Cli::parse().command {
        Command::Record {
            venue: args,
            out,
            seconds,
            archive,
            backpressure,
            queue,
            rotate_secs,
        } => {
            let config = args.resolve()?;
            let clock: Arc<dyn Clock> = Arc::new(MonotonicClock::new());
            let venue = registry::build(
                args.venue,
                &config,
                ReqwestFetch::shared()?,
                Arc::clone(&clock),
            )
            .await?;
            let mut sinks = RunSinks::none();
            if let Some(path) = &out {
                sinks = RunSinks::tape(RawRecorder::create(path).await?);
            }
            let pipeline = match &archive {
                Some(dir) => {
                    // Recover before writing a byte, so an interrupted previous
                    // run is quarantined and its lost window recorded rather
                    // than being quietly written around.
                    let now = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_nanos() as i64)
                        .unwrap_or(0);
                    let recovered = recovery::recover(dir, now)?;
                    if !recovered.was_clean() {
                        println!("recovery: {recovered}");
                    }
                    let writer = WriterConfig {
                        max_file_age: Duration::from_secs(rotate_secs),
                        ..WriterConfig::new(dir)
                    };
                    let p = Arc::new(Pipeline::start(PipelineConfig {
                        capacity: queue,
                        ..PipelineConfig::new(writer, backpressure)
                    })?);
                    sinks = sinks.with_archive(Arc::clone(&p));
                    Some(p)
                }
                None => None,
            };
            println!(
                "recording {} {:?} for {seconds}s{}",
                args.venue,
                config
                    .symbols
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>(),
                out.as_deref()
                    .map(|p| format!(" to {p}"))
                    .unwrap_or_default()
            );
            let (outcome, sinks) = tickvault::session::run(
                venue,
                config.symbols.clone(),
                clock,
                StopAfter::duration(Duration::from_secs(seconds)),
                sinks,
            )
            .await?;
            if let Some(tape) = sinks.tape {
                let rec = tape.lock().await;
                println!(
                    "captured {} frames, {} payload bytes",
                    rec.frames(),
                    rec.bytes()
                );
            }
            drop(sinks.archive);
            if let (Some(p), Some(dir)) = (pipeline, &archive) {
                let stats = p.stats();
                let writer = tickvault::pipeline::shutdown_shared(p).await?;
                println!(
                    "archive: {} ({} files)\n{}",
                    stats,
                    writer.manifest().files().len(),
                    ArchiveReader::open(dir)?.verify()
                );
            }
            println!(
                "{} frames, {} reconnects\n\n{}",
                outcome.frames, outcome.reconnects, outcome.report
            );
        }

        Command::ReplayTape {
            venue: args,
            tape,
            drop,
            drop_every,
            payloads,
            start,
            archive,
        } => {
            let config = args.resolve()?;
            // Replay stamps come from the tape; the clock only supplies the
            // sealing timestamp at the end.
            let clock: Arc<dyn Clock> = Arc::new(ManualClock::default());
            let http = ReqwestFetch::shared()?;
            let venue = match registry::build_offline(
                args.venue,
                &config,
                Arc::clone(&http),
                Arc::clone(&clock),
            ) {
                Ok(v) => v,
                // Only Kraken needs the network here, and only for precision.
                Err(_) => registry::build(args.venue, &config, http, Arc::clone(&clock)).await?,
            };

            let original = if payloads {
                RawTape::read_payloads(&tape, args.venue, parse_instant(&start)?)?
            } else {
                RawTape::read_jsonl(&tape)?
            };
            if original.is_empty() {
                bail!("{tape} contains no frames");
            }
            let mut to_drop = drop;
            if let Some(n) = drop_every {
                if n == 0 {
                    bail!("--drop-every must be at least 1");
                }
                // Determined by parsing rather than by matching a substring:
                // the substrings collide across venues.
                let book_frames = registry::delta_frame_indices(venue.as_ref(), &original);
                to_drop.extend(book_frames.iter().step_by(n).copied());
            }
            let played = original.without(&to_drop);
            println!(
                "replaying {} of {} frames ({} removed)",
                played.len(),
                original.len(),
                original.len() - played.len()
            );

            let mut session = BookSession::new(venue, config.symbols.clone());
            let pipeline = match archive.as_deref() {
                Some(dir) => {
                    // Block, never drop: a replay has no live socket to protect,
                    // so a dropped row here would be a hole invented by the tool.
                    let p = Arc::new(Pipeline::start(PipelineConfig::new(
                        WriterConfig::new(dir),
                        BackpressurePolicy::Block,
                    ))?);
                    session.enable_archive(4_096);
                    Some(p)
                }
                None => None,
            };
            let mut last = tickvault::clock::Stamp::ZERO;
            let mut unparsed = 0usize;
            for frame in &played.frames {
                let raw = frame.to_raw();
                last = raw.stamp;
                if let Err(e) = session.ingest(&raw) {
                    if unparsed == 0 {
                        eprintln!("unparsed frame: {e}");
                    }
                    unparsed += 1;
                }
                if let Some(p) = pipeline.as_ref() {
                    submit_all(p, session.take_archive_batches()).await;
                }
            }
            session.seal(last);
            if let Some(p) = pipeline {
                submit_all(&p, session.flush_archive()).await;
                let stats = p.stats();
                let writer = tickvault::pipeline::shutdown_shared(p).await?;
                let dir = archive.as_deref().expect("archive dir");
                println!(
                    "archive: {} ({} files) at {dir}",
                    stats,
                    writer.manifest().files().len()
                );
            }
            if unparsed > 0 {
                println!("{unparsed} frames could not be parsed");
            }

            for symbol in &config.symbols {
                if let Some(book) = session.book(symbol) {
                    println!(
                        "{symbol}: best bid {:?} best ask {:?} digest {:08x} ready {}",
                        book.best_bid().map(|(p, _)| p.to_string()),
                        book.best_ask().map(|(p, _)| p.to_string()),
                        book.digest(),
                        session.is_ready(symbol),
                    );
                }
            }
            println!("\n{}", session.report());
        }

        Command::Verify { archive, read_only } => {
            if !read_only {
                let now = wall_now();
                let recovered = recovery::recover(&archive, now)?;
                println!("recovery: {recovered}");
            }
            let reader = ArchiveReader::open(&archive)?;
            let report = reader.verify();
            println!("{report}");
            for t in reader.manifest().truncations() {
                println!(
                    "truncation: {} lost {}, quarantined {}",
                    t.reason,
                    t.lost_nanos()
                        .map(|n| format!("{:.3}s", n as f64 / 1e9))
                        .unwrap_or_else(|| "an unknown span".to_string()),
                    t.quarantined.as_deref().unwrap_or("nothing")
                );
            }
            if !report.is_clean() {
                bail!("archive verification failed");
            }
        }

        Command::Compact {
            archive,
            exclude_date,
        } => {
            let outcome = tickvault::store::compact::compact_all(
                &archive,
                &WriterConfig::new(&archive),
                wall_now(),
                exclude_date.as_deref(),
            )?;
            println!("{outcome}");
            let report = ArchiveReader::open(&archive)?.verify();
            println!("{report}");
            if !report.is_clean() {
                bail!("archive verification failed after compaction");
            }
        }

        Command::Soak {
            archive,
            start_seq,
            rotate_ms,
            batch_rows,
            seconds,
            pace_us,
            backpressure,
        } => {
            soak(
                archive,
                start_seq,
                rotate_ms,
                batch_rows,
                seconds,
                pace_us,
                backpressure,
            )
            .await?;
        }

        Command::Reconstruct {
            archive,
            venue,
            symbol,
            at,
            depth,
            no_checkpoints,
            show,
        } => {
            let symbol = Symbol::parse(&symbol).map_err(anyhow::Error::msg)?;
            let at_wall = parse_instant(&at)?;
            let mut request = Request::new(venue, &symbol, at_wall);
            if let Some(depth) = depth {
                request = request.with_depth(depth);
            }
            if no_checkpoints {
                request = request.without_checkpoints();
            }
            let built = Reconstructor::open(&archive)?.at(&request)?;
            println!("{built}");
            println!("digest {:08x}", built.digest());
            if !built.trust.is_clean() {
                println!("NOT CLEAN: {}", built.trust);
            }
            let bids = built.book.top(tickvault::types::Side::Bid, show);
            let asks = built.book.top(tickvault::types::Side::Ask, show);
            println!(
                "\n{:>18}  {:>14} | {:>14}  {:<18}",
                "bid qty", "bid", "ask", "ask qty"
            );
            for i in 0..show.min(bids.len().max(asks.len())) {
                let b = bids
                    .get(i)
                    .map(|(p, q)| (q.to_string(), p.to_string()))
                    .unwrap_or_default();
                let a = asks
                    .get(i)
                    .map(|(p, q)| (p.to_string(), q.to_string()))
                    .unwrap_or_default();
                println!("{:>18}  {:>14} | {:>14}  {:<18}", b.0, b.1, a.0, a.1);
            }
        }

        Command::Checkpoint {
            archive,
            every_secs,
        } => {
            let reconstructor = Reconstructor::open(&archive)?;
            let interval = (every_secs as i64) * 1_000_000_000;
            if interval <= 0 {
                bail!("--every-secs must be at least 1");
            }
            // One series per partition, since each has its own book.
            let mut partitions: std::collections::BTreeMap<(VenueId, Symbol), (i64, i64)> =
                Default::default();
            for file in reconstructor.reader().files() {
                let entry = partitions
                    .entry((file.venue, file.symbol.clone()))
                    .or_insert((i64::MAX, i64::MIN));
                entry.0 = entry.0.min(file.first_recv_wall);
                entry.1 = entry.1.max(file.last_recv_wall);
            }
            if partitions.is_empty() {
                bail!("{archive} has no files to checkpoint");
            }

            let mut written = 0;
            for ((venue, symbol), (first, last)) in partitions {
                let mut at = first + interval;
                while at <= last {
                    let built = reconstructor.at(&Request::new(venue, &symbol, at))?;
                    if !built.is_empty() {
                        checkpoint::write(
                            &archive,
                            &checkpoint::Checkpoint::of_l2(venue, &built.book, at),
                        )?;
                        written += 1;
                    }
                    at += interval;
                }
                println!(
                    "{venue} {symbol}: {:.1}s of archive",
                    (last - first) as f64 / 1e9
                );
            }
            println!("{written} checkpoint(s) written every {every_secs}s");
        }

        Command::Query {
            archive,
            venue,
            symbol,
            from,
            to,
            bar_secs,
            depth,
        } => {
            let symbol = Symbol::parse(&symbol).map_err(anyhow::Error::msg)?;
            let reconstructor = Reconstructor::open(&archive)?;
            let (start, end) = archive_span(&reconstructor, venue, &symbol)?;
            let query = Query::new(
                venue,
                &symbol,
                from.as_deref()
                    .map(parse_instant)
                    .transpose()?
                    .unwrap_or(start - 1),
                to.as_deref().map(parse_instant).transpose()?.unwrap_or(end),
            )
            .with_depth(depth);

            let interval = (bar_secs * 1e9) as i64;
            if interval <= 0 {
                bail!("--bar-secs must be positive");
            }
            let mut cursor = query.cursor(&reconstructor)?;
            let bars = tickvault::query::aggregate::bars(&mut cursor, interval)?;

            println!(
                "{venue} {symbol} over {:.3}s: {} messages, {} rows, {} file(s), from {}",
                query.duration_nanos() as f64 / 1e9,
                cursor.messages(),
                cursor.rows(),
                cursor.files_opened(),
                cursor.origin()
            );
            let trust = cursor.trust();
            if !trust.is_clean() {
                println!("NOT CLEAN: {trust}");
            }
            println!(
                "\n{:>14} {:>12} {:>12} {:>12} {:>12} {:>8} {:>10} {:>12}",
                "bar start (s)", "open", "high", "low", "close", "msgs", "spread bp", "volume"
            );
            for bar in &bars {
                println!(
                    "{:>14.3} {:>12} {:>12} {:>12} {:>12} {:>8} {:>10} {:>12}",
                    bar.start_wall as f64 / 1e9,
                    bar.open.to_string(),
                    bar.high.to_string(),
                    bar.low.to_string(),
                    bar.close.to_string(),
                    bar.updates,
                    bar.mean_spread_bps
                        .map(|b| format!("{b:.2}"))
                        .unwrap_or_else(|| "n/a".into()),
                    bar.traded_qty
                        .map(|v| v.to_string())
                        // An aggregated feed does not say what traded, and zero
                        // would claim nothing did.
                        .unwrap_or_else(|| "unknown".into()),
                );
            }

            // The final book's own statistics, from the book that was there.
            let book = cursor.book().clone();
            let top = tickvault::query::aggregate::TopOfBook::of(&book);
            let d = tickvault::query::aggregate::Depth::of(&book, depth);
            println!(
                "\nfinal book: mid {} spread {} imbalance {} over {} levels",
                top.mid()
                    .map(|m| m.to_string())
                    .unwrap_or_else(|| "n/a".into()),
                top.spread()
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "n/a".into()),
                d.imbalance()
                    .map(|i| format!("{i:+.4}"))
                    .unwrap_or_else(|| "n/a".into()),
                depth
            );
        }

        Command::Replay {
            archive,
            venue,
            symbol,
            from,
            to,
            speed,
            every,
        } => {
            let symbol = Symbol::parse(&symbol).map_err(anyhow::Error::msg)?;
            let reconstructor = Reconstructor::open(&archive)?;
            let (start, end) = archive_span(&reconstructor, venue, &symbol)?;
            let query = Query::new(
                venue,
                &symbol,
                from.as_deref()
                    .map(parse_instant)
                    .transpose()?
                    .unwrap_or(start - 1),
                to.as_deref().map(parse_instant).transpose()?.unwrap_or(end),
            );
            let pace = if speed > 0.0 {
                Speed::Scaled(speed)
            } else {
                Speed::Unpaced
            };

            let mut cursor = query.cursor(&reconstructor)?;
            let mut seen = 0u64;
            let stats = tickvault::query::replay::replay(&mut cursor, pace, |tick, cursor| {
                seen += 1;
                if seen.is_multiple_of(every.max(1)) {
                    let top = tickvault::query::aggregate::TopOfBook::of(cursor.book());
                    println!(
                        "{:>20} {:>12} / {:<12} spread {}{}",
                        tick.at_wall,
                        top.bid.map(|b| b.0.to_string()).unwrap_or_default(),
                        top.ask.map(|a| a.0.to_string()).unwrap_or_default(),
                        top.spread()
                            .map(|s| s.to_string())
                            .unwrap_or_else(|| "n/a".into()),
                        if tick.suspect { "  SUSPECT" } else { "" },
                    );
                }
                Ok(())
            })
            .await?;

            println!(
                "\n{} messages ({} suspect) covering {:.3}s in {:.3}s{}",
                stats.messages,
                stats.suspect_messages,
                stats.archive_span_nanos as f64 / 1e9,
                stats.elapsed_nanos as f64 / 1e9,
                stats
                    .speedup()
                    .map(|s| format!(", {s:.1}x real time"))
                    .unwrap_or_default()
            );
        }

        Command::Capabilities { venue } => {
            let clock: Arc<dyn Clock> = Arc::new(MonotonicClock::new());
            let http = ReqwestFetch::shared()?;
            let ids: Vec<VenueId> = match venue {
                Some(v) => vec![v],
                None => VenueId::ALL.to_vec(),
            };
            for id in ids {
                let config = VenueConfig {
                    symbols: vec![VenueConfig::default_symbol(id)],
                    kraken_precision: Some(Precision { price: 1, qty: 8 }),
                    ..VenueConfig::default()
                };
                let v =
                    registry::build_offline(id, &config, Arc::clone(&http), Arc::clone(&clock))?;
                let c = v.capabilities();
                println!("{}", c.id);
                println!("  book level        {}", c.book_level);
                println!("  validation        {:?}", c.validation);
                println!("  detects loss      {}", c.can_detect_loss());
                println!("  sequence scope    {:?}", c.scope);
                println!("  validation timing {:?}", c.timing);
                println!("  snapshot source   {:?}", c.snapshot_source);
                println!("  feed depth        {:?}", c.feed_depth);
                println!("  decimals          {:?}", c.decimals);
                println!("  redundant deletes {:?}", c.redundant_deletes);
                println!("  venue timestamps  {:?}", c.timestamps);
                println!("  keepalive         {:?}", c.keepalive);
                println!("  requires auth     {}", c.requires_auth);
                for limit in &c.detection_limits {
                    println!("  blind spot ({}): {}", limit.scope, limit.consequence);
                }
                println!();
            }
        }

        Command::Serve { config, dry_run } => {
            let config = tickvault::config::Config::read(&config)?;
            println!(
                "archive {} | backpressure {} | rotate {}s | queue {}",
                config.archive.display(),
                config.backpressure,
                config.rotate_secs,
                config.queue
            );
            for entry in &config.venues {
                let resolved = entry.resolve()?;
                println!(
                    "  {:<11} {:?} -> {}",
                    entry.name.to_string(),
                    resolved
                        .symbols
                        .iter()
                        .map(|s| s.to_string())
                        .collect::<Vec<_>>(),
                    config.archive_for(entry.name).display()
                );
            }
            match &config.status {
                Some(status) => println!("  status on http://{}", status.listen),
                None => println!("  no status service configured"),
            }
            if dry_run {
                return Ok(());
            }

            let clock: Arc<dyn Clock> = Arc::new(MonotonicClock::new());
            let health = Arc::new(tickvault::supervise::Health::default());

            if let Some(status) = config.status.clone() {
                let health = Arc::clone(&health);
                let clock = Arc::clone(&clock);
                tokio::spawn(async move {
                    if let Err(e) = tickvault::status::serve(&status.listen, health, clock).await {
                        tracing::error!(error = %e, "status service stopped");
                    }
                });
            }

            // Ctrl-C has to reach the writers rather than the process. An open
            // Parquet file is buffered whole in memory, so exiting without
            // closing it loses everything since the last rotation. The signal
            // asks the supervisor to stop, and the supervisor drains.
            let (stop, shutdown) = tokio::sync::watch::channel(false);
            tokio::spawn(async move {
                if tokio::signal::ctrl_c().await.is_ok() {
                    println!("\nstopping, closing open files");
                    let _ = stop.send(true);
                }
            });
            tickvault::supervise::serve(config, clock, Arc::clone(&health), shutdown).await?;
            println!("stopped");
        }
        Command::Bench { messages, levels } => {
            bench(messages, levels).await?;
        }

        Command::Retention {
            archive,
            max_age_days,
            max_bytes,
            dry_run,
        } => {
            let policy = tickvault::store::retention::Policy {
                max_age_days,
                max_bytes,
            };
            if policy.is_unbounded() {
                bail!("give --max-age-days or --max-bytes, or there is no policy to apply");
            }
            println!("policy: {}", policy.describe());
            let now = MonotonicClock::new().stamp().wall_nanos;
            if dry_run {
                let reader = ArchiveReader::open(&archive)?;
                let doomed = tickvault::store::retention::select(reader.files(), policy, now);
                if doomed.is_empty() {
                    println!("nothing to remove");
                } else {
                    for f in &doomed {
                        println!(
                            "  would remove {} ({} rows, {:.2} MB)",
                            f.path,
                            f.rows,
                            f.bytes as f64 / 1e6
                        );
                    }
                }
            } else {
                let removed = tickvault::store::retention::enforce(&archive, policy, now)?;
                println!("{removed}");
                if let Some(oldest) = removed.oldest_kept_wall {
                    println!(
                        "oldest kept: {}",
                        tickvault::clock::format_rfc3339_nanos(oldest)
                    );
                }
            }
        }
        Command::Transcode {
            archive,
            out,
            compression,
        } => {
            let (rows, files, before, after) = transcode(&archive, &out, &compression)?;
            println!(
                "{files} files, {rows} rows: {:.2} MB -> {:.2} MB as {compression}",
                before as f64 / 1e6,
                after as f64 / 1e6
            );
        }
        Command::Coverage {
            archive,
            bucket_secs,
            out,
        } => {
            if bucket_secs <= 0 {
                bail!("--bucket-secs must be positive");
            }
            let json = coverage_json(&archive, bucket_secs)?;
            match out {
                Some(path) => {
                    std::fs::write(&path, &json)?;
                    println!("wrote {path}");
                }
                None => println!("{json}"),
            }
        }
        Command::Plan { venue: args } => {
            let config = args.resolve()?;
            let clock: Arc<dyn Clock> = Arc::new(MonotonicClock::new());
            let http = ReqwestFetch::shared()?;
            let v = registry::build_offline(args.venue, &config, http, clock)
                .or_else(|_| bail!("{} needs the network to build; use --precision", args.venue))?;
            let caps = v.capabilities();
            let plan = caps
                .plan_subscriptions(&config.symbols)
                .map_err(anyhow::Error::msg)?;
            println!(
                "{}: {} symbols over {} connection(s)",
                args.venue,
                plan.symbol_count(),
                plan.connection_count()
            );
            println!("  {}", plan.rationale);
            println!(
                "  a single gap would invalidate at most {} symbol(s)",
                plan.worst_case_blast_radius(caps.gap_is_connection_wide())
            );
            for (i, conn) in plan.connections.iter().enumerate() {
                let names: Vec<String> = conn.iter().map(|s| s.to_string()).collect();
                println!("  connection {i}: {}", names.join(", "));
            }
        }
    }
    Ok(())
}