znippy-common 0.10.13

Core logic and data structures for Znippy, a parallel chunked compression system.
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
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
//! **Keyed feed archives** — znippy's custom archive type for security feeds
//! (CVE advisories first; malware/known-bad, popular names, signer keys later).
//!
//! # Why
//!
//! A feed like the full OSV + NVD + KEV advisory set is 2.65 M rows / 884 MB of
//! JSON. Loaded as one `Vec` it costs ~3 GB of RAM, which a 2 GB box does not
//! have. The scan never needs all of it at once: it asks "what is known about
//! package *P* in ecosystem *E*", one package at a time. So the set is stored
//! sorted by key in small frames, and a lookup reads exactly one frame.
//!
//! # Layout
//!
//! Every file of the archive is a frame; the names ARE the key index:
//!
//! ```text
//!  ┌──────────── blob region (one zstd/openzl blob per frame) ─────────────┐
//!  │ h/header                     text: format, feed, kind, generation, rev │
//!  │ k/npm/@angular/core          Arrow IPC, ~64 KB: rows of keys           │
//!  │ k/npm/express                  [@angular/core … ejs], sorted by key    │
//!  │ …                                                                      │
//!  │ k/pypi/django                one data frame run per group (ecosystem)  │
//!  │ t/npm/left-pad               tombstones (delta archives only)          │
//!  │ s/CVE-2021-44228             secondary index (skey, group, key) rows   │
//!  ├──────────── metadata tail ─────────────────────────────────────────────┤
//!  │ data sub-index per group     GroupKey{pkg_type: feed type_id,          │
//!  │   (+ feed columns: section,           repo: <group>}                   │
//!  │    group, first/last_key,                                              │
//!  │    keys, rows)                                                         │
//!  │ __znippy_lookup__ / __znippy_trie__   sorted paths  ← the key index    │
//!  │ __znippy_sign_archive__      root CMS over every (path, chunk hash)    │
//!  │ manifest · ZNPYMIDX · offset                                           │
//!  └────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! * A frame holds **whole keys only** (all rows of a package), so frame names
//!   are unique and `k/<group>/<first key>` sorts exactly as the keys do.
//! * Lookup of key `K` in group `G`: the frame that can hold it is the
//!   **floor** of `k/G/K` among the sorted paths
//!   ([`ArchiveReader::floor_path`]) — one binary search over ~20 k cached
//!   names — then one `pread` + decompress + blake3 of that one frame.
//! * The frame's first column is always the key column (Utf8, sorted).
//! * The secondary index maps a second key (an advisory id or alias) to the
//!   `(group, key)` pairs that carry it, in frames of its own.
//! * Signing uses znippy's existing root signature: it folds every frame's
//!   path-bound digest, so a frame, a name or a chunk hash cannot change
//!   without `verify_archive` failing. Because the key index *is* the signed
//!   names, the index cannot be bent either.
//!
//! # Generations
//!
//! A **base** archive is a full set at generation `g`. A **delta** archive at
//! generation `g+1` names `base_generation = g` and carries, per changed key,
//! the key's complete new rows (a data frame) or a tombstone. A
//! [`FeedStack`] reads base + deltas newest-first: the first layer that knows a
//! key decides. [`FeedStack::compact`] folds a stack into a new base, streaming
//! (one frame per layer in memory).
//!
//! Zero rayon: the writer is a single sequential pass, the reader is `&self`
//! positioned reads, shareable across gatling workers.

use std::collections::{HashSet, VecDeque};
use std::fs::File;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use anyhow::{Result, anyhow, bail, ensure};
use arrow::array::{
    Array, ArrayRef, Int8Builder, ListArray, StringArray, StringBuilder,
    UInt32Builder,
};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use arrow::ipc::writer::StreamWriter;
use arrow::record_batch::RecordBatch;

use crate::codec::CompressCtx;
use crate::index::{
    ArchiveReader, ChunkLoc, build_arrow_metadata_for_config, compose_index_schema,
};
use crate::meta_sink::{ArchiveMetaSink, ArrowIpcSink, GroupKey};
use crate::plugin::Col;
use crate::plugins::native::feed_native::FEED_FIELDS;

/// The format tag in every header.
pub const FEED_FORMAT: &str = "znippy-feed/v1";
/// Path of the header file.
pub const HEADER_PATH: &str = "h/header";
/// Prefix of data frames: `k/<group>/<first key>`.
pub const DATA_PREFIX: &str = "k/";
/// Prefix of tombstone frames: `t/<group>/<first key>`.
pub const TOMB_PREFIX: &str = "t/";
/// Prefix of secondary-index frames: `s/<first secondary key>`.
pub const SEC_PREFIX: &str = "s/";
/// Target uncompressed size of one frame.
pub const DEFAULT_FRAME_BYTES: usize = 64 * 1024;
/// Decoded frames a reader keeps (MRU). 16 × ~64 KB.
const FRAME_CACHE: usize = 16;
/// Frames bigger than this are never cached.
const FRAME_CACHE_MAX_BYTES: u64 = 1 << 20;
/// Separates a key from its continuation-frame number in a frame name.
pub const CONT: char = '\u{1}';

/// Base (a full set) or delta (changes on top of `base_generation`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FeedKind {
    Base,
    Delta,
}

impl FeedKind {
    fn as_str(self) -> &'static str {
        match self {
            FeedKind::Base => "base",
            FeedKind::Delta => "delta",
        }
    }
}

/// What a frame is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Section {
    Header,
    Data,
    Tombstone,
    Secondary,
}

impl Section {
    pub fn as_str(self) -> &'static str {
        match self {
            Section::Header => "header",
            Section::Data => "data",
            Section::Tombstone => "tombstone",
            Section::Secondary => "secondary",
        }
    }
}

/// The per-frame facts the feed handler puts in the sub-index columns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameStats {
    pub section: Section,
    pub group: String,
    pub first_key: String,
    pub last_key: String,
    pub keys: u32,
    pub rows: u32,
}

/// The header of a feed archive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeedHeader {
    /// Feed type name (`advisory`).
    pub feed: String,
    /// The handler `type_id` the data sub-indexes carry.
    pub type_id: i8,
    pub kind: FeedKind,
    /// This archive's generation.
    pub generation: u64,
    /// The generation a delta applies on top of (a base: its own generation).
    pub base_generation: u64,
    /// Free-form revision label (e.g. the intel bundle id + sequence).
    pub rev: String,
    /// Groups (ecosystems) with data or tombstones, sorted.
    pub groups: Vec<String>,
    pub keys: u64,
    pub rows: u64,
    pub tombstones: u64,
    pub secondary_rows: u64,
}

impl FeedHeader {
    fn to_bytes(&self) -> Vec<u8> {
        let groups: Vec<String> = self.groups.iter().map(|g| encode_group(g)).collect();
        format!(
            "format={FEED_FORMAT}\nfeed={}\ntype_id={}\nkind={}\ngeneration={}\nbase_generation={}\nrev={}\ngroups={}\nkeys={}\nrows={}\ntombstones={}\nsecondary_rows={}\n",
            self.feed,
            self.type_id,
            self.kind.as_str(),
            self.generation,
            self.base_generation,
            self.rev,
            groups.join(","),
            self.keys,
            self.rows,
            self.tombstones,
            self.secondary_rows,
        )
        .into_bytes()
    }

    fn parse(bytes: &[u8]) -> Result<Self> {
        let text = std::str::from_utf8(bytes).map_err(|_| anyhow!("feed header is not UTF-8"))?;
        let mut kv = std::collections::HashMap::new();
        for line in text.lines() {
            if let Some((k, v)) = line.split_once('=') {
                kv.insert(k, v);
            }
        }
        let get = |k: &str| kv.get(k).copied().ok_or_else(|| anyhow!("feed header lacks `{k}`"));
        ensure!(
            get("format")? == FEED_FORMAT,
            "feed header format {:?}; this build reads {FEED_FORMAT}",
            get("format")?
        );
        let num = |k: &str| -> Result<u64> {
            get(k)?.parse().map_err(|_| anyhow!("feed header `{k}` is not a number"))
        };
        let groups = get("groups")?;
        Ok(Self {
            feed: get("feed")?.to_string(),
            type_id: get("type_id")?.parse().map_err(|_| anyhow!("feed header type_id"))?,
            kind: match get("kind")? {
                "base" => FeedKind::Base,
                "delta" => FeedKind::Delta,
                k => bail!("feed header kind {k:?}"),
            },
            generation: num("generation")?,
            base_generation: num("base_generation")?,
            rev: get("rev")?.to_string(),
            groups: if groups.is_empty() {
                Vec::new()
            } else {
                groups.split(',').map(decode_group).collect::<Result<_>>()?
            },
            keys: num("keys")?,
            rows: num("rows")?,
            tombstones: num("tombstones")?,
            secondary_rows: num("secondary_rows")?,
        })
    }
}

/// Group names go into paths and the header list: `/`, `,`, `%` and control
/// bytes are percent-encoded.
fn encode_group(g: &str) -> String {
    let mut bytes = Vec::with_capacity(g.len());
    for b in g.bytes() {
        if b == b'/' || b == b',' || b == b'%' || b < 0x20 || b == 0x7f {
            bytes.extend_from_slice(format!("%{b:02X}").as_bytes());
        } else {
            bytes.push(b);
        }
    }
    String::from_utf8(bytes).expect("escaping ASCII bytes keeps UTF-8 valid")
}

fn decode_group(s: &str) -> Result<String> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            ensure!(i + 3 <= b.len(), "bad group escape in {s:?}");
            let hex = std::str::from_utf8(&b[i + 1..i + 3]).map_err(|_| anyhow!("bad group escape"))?;
            out.push(u8::from_str_radix(hex, 16).map_err(|_| anyhow!("bad group escape in {s:?}"))?);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| anyhow!("group {s:?} is not UTF-8"))
}

fn data_prefix(group: &str) -> String {
    format!("{DATA_PREFIX}{}/", encode_group(group))
}

fn tomb_prefix(group: &str) -> String {
    format!("{TOMB_PREFIX}{}/", encode_group(group))
}

/// Split a frame path into `(section, group, first key)`.
fn parse_path(path: &str) -> Result<(Section, String, String)> {
    if path == HEADER_PATH {
        return Ok((Section::Header, String::new(), String::new()));
    }
    if let Some(rest) = path.strip_prefix(SEC_PREFIX) {
        return Ok((Section::Secondary, String::new(), rest.to_string()));
    }
    let (section, rest) = if let Some(r) = path.strip_prefix(DATA_PREFIX) {
        (Section::Data, r)
    } else if let Some(r) = path.strip_prefix(TOMB_PREFIX) {
        (Section::Tombstone, r)
    } else {
        bail!("{path:?} is not a feed frame path");
    };
    let (g, k) = rest.split_once('/').ok_or_else(|| anyhow!("{path:?} has no group"))?;
    // A continuation frame `<key>\x01<seq>` starts with `<key>`.
    let k = k.split(CONT).next().unwrap_or(k);
    Ok((section, decode_group(g)?, k.to_string()))
}

fn decode_frame(bytes: &[u8]) -> Result<RecordBatch> {
    let reader = crate::ipc_guard::stream_reader(bytes)?;
    let schema = reader.schema();
    let mut batches = Vec::new();
    for b in reader {
        batches.push(b?);
    }
    match batches.len() {
        1 => Ok(batches.pop().expect("one")),
        _ => Ok(arrow::compute::concat_batches(&schema, &batches)?),
    }
}

fn key_column(batch: &RecordBatch) -> Result<&StringArray> {
    ensure!(batch.num_columns() > 0, "feed frame has no columns");
    batch
        .column(0)
        .as_any()
        .downcast_ref::<StringArray>()
        .ok_or_else(|| anyhow!("feed frame column 0 is not the Utf8 key column"))
}

/// Facts about one frame, from its path and bytes (what the feed handler's
/// `extract_metadata` reports).
pub fn frame_stats(path: &str, data: &[u8]) -> Result<FrameStats> {
    let (section, group, first) = parse_path(path)?;
    if section == Section::Header {
        return Ok(FrameStats { section, group, first_key: first.clone(), last_key: first, keys: 0, rows: 0 });
    }
    let batch = decode_frame(data)?;
    stats_of(section, group, &batch)
}

fn stats_of(section: Section, group: String, batch: &RecordBatch) -> Result<FrameStats> {
    let keys = key_column(batch)?;
    let n = keys.len();
    let mut distinct = 0u32;
    for i in 0..n {
        if i == 0 || keys.value(i) != keys.value(i - 1) {
            distinct += 1;
        }
    }
    Ok(FrameStats {
        section,
        group,
        first_key: if n > 0 { keys.value(0).to_string() } else { String::new() },
        last_key: if n > 0 { keys.value(n - 1).to_string() } else { String::new() },
        keys: distinct,
        rows: n as u32,
    })
}

/// A rough per-row byte cost, for cutting frames near the target size.
fn row_bytes(cols: &[ArrayRef], i: usize) -> usize {
    let mut n = 0usize;
    for c in cols {
        n += match c.data_type() {
            DataType::Utf8 => c
                .as_any()
                .downcast_ref::<StringArray>()
                .map_or(8, |a| a.value_length(i) as usize + 4),
            DataType::List(_) => c.as_any().downcast_ref::<ListArray>().map_or(8, |a| {
                let v = a.value(i);
                match v.as_any().downcast_ref::<StringArray>() {
                    Some(s) => (0..s.len()).map(|j| s.value_length(j) as usize + 4).sum::<usize>() + 4,
                    None => v.len() * 8 + 4,
                }
            }),
            DataType::Boolean => 1,
            t => t.primitive_width().unwrap_or(8),
        };
    }
    n
}

fn encode_batch(batch: &RecordBatch) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    {
        let mut w = StreamWriter::try_new(&mut buf, batch.schema().as_ref())?;
        w.write(batch)?;
        w.finish()?;
    }
    Ok(buf)
}

/// How to write a feed archive.
#[derive(Debug, Clone)]
pub struct FeedOptions {
    pub feed: String,
    pub type_id: i8,
    pub kind: FeedKind,
    pub generation: u64,
    /// For a delta: the generation it applies on top of. Ignored for a base
    /// (set to `generation`).
    pub base_generation: u64,
    pub rev: String,
    pub frame_bytes: usize,
    pub level: i32,
}

impl FeedOptions {
    /// A base archive of `feed` at `generation`.
    pub fn base(feed: &str, type_id: i8, generation: u64, rev: impl Into<String>) -> Self {
        Self {
            feed: feed.into(),
            type_id,
            kind: FeedKind::Base,
            generation,
            base_generation: generation,
            rev: rev.into(),
            frame_bytes: DEFAULT_FRAME_BYTES,
            level: 3,
        }
    }

    /// A delta archive at `generation` on top of `base_generation`.
    pub fn delta(feed: &str, type_id: i8, base_generation: u64, generation: u64, rev: impl Into<String>) -> Self {
        Self { kind: FeedKind::Delta, base_generation, ..Self::base(feed, type_id, generation, rev) }
    }
}

/// What a finished write produced.
#[derive(Debug, Clone)]
pub struct FeedReport {
    pub path: PathBuf,
    pub bytes: u64,
    pub data_frames: u64,
    pub tomb_frames: u64,
    pub secondary_frames: u64,
    pub keys: u64,
    pub rows: u64,
    pub tombstones: u64,
    pub secondary_rows: u64,
}

struct FrameRow {
    path: String,
    loc: ChunkLoc,
    stats: FrameStats,
}

struct GroupState {
    group: String,
    gidx: u32,
    frames: Vec<FrameRow>,
    pending: Vec<RecordBatch>,
    pending_bytes: usize,
    last_key: Option<String>,
    /// Key-arena offset/length of the current key (for secondary rows).
    cur_key: (u64, u32),
    tombs: Vec<String>,
    /// The name of the next frame when it begins in the middle of a key (a
    /// continuation frame), else `None` (named by its first key).
    pending_name: Option<String>,
    /// Continuation frames cut so far inside the current key.
    cont_seq: u32,
}

/// One secondary-index row, both strings in the writer's arena.
#[derive(Clone, Copy)]
struct SecRow {
    s_off: u64,
    s_len: u32,
    gidx: u32,
    k_off: u64,
    k_len: u32,
}

/// Streams a feed archive to disk. Feed it rows **sorted by (group, key)**:
/// every group once, keys ascending within it. A key's rows may span several
/// [`add_rows`](Self::add_rows) calls; a frame is only ever cut between keys.
pub struct FeedWriter {
    out: PathBuf,
    staged: PathBuf,
    file: Arc<File>,
    cursor: u64,
    ctx: Option<CompressCtx>,
    opts: FeedOptions,
    schema: SchemaRef,
    done_groups: Vec<(String, Vec<FrameRow>)>,
    seen_groups: HashSet<String>,
    cur: Option<GroupState>,
    arena: Vec<u8>,
    sec: Vec<SecRow>,
    keys: u64,
    rows: u64,
    tombstones: u64,
    sec_buf: Vec<String>,
}

impl FeedWriter {
    /// Start a feed archive at `out` for rows of `schema`. Column 0 must be the
    /// Utf8 key column.
    pub fn create(out: &Path, schema: SchemaRef, opts: FeedOptions) -> Result<Self> {
        ensure!(
            schema.fields().first().is_some_and(|f| f.data_type() == &DataType::Utf8),
            "feed schema column 0 must be the Utf8 key column"
        );
        ensure!(!opts.rev.contains('\n'), "feed rev must be one line");
        ensure!(!opts.feed.contains('\n') && !opts.feed.is_empty(), "feed name must be one non-empty line");
        // Unique per writer: two writers of the same archive (two readers building a missing
        // feed at once) must not share a staging file; the last rename wins, whole.
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let mut name = out.file_name().map(|n| n.to_os_string()).unwrap_or_default();
        name.push(format!(".{}.{nanos}.partial", std::process::id()));
        let staged = out.with_file_name(name);
        let file = Arc::new(
            std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&staged)
                .map_err(|e| anyhow!("create {}: {e}", staged.display()))?,
        );
        // No codec in this build (openzl off): frames are stored raw.
        let ctx = CompressCtx::new(opts.level).ok();
        let mut opts = opts;
        if opts.kind == FeedKind::Base {
            opts.base_generation = opts.generation;
        }
        Ok(Self {
            out: out.to_path_buf(),
            staged,
            file,
            cursor: 0,
            ctx,
            opts,
            schema,
            done_groups: Vec::new(),
            seen_groups: HashSet::new(),
            cur: None,
            arena: Vec::new(),
            sec: Vec::new(),
            keys: 0,
            rows: 0,
            tombstones: 0,
            sec_buf: Vec::new(),
        })
    }

    fn write_blob(&mut self, path: String, bytes: &[u8]) -> Result<ChunkLoc> {
        let checksum = *blake3::hash(bytes).as_bytes();
        let frame = match self.ctx.as_mut() {
            Some(c) => c.compress(bytes).ok(),
            None => None,
        };
        let (on_disk, compressed): (&[u8], bool) = match &frame {
            Some(f) if f.len() < bytes.len() => (f, true),
            _ => (bytes, false),
        };
        let blob_offset = self.cursor;
        self.file.write_all_at(on_disk, blob_offset)?;
        self.cursor += on_disk.len() as u64;
        let _ = path;
        Ok(ChunkLoc {
            chunk_seq: 0,
            fdata_offset: 0,
            blob_offset,
            blob_size: on_disk.len() as u64,
            uncompressed_size: bytes.len() as u64,
            compressed,
            checksum,
        })
    }

    fn switch_group(&mut self, group: &str) -> Result<()> {
        if self.cur.as_ref().is_some_and(|c| c.group == group) {
            return Ok(());
        }
        self.finish_group()?;
        ensure!(
            self.seen_groups.insert(group.to_string()),
            "feed group {group:?} was written twice: rows must be sorted by (group, key)"
        );
        let gidx = self.done_groups.len() as u32;
        self.cur = Some(GroupState {
            group: group.to_string(),
            gidx,
            frames: Vec::new(),
            pending: Vec::new(),
            pending_bytes: 0,
            last_key: None,
            cur_key: (0, 0),
            tombs: Vec::new(),
            pending_name: None,
            cont_seq: 0,
        });
        Ok(())
    }

    fn flush_pending(&mut self) -> Result<()> {
        let Some(cur) = self.cur.as_mut() else { return Ok(()) };
        if cur.pending.is_empty() {
            return Ok(());
        }
        let batch = arrow::compute::concat_batches(&self.schema, &cur.pending)?;
        cur.pending.clear();
        cur.pending_bytes = 0;
        let group = cur.group.clone();
        let stats = stats_of(Section::Data, group.clone(), &batch)?;
        let name = cur.pending_name.take().unwrap_or_else(|| stats.first_key.clone());
        let path = format!("{}{}", data_prefix(&group), name);
        let bytes = encode_batch(&batch)?;
        let loc = self.write_blob(path.clone(), &bytes)?;
        self.cur.as_mut().expect("cur").frames.push(FrameRow { path, loc, stats });
        Ok(())
    }

    /// Append rows of `group`. `batch` must have the writer's schema and be
    /// sorted by its key column (column 0), continuing after the previous call's
    /// last key. `secondary(batch, row, out)` pushes the row's secondary keys
    /// (an advisory's id and aliases) into `out`.
    pub fn add_rows(
        &mut self,
        group: &str,
        batch: &RecordBatch,
        secondary: &mut dyn FnMut(&RecordBatch, usize, &mut Vec<String>),
    ) -> Result<()> {
        ensure!(
            batch.schema().fields() == self.schema.fields(),
            "feed rows do not have the writer's schema"
        );
        self.switch_group(group)?;
        let keys = key_column(batch)?.clone();
        let cols: Vec<ArrayRef> = batch.columns().to_vec();
        let frame_bytes = self.opts.frame_bytes;
        let mut seg_start = 0usize;
        let mut sec_buf = std::mem::take(&mut self.sec_buf);
        for i in 0..batch.num_rows() {
            let k = keys.value(i);
            let cur = self.cur.as_mut().expect("group set");
            let new_key = match &cur.last_key {
                None => true,
                Some(lk) => {
                    ensure!(
                        k >= lk.as_str(),
                        "feed rows of group {group:?} are not sorted: {k:?} after {lk:?}"
                    );
                    k != lk.as_str()
                }
            };
            // Cut between keys at the target size; inside one key only at twice
            // it, so an ordinary key is never split and a huge one is split
            // into frames of bounded size.
            let cut = if new_key { frame_bytes } else { frame_bytes.saturating_mul(2) };
            if cur.pending_bytes >= cut {
                // Cut here. Between keys the next frame is named by its first key;
                // inside a key (a key bigger than a frame) it is a continuation
                // frame `<key>\x01<seq>`, which sorts right after the key's first
                // frame and before every longer key.
                if i > seg_start {
                    cur.pending.push(batch.slice(seg_start, i - seg_start));
                }
                seg_start = i;
                self.flush_pending()?;
                if !new_key {
                    let cur = self.cur.as_mut().expect("group set");
                    cur.cont_seq += 1;
                    cur.pending_name = Some(format!("{k}{CONT}{:06}", cur.cont_seq));
                }
            }
            if new_key {
                ensure!(!k.contains(CONT), "feed key {k:?} contains the reserved byte U+0001");
                let cur = self.cur.as_mut().expect("group set");
                cur.cont_seq = 0;
                let off = self.arena.len() as u64;
                self.arena.extend_from_slice(k.as_bytes());
                cur.cur_key = (off, k.len() as u32);
                cur.last_key = Some(k.to_string());
                self.keys += 1;
            }
            let cur = self.cur.as_mut().expect("group set");
            cur.pending_bytes += row_bytes(&cols, i);
            let (k_off, k_len) = cur.cur_key;
            let gidx = cur.gidx;
            sec_buf.clear();
            secondary(batch, i, &mut sec_buf);
            for s in &sec_buf {
                let s_off = self.arena.len() as u64;
                self.arena.extend_from_slice(s.as_bytes());
                self.sec.push(SecRow { s_off, s_len: s.len() as u32, gidx, k_off, k_len });
            }
            self.rows += 1;
        }
        self.sec_buf = sec_buf;
        if batch.num_rows() > seg_start {
            let cur = self.cur.as_mut().expect("group set");
            cur.pending.push(batch.slice(seg_start, batch.num_rows() - seg_start));
        }
        Ok(())
    }

    /// Record that `key` of `group` is gone (delta archives only). Keys
    /// ascending within the group; a group's tombstones may be given before,
    /// after or between its rows.
    pub fn tombstone(&mut self, group: &str, key: &str) -> Result<()> {
        ensure!(self.opts.kind == FeedKind::Delta, "only a delta archive carries tombstones");
        self.switch_group(group)?;
        let cur = self.cur.as_mut().expect("group set");
        if let Some(last) = cur.tombs.last() {
            ensure!(key > last.as_str(), "tombstones of {group:?} are not strictly ascending");
        }
        cur.tombs.push(key.to_string());
        self.tombstones += 1;
        Ok(())
    }

    fn finish_group(&mut self) -> Result<()> {
        self.flush_pending()?;
        let Some(mut cur) = self.cur.take() else { return Ok(()) };
        if !cur.tombs.is_empty() {
            let schema = Arc::new(Schema::new(vec![Field::new("key", DataType::Utf8, false)]));
            let per_frame = (self.opts.frame_bytes / 24).max(1);
            let tombs = std::mem::take(&mut cur.tombs);
            for chunk in tombs.chunks(per_frame) {
                let arr = StringArray::from_iter_values(chunk.iter());
                let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr)])?;
                let stats = stats_of(Section::Tombstone, cur.group.clone(), &batch)?;
                let path = format!("{}{}", tomb_prefix(&cur.group), stats.first_key);
                let loc = self.write_blob(path.clone(), &encode_batch(&batch)?)?;
                cur.frames.push(FrameRow { path, loc, stats });
            }
        }
        self.done_groups.push((cur.group, cur.frames));
        Ok(())
    }

    fn arena_str(&self, off: u64, len: u32) -> &str {
        // The arena only ever receives whole `&str`s, so every slice is UTF-8.
        std::str::from_utf8(&self.arena[off as usize..off as usize + len as usize]).unwrap_or("")
    }

    fn write_secondary(&mut self) -> Result<Vec<FrameRow>> {
        let mut sec = std::mem::take(&mut self.sec);
        {
            let arena = &self.arena;
            let s = |off: u64, len: u32| &arena[off as usize..off as usize + len as usize];
            let groups = &self.done_groups;
            sec.sort_unstable_by(|a, b| {
                s(a.s_off, a.s_len)
                    .cmp(s(b.s_off, b.s_len))
                    .then_with(|| groups[a.gidx as usize].0.cmp(&groups[b.gidx as usize].0))
                    .then_with(|| s(a.k_off, a.k_len).cmp(s(b.k_off, b.k_len)))
            });
            sec.dedup_by(|a, b| {
                s(a.s_off, a.s_len) == s(b.s_off, b.s_len)
                    && a.gidx == b.gidx
                    && s(a.k_off, a.k_len) == s(b.k_off, b.k_len)
            });
        }
        let schema = Arc::new(Schema::new(vec![
            Field::new("skey", DataType::Utf8, false),
            Field::new("group", DataType::Utf8, false),
            Field::new("key", DataType::Utf8, false),
        ]));
        let mut frames = Vec::new();
        let frame_bytes = self.opts.frame_bytes;
        let mut start = 0usize;
        let mut bytes = 0usize;
        let mut i = 0usize;
        let n = sec.len();
        let flush = |this: &mut Self, lo: usize, hi: usize, frames: &mut Vec<FrameRow>| -> Result<()> {
            let mut sb = StringBuilder::new();
            let mut gb = StringBuilder::new();
            let mut kb = StringBuilder::new();
            for r in &sec[lo..hi] {
                sb.append_value(this.arena_str(r.s_off, r.s_len));
                gb.append_value(&this.done_groups[r.gidx as usize].0);
                kb.append_value(this.arena_str(r.k_off, r.k_len));
            }
            let batch = RecordBatch::try_new(
                schema.clone(),
                vec![Arc::new(sb.finish()), Arc::new(gb.finish()), Arc::new(kb.finish())],
            )?;
            let stats = stats_of(Section::Secondary, String::new(), &batch)?;
            let path = format!("{SEC_PREFIX}{}", stats.first_key);
            let loc = this.write_blob(path.clone(), &encode_batch(&batch)?)?;
            frames.push(FrameRow { path, loc, stats });
            Ok(())
        };
        while i < n {
            let r = sec[i];
            if i > start && bytes >= frame_bytes {
                let p = sec[i - 1];
                let same = self.arena[r.s_off as usize..(r.s_off + r.s_len as u64) as usize]
                    == self.arena[p.s_off as usize..(p.s_off + p.s_len as u64) as usize];
                if !same {
                    flush(self, start, i, &mut frames)?;
                    start = i;
                    bytes = 0;
                }
            }
            bytes += r.s_len as usize + r.k_len as usize + 16;
            i += 1;
        }
        if n > start {
            flush(self, start, n, &mut frames)?;
        }
        self.sec = sec;
        Ok(frames)
    }

    fn sub_index(&self, rows: &[FrameRow]) -> Result<(Arc<Schema>, RecordBatch)> {
        let fields: Vec<Field> =
            FEED_FIELDS.iter().map(|(n, c)| Field::new(*n, c.data_type(), true)).collect();
        let composed = compose_index_schema(&fields);
        let schema = Arc::new(Schema::new_with_metadata(
            composed.fields().clone(),
            build_arrow_metadata_for_config(&crate::common_config::CONFIG),
        ));
        let paths: Vec<String> = rows.iter().map(|r| r.path.clone()).collect();
        let locs: Vec<ChunkLoc> = rows.iter().map(|r| r.loc.clone()).collect();
        let base = crate::meta_sink_append::base_batch_from_rows(&paths, &locs)?;
        let mut cols: Vec<ArrayRef> = base.columns().to_vec();
        let mut pt = Int8Builder::with_capacity(rows.len());
        for _ in rows {
            pt.append_value(self.opts.type_id);
        }
        cols.push(Arc::new(pt.finish()));
        for (name, col) in FEED_FIELDS {
            let arr: ArrayRef = match col {
                Col::U32 => {
                    let mut b = UInt32Builder::with_capacity(rows.len());
                    for r in rows {
                        b.append_value(if *name == "keys" { r.stats.keys } else { r.stats.rows });
                    }
                    Arc::new(b.finish())
                }
                _ => {
                    let mut b = StringBuilder::new();
                    for r in rows {
                        b.append_value(match *name {
                            "section" => r.stats.section.as_str(),
                            "group" => r.stats.group.as_str(),
                            "first_key" => r.stats.first_key.as_str(),
                            _ => r.stats.last_key.as_str(),
                        });
                    }
                    Arc::new(b.finish())
                }
            };
            cols.push(arr);
        }
        let batch = RecordBatch::try_new(schema.clone(), cols)?;
        Ok((schema, batch))
    }

    /// Seal unsigned.
    pub fn finish(self) -> Result<FeedReport> {
        self.seal(|s| s)
    }

    /// Seal with an archive-root signature (one CMS over every frame's
    /// path-bound digest; no per-frame signatures).
    #[cfg(feature = "sign")]
    pub fn finish_signed(self, signer: Box<dyn crate::sign::ArchiveSigner + Send>) -> Result<FeedReport> {
        self.seal(move |s| s.with_root_signer(signer))
    }

    fn seal(mut self, sink_fn: impl FnOnce(ArrowIpcSink) -> ArrowIpcSink) -> Result<FeedReport> {
        let res = (|| -> Result<FeedReport> {
            self.finish_group()?;
            let sec_frames = self.write_secondary()?;
            let mut groups: Vec<String> = self.done_groups.iter().map(|(g, _)| g.clone()).collect();
            groups.sort();
            let header = FeedHeader {
                feed: self.opts.feed.clone(),
                type_id: self.opts.type_id,
                kind: self.opts.kind,
                generation: self.opts.generation,
                base_generation: self.opts.base_generation,
                rev: self.opts.rev.clone(),
                groups,
                keys: self.keys,
                rows: self.rows,
                tombstones: self.tombstones,
                secondary_rows: self.sec.len() as u64,
            };
            let hb = header.to_bytes();
            let hloc = self.write_blob(HEADER_PATH.into(), &hb)?;
            let header_row = FrameRow {
                path: HEADER_PATH.into(),
                loc: hloc,
                stats: FrameStats {
                    section: Section::Header,
                    group: String::new(),
                    first_key: String::new(),
                    last_key: String::new(),
                    keys: 0,
                    rows: 0,
                },
            };
            let mut sink = sink_fn(ArrowIpcSink::new(self.file.clone(), self.cursor));
            let module = self.opts.feed.clone();
            let mut data_frames = 0u64;
            let mut tomb_frames = 0u64;
            for (g, frames) in &self.done_groups {
                for f in frames {
                    match f.stats.section {
                        Section::Tombstone => tomb_frames += 1,
                        _ => data_frames += 1,
                    }
                }
                if frames.is_empty() {
                    continue;
                }
                let (schema, batch) = self.sub_index(frames)?;
                sink.push_subindex(
                    &schema,
                    &[batch],
                    GroupKey { pkg_type: self.opts.type_id, repo: g.clone(), module_name: module.clone() },
                )?;
            }
            let (schema, batch) = self.sub_index(std::slice::from_ref(&header_row))?;
            sink.push_subindex(
                &schema,
                &[batch],
                GroupKey { pkg_type: self.opts.type_id, repo: "~header".into(), module_name: module.clone() },
            )?;
            if !sec_frames.is_empty() {
                let (schema, batch) = self.sub_index(&sec_frames)?;
                sink.push_subindex(
                    &schema,
                    &[batch],
                    GroupKey { pkg_type: self.opts.type_id, repo: "~secondary".into(), module_name: module },
                )?;
            }
            let bytes = Box::new(sink).finish()?;
            Ok(FeedReport {
                path: self.out.clone(),
                bytes,
                data_frames,
                tomb_frames,
                secondary_frames: sec_frames.len() as u64,
                keys: self.keys,
                rows: self.rows,
                tombstones: self.tombstones,
                secondary_rows: self.sec.len() as u64,
            })
        })();
        match res {
            Ok(r) => {
                std::fs::rename(&self.staged, &self.out)
                    .map_err(|e| anyhow!("rename {} into place: {e}", self.out.display()))?;
                Ok(r)
            }
            Err(e) => {
                let _ = std::fs::remove_file(&self.staged);
                Err(e)
            }
        }
    }
}

/// What one archive knows about a key.
#[derive(Debug, Clone)]
pub enum Hit {
    /// This archive says nothing about the key.
    Absent,
    /// A delta removed the key.
    Removed,
    /// The key's complete rows.
    Rows(RecordBatch),
}

/// What [`FeedArchive::visit`] found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Found {
    Absent,
    Removed,
    Rows,
}

/// One opened feed archive. `&self` reads only (positioned `pread`s), so one
/// archive serves any number of threads. RAM: the sorted frame names + chunk
/// locators (~20 k rows for the full advisory set) and a 16-frame cache.
pub struct FeedArchive {
    path: PathBuf,
    reader: ArchiveReader,
    header: FeedHeader,
    cache: Mutex<VecDeque<(String, RecordBatch)>>,
}

impl FeedArchive {
    /// Open without checking a signature (tests, trusted local files).
    pub fn open(path: &Path) -> Result<Self> {
        let reader = ArchiveReader::open(path)?;
        let hb = reader
            .read_file(HEADER_PATH)
            .map_err(|e| anyhow!("{} is not a feed archive: {e}", path.display()))?;
        let header = FeedHeader::parse(&hb)?;
        Ok(Self { path: path.to_path_buf(), reader, header, cache: Mutex::new(VecDeque::new()) })
    }

    /// Open after verifying the archive-root signature against `roots`. The
    /// key index is the signed frame names, so after this every lookup is
    /// against signed data (each frame's bytes are blake3-checked on read).
    #[cfg(feature = "sign")]
    pub fn open_verified(
        path: &Path,
        roots: &crate::sign::CertStore,
    ) -> Result<(Self, crate::sign::VerifiedSigner)> {
        let report = crate::sign::verify_archive(path, roots)
            .map_err(|e| anyhow!("feed archive {}: {e}", path.display()))?;
        Ok((Self::open(path)?, report.signer))
    }

    pub fn header(&self) -> &FeedHeader {
        &self.header
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Number of frames (all sections).
    pub fn frame_count(&self) -> usize {
        self.reader.row_count()
    }

    /// Read (and cache) one frame by path.
    pub fn read_frame(&self, path: &str) -> Result<RecordBatch> {
        if let Ok(mut c) = self.cache.lock()
            && let Some(pos) = c.iter().position(|(p, _)| p == path)
        {
            let hit = c.remove(pos).expect("pos");
            let b = hit.1.clone();
            c.push_front(hit);
            return Ok(b);
        }
        let bytes = self.reader.read_file(path)?;
        let batch = decode_frame(&bytes)?;
        let (_, _, first) = parse_path(path)?;
        if path != HEADER_PATH {
            let keys = key_column(&batch)?;
            ensure!(
                keys.len() > 0 && keys.value(0) == first,
                "feed frame {path:?} does not start with its own key"
            );
        }
        if bytes.len() as u64 <= FRAME_CACHE_MAX_BYTES
            && let Ok(mut c) = self.cache.lock()
        {
            c.push_front((path.to_string(), batch.clone()));
            c.truncate(FRAME_CACHE);
        }
        Ok(batch)
    }

    fn rows_in(batch: &RecordBatch, col: usize, key: &str) -> Result<Option<(usize, usize)>> {
        let keys = batch
            .column(col)
            .as_any()
            .downcast_ref::<StringArray>()
            .ok_or_else(|| anyhow!("feed key column is not Utf8"))?;
        let n = keys.len();
        let lo = partition(n, |i| keys.value(i) < key);
        let hi = partition(n, |i| keys.value(i) <= key);
        Ok((hi > lo).then_some((lo, hi - lo)))
    }

    /// What this archive knows about `key` in `group`, the rows in one batch.
    /// A key bigger than a frame is concatenated here; [`visit`](Self::visit)
    /// streams it instead.
    pub fn get(&self, group: &str, key: &str) -> Result<Hit> {
        let mut parts: Vec<RecordBatch> = Vec::new();
        match self.visit(group, key, &mut |b| {
            parts.push(b);
            Ok(())
        })? {
            Found::Absent => Ok(Hit::Absent),
            Found::Removed => Ok(Hit::Removed),
            Found::Rows if parts.len() == 1 => Ok(Hit::Rows(parts.pop().expect("one"))),
            Found::Rows => Ok(Hit::Rows(arrow::compute::concat_batches(&parts[0].schema(), &parts)?)),
        }
    }

    /// Stream `key`'s rows to `f`, one frame's slice at a time: the frame that
    /// holds the key's start (the floor of `k/<group>/<key>`), then the key's
    /// continuation frames (`k/<group>/<key>\x01…`). Memory stays one frame
    /// however many rows the key has.
    pub fn visit(
        &self,
        group: &str,
        key: &str,
        f: &mut dyn FnMut(RecordBatch) -> Result<()>,
    ) -> Result<Found> {
        let prefix = data_prefix(group);
        let target = format!("{prefix}{key}");
        let mut found = false;
        if let Some(p) = self.reader.floor_path(&prefix, &target) {
            let p = p.to_string();
            let batch = self.read_frame(&p)?;
            if let Some((lo, n)) = Self::rows_in(&batch, 0, key)? {
                f(batch.slice(lo, n))?;
                found = true;
            }
        }
        let cont = format!("{target}{CONT}");
        for p in self.reader.paths_with_prefix(&cont) {
            // Not through the cache: a huge key would only evict the hot frames.
            let batch = decode_frame(&self.reader.read_file(p)?)?;
            let keys = key_column(&batch)?;
            ensure!(keys.len() > 0 && keys.value(0) == key, "continuation frame {p:?} does not start with {key:?}");
            if let Some((lo, n)) = Self::rows_in(&batch, 0, key)? {
                f(batch.slice(lo, n))?;
                found = true;
            }
        }
        if found {
            return Ok(Found::Rows);
        }
        if self.header.kind == FeedKind::Delta {
            let prefix = tomb_prefix(group);
            let target = format!("{prefix}{key}");
            if let Some(p) = self.reader.floor_path(&prefix, &target) {
                let p = p.to_string();
                let batch = self.read_frame(&p)?;
                if Self::rows_in(&batch, 0, key)?.is_some() {
                    return Ok(Found::Removed);
                }
            }
        }
        Ok(Found::Absent)
    }

    /// The `(group, key)` pairs this archive's secondary index lists for `skey`.
    pub fn secondary(&self, skey: &str) -> Result<Vec<(String, String)>> {
        let target = format!("{SEC_PREFIX}{skey}");
        let Some(p) = self.reader.floor_path(SEC_PREFIX, &target) else { return Ok(Vec::new()) };
        let p = p.to_string();
        let batch = self.read_frame(&p)?;
        let Some((lo, n)) = Self::rows_in(&batch, 0, skey)? else { return Ok(Vec::new()) };
        let col = |i: usize| -> Result<&StringArray> {
            batch.column(i).as_any().downcast_ref::<StringArray>().ok_or_else(|| anyhow!("secondary column"))
        };
        let (g, k) = (col(1)?, col(2)?);
        Ok((lo..lo + n).map(|i| (g.value(i).to_string(), k.value(i).to_string())).collect())
    }

    /// Data frame paths of `group`, in key order.
    pub fn data_frames(&self, group: &str) -> Vec<String> {
        self.reader.paths_with_prefix(&data_prefix(group)).into_iter().map(String::from).collect()
    }

    /// Every tombstoned key of `group`, ascending.
    pub fn tombstones(&self, group: &str) -> Result<Vec<String>> {
        let mut out = Vec::new();
        for p in self.reader.paths_with_prefix(&tomb_prefix(group)) {
            let b = self.read_frame(p)?;
            let k = key_column(&b)?;
            out.extend((0..k.len()).map(|i| k.value(i).to_string()));
        }
        Ok(out)
    }
}

fn partition(n: usize, pred: impl Fn(usize) -> bool) -> usize {
    let (mut lo, mut hi) = (0usize, n);
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if pred(mid) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    lo
}

/// A base archive plus its deltas, read newest-first.
pub struct FeedStack {
    /// `layers[0]` is the base; later entries are deltas in generation order.
    layers: Vec<FeedArchive>,
}

impl FeedStack {
    /// Stack `base` and `deltas`. The chain must be unbroken: every delta names
    /// the previous layer's generation as its `base_generation`.
    pub fn new(base: FeedArchive, mut deltas: Vec<FeedArchive>) -> Result<Self> {
        ensure!(base.header.kind == FeedKind::Base, "{} is not a base feed archive", base.path.display());
        deltas.sort_by_key(|d| d.header.generation);
        let mut prev = base.header.generation;
        for d in &deltas {
            ensure!(d.header.kind == FeedKind::Delta, "{} is not a delta", d.path.display());
            ensure!(
                d.header.feed == base.header.feed && d.header.type_id == base.header.type_id,
                "{} is a {:?} delta, the base is {:?}",
                d.path.display(),
                d.header.feed,
                base.header.feed
            );
            ensure!(
                d.header.base_generation == prev,
                "delta {} applies on generation {}, the stack is at {}",
                d.path.display(),
                d.header.base_generation,
                prev
            );
            prev = d.header.generation;
        }
        let mut layers = vec![base];
        layers.extend(deltas);
        Ok(Self { layers })
    }

    /// Open `base` and `deltas` from disk (unverified).
    pub fn open(base: &Path, deltas: &[PathBuf]) -> Result<Self> {
        let d = deltas.iter().map(|p| FeedArchive::open(p)).collect::<Result<Vec<_>>>()?;
        Self::new(FeedArchive::open(base)?, d)
    }

    /// Open and verify every layer's signature against `roots`.
    #[cfg(feature = "sign")]
    pub fn open_verified(base: &Path, deltas: &[PathBuf], roots: &crate::sign::CertStore) -> Result<Self> {
        let d = deltas
            .iter()
            .map(|p| FeedArchive::open_verified(p, roots).map(|(a, _)| a))
            .collect::<Result<Vec<_>>>()?;
        Self::new(FeedArchive::open_verified(base, roots)?.0, d)
    }

    pub fn layers(&self) -> &[FeedArchive] {
        &self.layers
    }

    /// The newest layer's header.
    pub fn top(&self) -> &FeedHeader {
        &self.layers.last().expect("a stack has a base").header
    }

    /// Effective rows of `key` in `group`: the newest layer that knows the key
    /// decides (rows, or removed → `None`).
    pub fn get(&self, group: &str, key: &str) -> Result<Option<RecordBatch>> {
        for layer in self.layers.iter().rev() {
            match layer.get(group, key)? {
                Hit::Rows(b) => return Ok(Some(b)),
                Hit::Removed => return Ok(None),
                Hit::Absent => {}
            }
        }
        Ok(None)
    }

    /// Stream the effective rows of `key` to `f` (one frame slice at a time);
    /// `true` when the key exists. Newest layer that knows the key decides.
    pub fn visit(
        &self,
        group: &str,
        key: &str,
        f: &mut dyn FnMut(RecordBatch) -> Result<()>,
    ) -> Result<bool> {
        for layer in self.layers.iter().rev() {
            match layer.visit(group, key, f)? {
                Found::Rows => return Ok(true),
                Found::Removed => return Ok(false),
                Found::Absent => {}
            }
        }
        Ok(false)
    }

    /// Candidate `(group, key)` pairs for a secondary key, over every layer.
    /// A candidate may be stale (a delta changed the key); re-read it with
    /// [`get`](Self::get) and filter.
    pub fn secondary(&self, skey: &str) -> Result<Vec<(String, String)>> {
        let mut out = Vec::new();
        for l in &self.layers {
            out.extend(l.secondary(skey)?);
        }
        out.sort();
        out.dedup();
        Ok(out)
    }

    /// Every group any layer has.
    pub fn groups(&self) -> Vec<String> {
        let mut g: Vec<String> = self.layers.iter().flat_map(|l| l.header.groups.iter().cloned()).collect();
        g.sort();
        g.dedup();
        g
    }

    /// Fold the stack into one base archive at the top generation, streaming:
    /// a k-way merge over the layers' sorted frames, one frame per layer in
    /// memory. `secondary` re-derives each row's secondary keys.
    pub fn compact(
        &self,
        out: &Path,
        rev: impl Into<String>,
        secondary: &mut dyn FnMut(&RecordBatch, usize, &mut Vec<String>),
    ) -> Result<FeedReport> {
        self.compact_with(out, rev, secondary, |w| w.finish())
    }

    /// [`compact`](Self::compact), sealed with a root signature.
    #[cfg(feature = "sign")]
    pub fn compact_signed(
        &self,
        out: &Path,
        rev: impl Into<String>,
        secondary: &mut dyn FnMut(&RecordBatch, usize, &mut Vec<String>),
        signer: Box<dyn crate::sign::ArchiveSigner + Send>,
    ) -> Result<FeedReport> {
        self.compact_with(out, rev, secondary, move |w| w.finish_signed(signer))
    }

    fn compact_with(
        &self,
        out: &Path,
        rev: impl Into<String>,
        secondary: &mut dyn FnMut(&RecordBatch, usize, &mut Vec<String>),
        seal: impl FnOnce(FeedWriter) -> Result<FeedReport>,
    ) -> Result<FeedReport> {
        let top = self.top();
        let base = &self.layers[0];
        let schema = self.schema()?;
        let opts = FeedOptions {
            frame_bytes: DEFAULT_FRAME_BYTES,
            ..FeedOptions::base(&top.feed, top.type_id, top.generation, rev)
        };
        let _ = base;
        let mut w = FeedWriter::create(out, schema, opts)?;
        for group in self.groups() {
            let mut cursors: Vec<LayerCursor> = Vec::with_capacity(self.layers.len());
            for l in &self.layers {
                cursors.push(LayerCursor::new(l, &group)?);
            }
            loop {
                // The smallest key any layer still has.
                let mut min: Option<String> = None;
                for c in &cursors {
                    if let Some(k) = c.peek()
                        && min.as_deref().is_none_or(|m| k < m)
                    {
                        min = Some(k.to_string());
                    }
                }
                let Some(key) = min else { break };
                // Newest layer that has it decides (its rows stream straight into
                // the writer); every layer moves past it.
                let mut decided = false;
                for c in cursors.iter_mut().rev() {
                    let mut emit = |b: RecordBatch| w.add_rows(&group, &b, secondary);
                    let had = c.take(&key, if decided { None } else { Some(&mut emit) })?;
                    decided |= had;
                }
            }
        }
        seal(w)
    }

    fn schema(&self) -> Result<SchemaRef> {
        for l in &self.layers {
            for g in &l.header.groups {
                if let Some(p) = l.data_frames(g).first() {
                    return Ok(l.read_frame(p)?.schema());
                }
            }
        }
        bail!("the stack holds no data frame to take the schema from")
    }
}

/// Sorted walk over one layer's keys of one group: data rows and tombstones.
struct LayerCursor<'a> {
    layer: &'a FeedArchive,
    frames: Vec<String>,
    next_frame: usize,
    batch: Option<RecordBatch>,
    row: usize,
    tombs: Vec<String>,
    tomb: usize,
}

impl<'a> LayerCursor<'a> {
    fn new(layer: &'a FeedArchive, group: &str) -> Result<Self> {
        let tombs = if layer.header.kind == FeedKind::Delta { layer.tombstones(group)? } else { Vec::new() };
        let mut c = Self { layer, frames: layer.data_frames(group), next_frame: 0, batch: None, row: 0, tombs, tomb: 0 };
        c.load()?;
        Ok(c)
    }

    /// Make `batch[row]` valid, or leave `batch` empty at the end.
    fn load(&mut self) -> Result<()> {
        while self.batch.as_ref().is_none_or(|b| self.row >= b.num_rows()) {
            if self.next_frame >= self.frames.len() {
                self.batch = None;
                return Ok(());
            }
            // Read without the shared cache: a compaction walks every frame once.
            let bytes = self.layer.reader.read_file(&self.frames[self.next_frame])?;
            self.batch = Some(decode_frame(&bytes)?);
            self.next_frame += 1;
            self.row = 0;
        }
        Ok(())
    }

    fn data_key(&self) -> Option<&str> {
        let b = self.batch.as_ref()?;
        b.column(0).as_any().downcast_ref::<StringArray>().map(|k| k.value(self.row))
    }

    fn peek(&self) -> Option<&str> {
        let t = self.tombs.get(self.tomb).map(String::as_str);
        match (self.data_key(), t) {
            (Some(d), Some(t)) => Some(if d <= t { d } else { t }),
            (d, t) => d.or(t),
        }
    }

    /// Advance past `key`, handing its rows to `emit` when given. `true` when
    /// this layer knows the key (rows or a tombstone).
    fn take(
        &mut self,
        key: &str,
        mut emit: Option<&mut dyn FnMut(RecordBatch) -> Result<()>>,
    ) -> Result<bool> {
        let mut had_rows = false;
        while self.data_key() == Some(key) {
            let b = self.batch.clone().expect("batch");
            let k = key_column(&b)?;
            let mut end = self.row;
            while end < b.num_rows() && k.value(end) == key {
                end += 1;
            }
            if let Some(e) = emit.as_mut() {
                e(b.slice(self.row, end - self.row))?;
            }
            had_rows = true;
            self.row = end;
            self.load()?;
        }
        let removed = self.tombs.get(self.tomb).is_some_and(|t| t == key);
        if removed {
            self.tomb += 1;
        }
        Ok(had_rows || removed)
    }
}

#[allow(dead_code)]
fn _assert_send_sync() {
    fn is<T: Send + Sync>() {}
    is::<FeedArchive>();
    is::<FeedStack>();
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::UInt32Array;

    fn schema() -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("key", DataType::Utf8, false),
            Field::new("id", DataType::Utf8, false),
            Field::new("n", DataType::UInt32, false),
        ]))
    }

    /// Rows `(key, id, n)` → one batch.
    fn batch(rows: &[(&str, &str, u32)]) -> RecordBatch {
        RecordBatch::try_new(
            schema(),
            vec![
                Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.0))),
                Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.1))),
                Arc::new(UInt32Array::from_iter_values(rows.iter().map(|r| r.2))),
            ],
        )
        .unwrap()
    }

    fn sec(b: &RecordBatch, i: usize, out: &mut Vec<String>) {
        let id = b.column(1).as_any().downcast_ref::<StringArray>().unwrap();
        out.push(id.value(i).to_string());
    }

    fn ids(b: &RecordBatch) -> Vec<String> {
        let id = b.column(1).as_any().downcast_ref::<StringArray>().unwrap();
        (0..id.len()).map(|i| id.value(i).to_string()).collect()
    }

    /// A base with many small frames: `n` keys per group, 3 rows each.
    fn build_base(dir: &Path, n: usize, frame_bytes: usize) -> PathBuf {
        let p = dir.join("base.znippy");
        let opts = FeedOptions { frame_bytes, ..FeedOptions::base("advisory", 27, 1, "rev-1") };
        let mut w = FeedWriter::create(&p, schema(), opts).unwrap();
        for g in ["cargo", "npm"] {
            let keys: Vec<String> = (0..n).map(|i| format!("pkg-{i:05}")).collect();
            let ids: Vec<Vec<String>> =
                (0..n).map(|i| (0..3).map(|j| format!("CVE-{g}-{i}-{j}")).collect()).collect();
            let mut rows: Vec<(&str, &str, u32)> = Vec::new();
            for i in 0..n {
                for j in 0..3 {
                    rows.push((&keys[i], &ids[i][j], j as u32));
                }
            }
            // Two calls, cut in the middle of a key's rows: a key may span calls.
            let b = batch(&rows);
            let cut = rows.len() / 2 + 1;
            w.add_rows(g, &b.slice(0, cut), &mut sec).unwrap();
            w.add_rows(g, &b.slice(cut, rows.len() - cut), &mut sec).unwrap();
        }
        let r = w.finish().unwrap();
        assert_eq!(r.keys, 2 * n as u64);
        assert_eq!(r.rows, 6 * n as u64);
        assert!(r.data_frames >= 4, "small frames give many frames: {r:?}");
        p
    }

    #[test]
    fn lookup_by_key_reads_whole_keys_from_one_frame() {
        let d = tempfile::tempdir().unwrap();
        let p = build_base(d.path(), 500, 1024);
        let a = FeedArchive::open(&p).unwrap();
        assert_eq!(a.header().groups, vec!["cargo".to_string(), "npm".to_string()]);
        assert_eq!(a.header().kind, FeedKind::Base);
        for i in [0usize, 1, 77, 250, 499] {
            let key = format!("pkg-{i:05}");
            match a.get("npm", &key).unwrap() {
                Hit::Rows(b) => assert_eq!(
                    ids(&b),
                    (0..3).map(|j| format!("CVE-npm-{i}-{j}")).collect::<Vec<_>>(),
                    "{key}"
                ),
                h => panic!("{key}: {h:?}"),
            }
        }
        assert!(matches!(a.get("npm", "pkg-00500").unwrap(), Hit::Absent));
        assert!(matches!(a.get("npm", "aaa").unwrap(), Hit::Absent), "before the first frame");
        assert!(matches!(a.get("npm", "pkg-00001x").unwrap(), Hit::Absent), "between keys");
        assert!(matches!(a.get("pypi", "pkg-00001").unwrap(), Hit::Absent), "unknown group");
        // Every data frame holds whole keys: no key starts two frames.
        let frames = a.data_frames("npm");
        assert!(frames.len() > 2);
        for f in &frames {
            let b = a.read_frame(f).unwrap();
            assert_eq!(b.num_rows() % 3, 0, "{f} cut a key");
        }
    }

    #[test]
    fn lookup_by_secondary_key() {
        let d = tempfile::tempdir().unwrap();
        let p = build_base(d.path(), 300, 1024);
        let a = FeedArchive::open(&p).unwrap();
        assert_eq!(
            a.secondary("CVE-cargo-123-2").unwrap(),
            vec![("cargo".to_string(), "pkg-00123".to_string())]
        );
        assert!(a.secondary("CVE-nope").unwrap().is_empty());
        assert!(a.secondary("").unwrap().is_empty());
    }

    #[test]
    fn unsorted_rows_and_repeated_groups_are_refused() {
        let d = tempfile::tempdir().unwrap();
        let mut w = FeedWriter::create(&d.path().join("x.znippy"), schema(), FeedOptions::base("advisory", 27, 1, "r")).unwrap();
        assert!(w.add_rows("npm", &batch(&[("b", "1", 0), ("a", "2", 0)]), &mut sec).is_err());
        let mut w = FeedWriter::create(&d.path().join("y.znippy"), schema(), FeedOptions::base("advisory", 27, 1, "r")).unwrap();
        w.add_rows("npm", &batch(&[("a", "1", 0)]), &mut sec).unwrap();
        w.add_rows("pypi", &batch(&[("a", "1", 0)]), &mut sec).unwrap();
        assert!(w.add_rows("npm", &batch(&[("z", "1", 0)]), &mut sec).is_err());
        assert!(w.tombstone("npm", "q").is_err(), "a base has no tombstones");
    }

    #[test]
    fn delta_stacking_newest_wins_and_compaction_folds_it() {
        let d = tempfile::tempdir().unwrap();
        let base = build_base(d.path(), 200, 1024);
        // gen 2: change npm pkg-00010, remove npm pkg-00020, add npm pkg-zzz.
        let d2 = d.path().join("d2.znippy");
        let mut w = FeedWriter::create(&d2, schema(), FeedOptions::delta("advisory", 27, 1, 2, "rev-2")).unwrap();
        w.add_rows("npm", &batch(&[("pkg-00010", "CVE-NEW-10", 9)]), &mut sec).unwrap();
        w.tombstone("npm", "pkg-00020").unwrap();
        w.add_rows("npm", &batch(&[("pkg-zzz", "CVE-ZZZ", 1)]), &mut sec).unwrap();
        w.finish().unwrap();
        // gen 3: change it again, and bring pkg-00020 back.
        let d3 = d.path().join("d3.znippy");
        let mut w = FeedWriter::create(&d3, schema(), FeedOptions::delta("advisory", 27, 2, 3, "rev-3")).unwrap();
        w.add_rows("npm", &batch(&[("pkg-00010", "CVE-NEWER-10", 9)]), &mut sec).unwrap();
        w.add_rows("npm", &batch(&[("pkg-00020", "CVE-BACK-20", 1)]), &mut sec).unwrap();
        w.tombstone("cargo", "pkg-00005").unwrap();
        w.finish().unwrap();

        let only2 = FeedStack::open(&base, &[d2.clone()]).unwrap();
        assert_eq!(ids(&only2.get("npm", "pkg-00010").unwrap().unwrap()), vec!["CVE-NEW-10"]);
        assert!(only2.get("npm", "pkg-00020").unwrap().is_none(), "tombstoned");
        assert_eq!(ids(&only2.get("npm", "pkg-zzz").unwrap().unwrap()), vec!["CVE-ZZZ"]);
        assert_eq!(ids(&only2.get("npm", "pkg-00011").unwrap().unwrap()).len(), 3, "untouched key falls through");

        // Deltas given out of order are sorted by generation.
        let st = FeedStack::open(&base, &[d3.clone(), d2.clone()]).unwrap();
        assert_eq!(st.top().generation, 3);
        assert_eq!(ids(&st.get("npm", "pkg-00010").unwrap().unwrap()), vec!["CVE-NEWER-10"]);
        assert_eq!(ids(&st.get("npm", "pkg-00020").unwrap().unwrap()), vec!["CVE-BACK-20"]);
        assert!(st.get("cargo", "pkg-00005").unwrap().is_none());
        let cands = st.secondary("CVE-NEWER-10").unwrap();
        assert_eq!(cands, vec![("npm".to_string(), "pkg-00010".to_string())]);

        // A gap in the chain is refused.
        assert!(FeedStack::open(&base, &[d3.clone()]).is_err());

        // Compaction = the effective view, as one base at generation 3.
        let c = d.path().join("c.znippy");
        let rep = st.compact(&c, "rev-3c", &mut sec).unwrap();
        assert_eq!(rep.keys, 400 + 1 - 1, "{rep:?}");
        let cs = FeedStack::open(&c, &[]).unwrap();
        assert_eq!(cs.top().generation, 3);
        assert_eq!(cs.top().kind, FeedKind::Base);
        for (g, k) in [("npm", "pkg-00010"), ("npm", "pkg-00020"), ("npm", "pkg-zzz"), ("npm", "pkg-00199"), ("cargo", "pkg-00005"), ("cargo", "pkg-00006")] {
            let a = st.get(g, k).unwrap().map(|b| ids(&b));
            let b = cs.get(g, k).unwrap().map(|b| ids(&b));
            assert_eq!(a, b, "{g}/{k}");
        }
        assert_eq!(cs.secondary("CVE-NEW-10").unwrap(), vec![], "stale secondary rows are gone after compaction");
    }

    /// A key bigger than a frame is split into continuation frames; its
    /// neighbours (incl. keys it is a prefix of) still resolve, and a
    /// compaction carries every row.
    #[test]
    fn a_huge_key_is_split_into_continuation_frames() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("h.znippy");
        let opts = FeedOptions { frame_bytes: 512, ..FeedOptions::base("advisory", 27, 1, "r") };
        let mut w = FeedWriter::create(&p, schema(), opts).unwrap();
        let big: Vec<String> = (0..2000).map(|i| format!("CVE-BIG-{i:05}")).collect();
        let mut rows: Vec<(&str, &str, u32)> = vec![("lia", "CVE-A", 0)];
        rows.extend(big.iter().map(|id| ("lib", id.as_str(), 1)));
        rows.extend([("lib-x", "CVE-X", 2), ("lib2", "CVE-2", 3), ("libz", "CVE-Z", 4)]);
        w.add_rows("deb", &batch(&rows), &mut sec).unwrap();
        w.finish().unwrap();
        let a = FeedArchive::open(&p).unwrap();
        let conts = a.data_frames("deb").iter().filter(|f| f.contains(CONT)).count();
        assert!(conts > 10, "the big key spans many frames: {conts}");
        let mut n = 0usize;
        let mut streamed = Vec::new();
        assert_eq!(a.visit("deb", "lib", &mut |b| { n += 1; streamed.extend(ids(&b)); Ok(()) }).unwrap(), Found::Rows);
        assert!(n > 10);
        assert_eq!(streamed, big);
        for (k, id) in [("lia", "CVE-A"), ("lib-x", "CVE-X"), ("lib2", "CVE-2"), ("libz", "CVE-Z")] {
            match a.get("deb", k).unwrap() {
                Hit::Rows(b) => assert_eq!(ids(&b), vec![id.to_string()], "{k}"),
                h => panic!("{k}: {h:?}"),
            }
        }
        assert!(matches!(a.get("deb", "lib1").unwrap(), Hit::Absent));
        let st = FeedStack::open(&p, &[]).unwrap();
        let c = d.path().join("hc.znippy");
        let rep = st.compact(&c, "rc", &mut sec).unwrap();
        assert_eq!(rep.rows, 2004);
        assert_eq!(ids(&FeedStack::open(&c, &[]).unwrap().get("deb", "lib").unwrap().unwrap()), big);
        // The reserved byte cannot be in a key.
        let mut w = FeedWriter::create(&d.path().join("bad.znippy"), schema(), FeedOptions::base("advisory", 27, 1, "r")).unwrap();
        assert!(w.add_rows("deb", &batch(&[("a\u{1}b", "x", 0)]), &mut sec).is_err());
    }

    #[test]
    fn group_names_are_escaped_in_paths() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("g.znippy");
        let mut w = FeedWriter::create(&p, schema(), FeedOptions::base("advisory", 27, 1, "r")).unwrap();
        w.add_rows("Alpine/v3,20%", &batch(&[("a/b", "1", 0)]), &mut sec).unwrap();
        w.finish().unwrap();
        let a = FeedArchive::open(&p).unwrap();
        assert_eq!(a.header().groups, vec!["Alpine/v3,20%".to_string()]);
        assert!(matches!(a.get("Alpine/v3,20%", "a/b").unwrap(), Hit::Rows(_)));
    }

    #[test]
    fn feed_handler_reports_the_frame_index() {
        use crate::plugin::{ArchiveTypePlugin, ExtensionValue};
        let d = tempfile::tempdir().unwrap();
        let p = build_base(d.path(), 50, 512);
        let a = FeedArchive::open(&p).unwrap();
        let f = a.data_frames("cargo")[1].clone();
        let bytes = a.reader.read_file(&f).unwrap();
        let row = crate::plugins::native::feed_native::AdvisoryFeedPlugin.extract_metadata(&f, &bytes).unwrap();
        assert_eq!(row.fields["section"], ExtensionValue::Str("data".into()));
        assert_eq!(row.fields["group"], ExtensionValue::Str("cargo".into()));
        assert_eq!(format!("k/cargo/{}", match &row.fields["first_key"] { ExtensionValue::Str(s) => s.clone(), _ => unreachable!() }), f);
        // The data sub-index carries the feed columns (what `znippy list` shows).
        let entries = crate::index::read_znippy_manifest(&p).unwrap();
        assert!(entries.iter().any(|e| e.pkg_type == 27 && e.repo == "cargo" && e.module_name == "advisory"));
        let (schema, _) = crate::index::read_znippy_index(&p).unwrap();
        assert!(schema.field_with_name("first_key").is_ok(), "{schema:?}");
    }

    #[cfg(feature = "sign")]
    #[test]
    fn signed_feed_verifies_and_a_tampered_frame_is_refused() {
        use crate::sign::{CertStore, dev};
        let d = tempfile::tempdir().unwrap();
        let (ca_key, ca_der) = dev::mint_ca("feed-test-ca").unwrap();
        let signer = dev::new_p256_signer(&ca_key, &ca_der, "intel-signer").unwrap();
        let p = d.path().join("s.znippy");
        let mut w = FeedWriter::create(&p, schema(), FeedOptions::base("advisory", 27, 7, "signed")).unwrap();
        w.add_rows("npm", &batch(&[("a", "CVE-1", 0), ("b", "CVE-2", 0)]), &mut sec).unwrap();
        w.finish_signed(Box::new(signer)).unwrap();
        let roots = CertStore::from_der_certs(&[ca_der.clone()]).unwrap();
        let (a, who) = FeedArchive::open_verified(&p, &roots).unwrap();
        assert_eq!(who.common_name(), "intel-signer");
        assert!(matches!(a.get("npm", "b").unwrap(), Hit::Rows(_)));
        // Root-only: no per-frame CMS.
        let sigs = crate::sign::read_archive_signatures(&p).unwrap().unwrap();
        assert!(sigs.artifacts.is_empty());

        // Another CA is not trusted.
        let (_k2, other) = dev::mint_ca("other").unwrap();
        assert!(FeedArchive::open_verified(&p, &CertStore::from_der_certs(&[other]).unwrap()).is_err());

        // Unsigned archive is refused by open_verified.
        let u = build_base(d.path(), 10, 512);
        assert!(FeedArchive::open_verified(&u, &roots).is_err());

        // Rename a frame in the index (bend the key index): the root no longer verifies.
        let mut bytes = std::fs::read(&p).unwrap();
        let needle = b"k/npm/a";
        let mut hit = 0;
        let mut i = 0;
        while i + needle.len() <= bytes.len() {
            if &bytes[i..i + needle.len()] == needle {
                bytes[i + needle.len() - 1] = b'0';
                hit += 1;
            }
            i += 1;
        }
        assert!(hit > 0);
        let t = d.path().join("t.znippy");
        std::fs::write(&t, &bytes).unwrap();
        assert!(FeedArchive::open_verified(&t, &roots).is_err(), "a renamed frame must fail verification");
    }
}