pigeonhole 1.3.2

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model.
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
//! The change feed (D310): the committed changes of some tables, in commit order, from the
//! writer, resumable by token.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use pigeonhole_engine::{CatalogEvent, FamilyId, FeedReader, FeedSpec, FeedStart, Next, TableId};
use pigeonhole_format::key::Kind;
use pigeonhole_format::manifest::Edit;
use pigeonhole_format::value::decode_value;

use crate::db::{Db, Snapshot};
use crate::table::TableCore;
use crate::{Error, ErrorCode, FamilyInfo, ReadTable, Result, Table, Value};

/// Table and family names by id, as the feed's changes carry them.
type Names = HashMap<(TableId, FamilyId), (Arc<str>, Arc<str>)>;

/// What a [`Change`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChangeKind {
    /// A value for one cell version ([`RowMutation::put`](crate::RowMutation::put) and its
    /// typed forms).
    Put,
    /// A merge operand, or an aggregate family's input
    /// ([`RowMutation::merge`](crate::RowMutation::merge), `incr`, `aggregate`).
    Merge,
    /// Deleted exactly the version at [`Change::timestamp`]
    /// ([`RowMutation::delete_cell`](crate::RowMutation::delete_cell)).
    DeleteCell,
    /// Deleted every version of the column at or below [`Change::timestamp`]
    /// ([`RowMutation::delete_column`](crate::RowMutation::delete_column)).
    DeleteColumn,
    /// Deleted every cell of the row in the family at or below [`Change::timestamp`]
    /// ([`RowMutation::delete_family`](crate::RowMutation::delete_family); a
    /// [`delete_row`](crate::RowMutation::delete_row) is one per family).
    DeleteFamily,
}

impl ChangeKind {
    pub(crate) fn of(kind: Kind) -> Self {
        match kind {
            Kind::Put => ChangeKind::Put,
            Kind::Merge => ChangeKind::Merge,
            Kind::CellDelete => ChangeKind::DeleteCell,
            Kind::ColumnDelete => ChangeKind::DeleteColumn,
            Kind::FamilyDelete => ChangeKind::DeleteFamily,
        }
    }

    /// Whether it is one of the deletes (it has no value).
    pub fn is_delete(self) -> bool {
        matches!(
            self,
            ChangeKind::DeleteCell | ChangeKind::DeleteColumn | ChangeKind::DeleteFamily
        )
    }
}

/// One mutation of a delivered [`Commit`].
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
    table: Arc<str>,
    family: Arc<str>,
    kind: ChangeKind,
    ts: u64,
    row: Vec<u8>,
    qualifier: Vec<u8>,
    /// The stored value (its tag byte first); empty for deletes.
    stored: Vec<u8>,
    /// The engine's ids of its table and family (a replica applies by them, D315).
    ids: (TableId, FamilyId),
}

impl Change {
    /// The engine's ids of its table and family.
    #[cfg(feature = "__unstable-replication")]
    pub(crate) fn ids(&self) -> (TableId, FamilyId) {
        self.ids
    }

    /// The table's name. Empty only for a family created after the feed opened whose table
    /// was dropped before the feed reached this change: its name went with the table.
    pub fn table(&self) -> &str {
        &self.table
    }

    /// The family's name (empty in the same case as [`table`](Self::table)).
    pub fn family(&self) -> &str {
        &self.family
    }

    /// What it did.
    pub fn kind(&self) -> ChangeKind {
        self.kind
    }

    /// The row key.
    pub fn row(&self) -> &[u8] {
        &self.row
    }

    /// The qualifier (empty for [`ChangeKind::DeleteFamily`]).
    pub fn qualifier(&self) -> &[u8] {
        &self.qualifier
    }

    /// Its timestamp: the one the write gave, or else its commit's.
    pub fn timestamp(&self) -> u64 {
        self.ts
    }

    /// The value as the engine stored it, tag byte first (empty for the deletes): what a
    /// range move's target writes again with
    /// [`LoggedBatch::push`](crate::replication::LoggedBatch::push) (D331 PR 4). Not part of
    /// the stable API.
    #[cfg(feature = "__unstable-replication")]
    #[doc(hidden)]
    pub fn stored(&self) -> &[u8] {
        &self.stored
    }

    /// The value written or merged, as the read API types it; `None` for the deletes.
    pub fn value(&self) -> Option<Value<'_>> {
        if self.kind.is_delete() {
            return None;
        }
        // Checked when the commit was delivered (`fill`): a value that doesn't decode fails
        // `next` with `Corruption` instead of reaching here.
        decode_value(&self.stored)
            .ok()
            .map(crate::cell::typed_value)
    }
}

/// One whole commit: every change of it in the feed's tables and row prefix, never part of
/// one. Commits arrive once each, in commit order ([`Commit::seqno`]).
#[derive(Debug, Clone, PartialEq)]
pub struct Commit {
    seqno: u64,
    ts: u64,
    changes: Vec<Change>,
    /// A spanning commit's xid (D329 2b): [`xid`](Self::xid), and a replicated event's.
    pub(crate) xid: Option<std::sync::Arc<[u8]>>,
}

impl Commit {
    /// Its sequence number: the order commits arrive in, and what a [`Snapshot::seqno`]
    /// counts.
    pub fn seqno(&self) -> u64 {
        self.seqno
    }

    /// Its commit timestamp.
    pub fn timestamp(&self) -> u64 {
        self.ts
    }

    /// The transaction it is a share of, when it's a spanning commit's (D329 2b, ICR 0140
    /// amendment 2): every share of one commit, on every partition, carries the same, so a
    /// subscriber can group them. `None` for any other commit. Hidden, as
    /// [`Transaction::tag_xid`](crate::Transaction::tag_xid).
    #[cfg(feature = "__unstable-txn-prepare")]
    #[doc(hidden)]
    pub fn xid(&self) -> Option<&[u8]> {
        self.xid.as_deref()
    }

    /// Its changes the feed follows, in the order the commit wrote them.
    pub fn changes(&self) -> &[Change] {
        &self.changes
    }
}

impl Commit {
    /// A commit with nothing in it yet: the buffer the next one is read into.
    fn empty() -> Self {
        Commit {
            seqno: 0,
            ts: 0,
            changes: Vec::new(),
            xid: None,
        }
    }
}

/// What a feed delivers ([`Feed::next_event`]): a commit, or in a feed of every table
/// ([`Pigeonhole::feed`](crate::Pigeonhole::feed)) a change to its tables too (D315), each
/// in its place in commit order.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FeedEvent {
    /// One whole commit, as [`Feed::next`] delivers it.
    Commit(Commit),
    /// Tables created or dropped, or families added: every commit before it saw the old
    /// tables, every commit after it the new ones.
    Catalog(CatalogChange),
    /// A range drop (D331), to a replica's follower only
    /// ([`include_silent`](Feed::include_silent)): apply it with
    /// [`Pigeonhole::apply_range_drop`](crate::Pigeonhole::apply_range_drop). Not part of
    /// the stable API.
    #[cfg(feature = "__unstable-replication")]
    #[doc(hidden)]
    RangeDrop(crate::replication::RangeDrop),
}

/// One change to the database's tables, as a feed of every table delivers it
/// ([`FeedEvent::Catalog`]): one or more edits that applied together.
#[derive(Debug, Clone, PartialEq)]
pub struct CatalogChange {
    seqno: u64,
    ts: u64,
    edits: Vec<CatalogEdit>,
    /// The change as the engine recorded it, with its ids and root sequence (a replica applies
    /// it, D315).
    raw: CatalogEvent,
}

impl CatalogChange {
    /// The change as the engine recorded it, with its ids.
    #[cfg(feature = "__unstable-replication")]
    pub(crate) fn raw(&self) -> &CatalogEvent {
        &self.raw
    }

    /// Where it falls in commit order: every commit with a lower [`Commit::seqno`] came
    /// before it, every commit at or above it comes after.
    pub fn seqno(&self) -> u64 {
        self.seqno
    }

    /// The timestamp floor when it applied: every commit before it that took the default
    /// timestamp has one at most this.
    pub fn timestamp(&self) -> u64 {
        self.ts
    }

    /// Its edits, in the order they applied.
    pub fn edits(&self) -> &[CatalogEdit] {
        &self.edits
    }
}

/// One edit of a [`CatalogChange`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum CatalogEdit {
    /// A table was created, with these families.
    #[non_exhaustive]
    TableCreated {
        /// Its name.
        table: String,
        /// Its families, with their options.
        families: Vec<FamilyInfo>,
    },
    /// A family was added to an existing table.
    #[non_exhaustive]
    FamilyAdded {
        /// The table's name.
        table: String,
        /// The family, with its options.
        family: FamilyInfo,
    },
    /// A table was dropped, with all its data.
    #[non_exhaustive]
    TableDropped {
        /// Its name.
        table: String,
    },
}

/// How far a feed has covered its history ([`Feed::position`]). Not part of the stable API.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FeedPosition {
    seqno: u64,
    catalog: u64,
}

impl FeedPosition {
    /// Every commit of the feed's tables at or below it is covered.
    pub fn seqno(&self) -> u64 {
        self.seqno
    }

    /// A feed of every table: every catalog change with a root sequence at or below it was
    /// delivered or passed over (0 for none, and in a feed of some tables).
    pub fn catalog_sequence(&self) -> u64 {
        self.catalog
    }

    /// Whether this position covers everything `other` does, both parts at least as large:
    /// the parts are independent, so positions aren't totally ordered.
    pub fn covers(&self, other: &FeedPosition) -> bool {
        self.seqno >= other.seqno && self.catalog >= other.catalog
    }
}

/// Where a [`Feed`] left off: [`FeedBuilder::resume`] continues after its last delivered
/// commit, in this or a later open of the database. Opaque bytes, to store with the work
/// the commits fed (`as_bytes`, `from_bytes`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FeedToken(Vec<u8>);

impl FeedToken {
    /// The token's bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// A token from bytes [`as_bytes`](Self::as_bytes) gave. Checked when a feed resumes
    /// from it: bytes from another database or not a token are `InvalidArgument`.
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        FeedToken(bytes.into())
    }
}

/// Builds a [`Feed`] ([`Table::feed`], or [`ReadTable::feed`] in a reader process).
#[derive(Debug)]
#[must_use = "a builder does nothing until `open`"]
pub struct FeedBuilder {
    db: Arc<Db>,
    tables: Vec<Arc<TableCore>>,
    /// Every table, including those created later ([`crate::Pigeonhole::feed`], D315).
    all: bool,
    prefix: Vec<u8>,
    durable: bool,
    start: FeedStart,
    /// The first refusal (a handle from another database), returned by `open`.
    error: Option<Error>,
}

impl FeedBuilder {
    pub(crate) fn new(core: &Arc<TableCore>) -> Self {
        FeedBuilder {
            db: Arc::clone(&core.db),
            tables: vec![Arc::clone(core)],
            all: false,
            prefix: Vec::new(),
            durable: true,
            start: FeedStart::Now,
            error: None,
        }
    }

    /// A feed of every table of `db` (D315, ICR 0114).
    pub(crate) fn all_tables(db: &Arc<Db>) -> Self {
        FeedBuilder {
            db: Arc::clone(db),
            tables: Vec::new(),
            all: true,
            prefix: Vec::new(),
            durable: true,
            start: FeedStart::Now,
            error: None,
        }
    }

    /// Follows `table` as well: one feed, the commits of all its tables in one order, each
    /// commit whole across them.
    pub fn table(self, table: &Table) -> Self {
        self.add(&table.core)
    }

    /// Follows `table` as well, in a reader process ([`table`](Self::table) for a
    /// [`ReadTable`]).
    pub fn read_table(self, table: &ReadTable) -> Self {
        self.add(&table.core)
    }

    fn add(mut self, core: &Arc<TableCore>) -> Self {
        if self.all {
            self.error.get_or_insert(Error::new(
                ErrorCode::InvalidArgument,
                format!(
                    "a feed of every table already follows table {:?}",
                    core.info.name
                ),
            ));
            return self;
        }
        if !Arc::ptr_eq(&self.db, &core.db) {
            self.error.get_or_insert(Error::new(
                ErrorCode::InvalidArgument,
                format!("table {:?} belongs to another database", core.info.name),
            ));
            return self;
        }
        if !self.tables.iter().any(|t| t.info.id == core.info.id) {
            self.tables.push(Arc::clone(core));
        }
        self
    }

    /// Only the changes to rows starting with `prefix`. A commit with none is passed over.
    pub fn prefix(mut self, prefix: &[u8]) -> Self {
        self.prefix = prefix.to_vec();
        self
    }

    /// Delivers a commit once it is visible to reads, not only once it is durable at its
    /// level (the default). Earlier, by up to a sync; but a power loss can undo a
    /// `Buffered` or `None` commit it delivered, and then the feed's next resume expires.
    pub fn visible(mut self) -> Self {
        self.durable = false;
        self
    }

    /// Starts after the commits `snapshot` sees: read the snapshot, then follow the feed,
    /// and nothing is missed or seen twice.
    pub fn from_snapshot(mut self, snapshot: &Snapshot) -> Self {
        if let Err(e) = self.db.check_snapshot(snapshot) {
            self.error.get_or_insert(e);
            return self;
        }
        // The snapshot itself, so a feed of every table knows which catalog changes it saw.
        self.start = FeedStart::Snapshot(snapshot.inner.clone());
        self
    }

    /// Starts with the oldest commit the database's feed history still holds
    /// ([`Options::change_feed`](crate::Options::change_feed)), across reopens too: from the
    /// oldest earlier open whose history every shard still keeps whole. Under load that
    /// history can be recycled before the feed reaches it, which expires the feed at once;
    /// [`from_snapshot`](Self::from_snapshot) is the way to start from a known state.
    pub fn from_oldest(mut self) -> Self {
        self.start = FeedStart::Oldest;
        self
    }

    /// Continues after the last commit a feed delivered before `token` was taken.
    pub fn resume(mut self, token: &FeedToken) -> Self {
        self.start = FeedStart::Token(token.0.clone());
        self
    }

    /// Subscribes. With none of `from_snapshot`, `from_oldest` and `resume`, the feed starts
    /// with the commits after this call; with several, the last one called wins.
    ///
    /// A table or snapshot from another database is `InvalidArgument`, as everywhere else,
    /// and a snapshot from before an automatic recovery is `SnapshotExpired`, as reading it
    /// would be.
    ///
    /// Fails with `InvalidArgument` if the database's change feed is off or doesn't follow
    /// one of the tables ([`Options::feed_tables`](crate::Options::feed_tables)), or if a
    /// token is not one of this database's. A feed of every table
    /// ([`Pigeonhole::feed`](crate::Pigeonhole::feed)) needs the change feed on for every
    /// table, with no `feed_tables` list. A start whose history is gone shows at the first
    /// [`Feed::next`], as `FeedExpired`.
    pub fn open(self) -> Result<Feed> {
        if let Some(e) = self.error {
            return Err(e);
        }
        let spec = FeedSpec {
            tables: self.tables.iter().map(|t| t.info.id).collect(),
            prefix: self.prefix,
            durable: self.durable,
            start: self.start,
        };
        let mut names = HashMap::new();
        for t in &self.tables {
            note_names(&mut names, &t.info);
        }
        let (mut reader, generation) = subscribe(&self.db, spec.clone())?;
        let reader_progress = Arc::new(AtomicU64::new(0));
        reader.set_progress(Arc::clone(&reader_progress));
        let start = stream_position(&reader);
        Ok(Feed {
            db: self.db,
            // Only ever resubscribed from its own token: the start isn't kept, so a snapshot
            // start doesn't stay pinned for the feed's life.
            spec: FeedSpec {
                start: FeedStart::Now,
                ..spec
            },
            reader,
            generation,
            out: Delivery {
                names,
                commit: Commit::empty(),
                event: None,
                oldest_retained: None,
                failed: None,
            },
            covered: pigeonhole_engine::FeedPosition::default(),
            span: (start, start),
            xid_out: false,
            progress: FeedProgress::attach(reader_progress),
            include_silent: false,
        })
    }
}

/// The table and family names of `info`, by id.
fn note_names(names: &mut Names, info: &pigeonhole_engine::TableInfo) {
    let table: Arc<str> = Arc::from(info.name.as_str());
    for f in &info.families {
        names
            .entry((info.id, f.id))
            .or_insert_with(|| (Arc::clone(&table), Arc::from(f.name.as_str())));
    }
}

/// Where a feed's stream is, as its token records it (D315 PR 3): every commit at or below
/// `seqno` delivered or passed over, and every catalog change through `catalog`. Two
/// deliveries of one feed chain when one's end is the next one's start, and a feed resumed
/// from a token taken after a delivery starts at that delivery's end.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct StreamPosition {
    pub(crate) seqno: u64,
    pub(crate) catalog: u64,
}

fn stream_position(reader: &FeedReader) -> StreamPosition {
    StreamPosition {
        seqno: reader.delivered(),
        catalog: reader.position().catalog,
    }
}

/// The engine's reader for `spec` on the current engine, and that engine's generation.
fn subscribe(db: &Db, spec: FeedSpec) -> Result<(FeedReader, u64)> {
    loop {
        let generation = db.generation();
        let reader = db.engine().feed(spec.clone())?;
        // A recovery's swap between the two loads: subscribe again on the new engine.
        if db.generation() == generation {
            return Ok((reader, generation));
        }
    }
}

/// A subscription to the committed changes of some tables ([`Table::feed`]): whole commits,
/// once each, in commit order, from the writer.
///
/// By default a commit arrives once it is durable at its level, so nothing delivered is
/// ever undone ([`FeedBuilder::visible`] for sooner). Take a [`token`](Self::token) after
/// handling a commit to continue there later, in this open or the next.
///
/// When the history a feed needs is gone, it expires: [`next`](Self::next) fails with
/// [`ErrorCode::FeedExpired`] from then on. That happens when retention
/// ([`Options::change_feed`](crate::Options::change_feed)) passed it, when the database
/// was opened since with the feed turned off, without these tables, or with another
/// explicit shard count (an open that mentions neither inherits them and keeps it), or when
/// a power loss took commits it delivered. Start again from a snapshot.
///
/// ```
/// use std::time::Duration;
/// use pigeonhole::{Family, FeedRetention, Options, Pigeonhole};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let options = Options::default().change_feed(FeedRetention::bytes(64 << 20));
/// let db = Pigeonhole::open(dir.join("app.phdb"), options)?;
/// let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
/// let mut feed = t.feed().open()?;
/// t.mutate(b"row").put("f", b"q", b"v").commit()?;
/// let commit = feed.next(Duration::from_secs(5))?.expect("the commit");
/// let change = &commit.changes()[0];
/// assert_eq!((change.row(), change.qualifier()), (&b"row"[..], &b"q"[..]));
/// let token = feed.token(); // store it with what the commit fed
/// drop(feed);
/// let mut feed = t.feed().resume(&token).open()?;
/// assert!(feed.try_next()?.is_none());
/// # drop(feed);
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Feed {
    db: Arc<Db>,
    spec: FeedSpec,
    reader: FeedReader,
    /// The engine generation `reader` reads (D265).
    generation: u64,
    /// What the last call delivered, the names that fill it, and how the feed ended.
    out: Delivery,
    /// The position covered by the readers before the current one (a recovery's or a writer
    /// restart's resubscribe starts the new one at the token's delivered seqno, which can
    /// be below it).
    covered: pigeonhole_engine::FeedPosition,
    /// The stream's position before and after the last delivery (D315 PR 3): a replica checks
    /// that the runs it applies chain, each starting where the last ended.
    span: (StreamPosition, StreamPosition),
    /// The commit last delivered carried an xid (D329 2b): the next delivery clears it. With
    /// none now and none before, a delivery's xid costs one test (#2076's feed shapes).
    xid_out: bool,
    /// Its position, published by the reader as it moves ([`Feed::progress`]).
    progress: FeedProgress,
    /// Feed-silent commits are delivered (D331: a replica's follower only), kept across a
    /// resubscribe.
    include_silent: bool,
}

/// Where a [`Feed`] is, readable from any thread ([`Feed::progress`], D316 A4, ICR 0116): a
/// cheap handle, cloned from the feed, that a metrics exporter keeps while the feed's own
/// thread reads it. `pigeonhole-otel`'s `Registration::watch_feed` reports
/// [`Pigeonhole::visible_seqno`](crate::Pigeonhole::visible_seqno) less
/// [`covered_seqno`](Self::covered_seqno) as the feed's lag.
#[derive(Debug, Clone)]
pub struct FeedProgress {
    covered: Arc<AtomicU64>,
    live: Arc<AtomicBool>,
}

impl FeedProgress {
    fn attach(covered: Arc<AtomicU64>) -> Self {
        Self {
            covered,
            live: Arc::new(AtomicBool::new(true)),
        }
    }

    /// How far the feed has covered its history, as a seqno: every commit at or below it
    /// is covered, delivered or passed over (it carried nothing for the feed's tables, or no
    /// record holds it) or before the feed's start. Catalog changes aren't included. It's
    /// the seqno part of the feed's position, kept current as the feed reads, even while it
    /// waits, so a feed that keeps up stays near [`Pigeonhole::visible_seqno`]. It never
    /// goes back, a resubscribe after a recovery included.
    ///
    /// [`Pigeonhole::visible_seqno`]: crate::Pigeonhole::visible_seqno
    pub fn covered_seqno(&self) -> u64 {
        self.covered.load(Ordering::Relaxed)
    }

    /// Whether the feed still exists: `false` once it was dropped. A feed that failed or
    /// expired but is still held stays live, and its position stops, so a lag measured from
    /// it grows until the feed is dropped (cli692 on #1523).
    pub fn is_live(&self) -> bool {
        self.live.load(Ordering::Relaxed)
    }
}

impl Drop for Feed {
    fn drop(&mut self) {
        self.progress.live.store(false, Ordering::Relaxed);
    }
}

/// The longest single wait handed to the engine; a longer `next` waits again.
const WAIT_SLICE: Duration = Duration::from_secs(3600);

impl Feed {
    /// The next commit, waiting up to `timeout` for one; `None` if none arrived in time. A
    /// feed of every table passes its catalog changes over ([`next_event`](Self::next_event)
    /// delivers them too).
    ///
    /// An error reading the feed ends it: every later call returns the same error, as an
    /// expired feed does, so no commit is ever skipped. A value that doesn't decode is
    /// `Corruption`; the feed's [`token`](Self::token) then points past that commit, so
    /// resuming from it skips the damaged one.
    pub fn next(&mut self, timeout: Duration) -> Result<Option<&Commit>> {
        Ok(self.wait(timeout, false)?.then_some(&self.out.commit))
    }

    /// The next commit if one is ready; `None` otherwise. Never waits. Errors end the feed
    /// as [`next`](Self::next)'s do.
    pub fn try_next(&mut self) -> Result<Option<&Commit>> {
        Ok(self.try_step(false)?.then_some(&self.out.commit))
    }

    /// The next commit, for an async caller (D310 PR 5a): `Poll::Ready` with it, or with an
    /// error as [`next`](Self::next) would end with (they end the feed the same way), and
    /// `Poll::Pending` until there is one, with `cx`'s waker registered so the task is woken,
    /// never spinning, when the frontier can move. A feed doesn't end on its own, so there is
    /// no `None`. It follows an automatic recovery as `next` does.
    ///
    /// The writer process only: in a reader process it is
    /// [`ErrorCode::Unsupported`]; call the blocking [`next`](Self::next) on a thread of its
    /// own (#1407). [`nonblocking::FeedStream`](crate::nonblocking::FeedStream) wraps this
    /// as a `Stream` of owned commits.
    pub fn poll_next(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<&Commit>> {
        self.poll_step(cx, false).map_ok(|()| &self.out.commit)
    }

    /// The next event, waiting up to `timeout` for one; `None` if none arrived in time: a
    /// commit, or in a feed of every table ([`Pigeonhole::feed`](crate::Pigeonhole::feed))
    /// a catalog change too (D315), each in its place in commit order. Errors end the feed as
    /// [`next`](Self::next)'s do, and the [`token`](Self::token) after an event resumes just
    /// past it.
    pub fn next_event(&mut self, timeout: Duration) -> Result<Option<&FeedEvent>> {
        Ok(if self.wait(timeout, true)? {
            self.out.event.as_ref()
        } else {
            None
        })
    }

    /// The next event if one is ready; `None` otherwise. Never waits. As
    /// [`next_event`](Self::next_event) otherwise.
    pub fn try_next_event(&mut self) -> Result<Option<&FeedEvent>> {
        Ok(if self.try_step(true)? {
            self.out.event.as_ref()
        } else {
            None
        })
    }

    /// The next event, for an async caller: [`poll_next`](Self::poll_next) for
    /// [`next_event`](Self::next_event). The writer process only, as `poll_next`.
    /// [`nonblocking::FeedEventStream`](crate::nonblocking::FeedEventStream) wraps it as a
    /// `Stream` of owned events.
    pub fn poll_next_event(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<&FeedEvent>> {
        use std::task::Poll;
        match self.poll_step(cx, true) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
            Poll::Ready(Ok(())) => match &self.out.event {
                Some(event) => Poll::Ready(Ok(event)),
                None => unreachable!("a delivered step leaves its event"),
            },
        }
    }

    /// Waits up to `timeout` for the next delivery into `self.out` (catalog changes too, if
    /// `events`): whether one arrived.
    fn wait(&mut self, timeout: Duration, events: bool) -> Result<bool> {
        self.check_failed()?;
        let deadline = Instant::now().checked_add(timeout);
        loop {
            self.follow_recovery()?;
            let left = deadline.map_or(WAIT_SLICE, |d| {
                d.saturating_duration_since(Instant::now()).min(WAIT_SLICE)
            });
            let next = match self.reader.wait(left) {
                Ok(next) => next,
                Err(e) => {
                    self.read_error(e)?;
                    continue;
                }
            };
            match step(&mut self.out, &self.db, self.generation, next, events)? {
                Step::Ready => {
                    self.note_delivery();
                    if self.drop_passed(events) {
                        continue;
                    }
                    return Ok(true);
                }
                // A catalog change a commits-only call passes over, or a superseded
                // reader's expiry: look again (the engine returns at once if more is ready).
                Step::Again => continue,
                Step::Pending => {}
            }
            // Out of time, unless a recovery's swap ended the old engine's wait early (look
            // again on the new one) or the wait was one slice of a longer one.
            let more = deadline.is_none_or(|d| Instant::now() < d);
            if !more {
                return Ok(false);
            }
        }
    }

    /// The next delivery into `self.out` if one is ready, as [`wait`](Self::wait) without
    /// waiting.
    fn try_step(&mut self, events: bool) -> Result<bool> {
        self.check_failed()?;
        loop {
            self.follow_recovery()?;
            let next = match self.reader.try_next() {
                Ok(next) => next,
                Err(e) => {
                    self.read_error(e)?;
                    continue;
                }
            };
            return match step(&mut self.out, &self.db, self.generation, next, events)? {
                Step::Ready => {
                    self.note_delivery();
                    if self.drop_passed(events) {
                        continue;
                    }
                    Ok(true)
                }
                Step::Again => continue,
                Step::Pending => Ok(false),
            };
        }
    }

    /// The next delivery into `self.out`, for an async caller, as [`wait`](Self::wait).
    fn poll_step(
        &mut self,
        cx: &mut std::task::Context<'_>,
        events: bool,
    ) -> std::task::Poll<Result<()>> {
        use std::task::Poll;
        if let Err(e) = self.check_failed() {
            return Poll::Ready(Err(e));
        }
        loop {
            if let Err(e) = self.follow_recovery() {
                return Poll::Ready(Err(e));
            }
            let next = match self.reader.poll_next(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Ok(next)) => next,
                // The old engine failing under a recovery's swap: follow it and look again.
                Poll::Ready(Err(_)) if swapped(&self.db, self.generation) => continue,
                // `Unsupported` in a reader process: not the feed's failure, so not kept.
                Poll::Ready(Err(e @ pigeonhole_engine::Error::Unsupported(_))) => {
                    return Poll::Ready(Err(e.into()));
                }
                Poll::Ready(Err(e)) => {
                    return Poll::Ready(Err(fail(&mut self.out.failed, e.into())));
                }
            };
            return match step(&mut self.out, &self.db, self.generation, next, events) {
                Ok(Step::Ready) => {
                    self.note_delivery();
                    if self.drop_passed(events) {
                        continue;
                    }
                    Poll::Ready(Ok(()))
                }
                Ok(Step::Again) => continue,
                // The engine's `poll_next` returns `Poll::Pending` instead.
                Ok(Step::Pending) => Poll::Pending,
                Err(e) => Poll::Ready(Err(e)),
            };
        }
    }

    /// An error from the engine's reader in a blocking call: `Ok` to look again, after a
    /// reader process's writer restarted (followed from the token) or under a recovery's swap
    /// (the old engine failing: follow the recovery); else the feed's failure, kept.
    fn read_error(&mut self, e: pigeonhole_engine::Error) -> Result<()> {
        if matches!(e, pigeonhole_engine::Error::SnapshotExpired) {
            return self.resubscribe();
        }
        if swapped(&self.db, self.generation) {
            return Ok(());
        }
        Err(fail(&mut self.out.failed, e.into()))
    }

    /// The last event [`next_event`](Self::next_event) (or its try and poll forms) delivered,
    /// as a replica applies it (D315 PR 3): its changes with the primary's ids, its position
    /// span, and the feed's token right after it. Call it before the feed's next call, which
    /// moves both. `None` before any event. Not part of the stable API.
    #[cfg(feature = "__unstable-replication")]
    #[doc(hidden)]
    pub fn replicated(&self) -> Option<crate::replication::ReplicatedEvent> {
        let event = self.out.event.as_ref()?;
        Some(crate::replication::ReplicatedEvent::new(
            event,
            self.span,
            self.token(),
            self.reader.silent(),
        ))
    }

    /// Delivers the primary's feed-silent commits too (D331, ICR 0141), each marked in
    /// [`replicated`](Self::replicated): for a replica's follower only, which applies them
    /// silent. [`FeedBuilder`](crate::FeedBuilder) has no such option, so a client's
    /// subscription never sees them. Not part of the stable API.
    #[cfg(feature = "__unstable-replication")]
    #[doc(hidden)]
    pub fn include_silent(&mut self) {
        self.include_silent = true;
        self.reader.include_silent();
    }

    /// The digest of the catalog at the feed's position, for a feed of every table (#1853
    /// part C2): a replica that applied everything this feed delivered has the same
    /// [`Pigeonhole::replication_catalog_digest`](crate::Pigeonhole::replication_catalog_digest).
    /// Not part of the stable API.
    #[cfg(feature = "__unstable-replication")]
    #[doc(hidden)]
    pub fn catalog_digest(&self) -> Option<u64> {
        self.reader.catalog_digest()
    }

    /// A delivery happened: the span from the last one's end to the stream's position now.
    /// D331: a range drop comes from the engine as an empty commit at its seqno, which the
    /// reader names ([`FeedReader::range_drop`](pigeonhole_engine::FeedReader::range_drop);
    /// only with `include_silent`). An event call gets it as [`FeedEvent::RangeDrop`]; a
    /// commits-only call passes it over (true).
    #[inline(always)]
    fn drop_passed(&mut self, events: bool) -> bool {
        // One flag for a commit (#2089's callgrind): only a feed that includes feed-silent
        // records gets a drop.
        if !self.include_silent || self.reader.range_drop().is_none() {
            return false;
        }
        self.drop_taken(events)
    }

    /// [`drop_passed`](Self::drop_passed) for a delivery that is a drop's.
    #[cold]
    #[inline(never)]
    fn drop_taken(&mut self, events: bool) -> bool {
        let Some(_drop) = self.reader.range_drop() else {
            return false;
        };
        // Only a commit can stand for a drop: a catalog change delivered after one leaves
        // the reader's drop behind it (feed1248 on #2089).
        if events && !matches!(self.out.event, Some(FeedEvent::Commit(_))) {
            return false;
        }
        if !events {
            return true;
        }
        #[cfg(feature = "__unstable-replication")]
        {
            self.out.event = Some(FeedEvent::RangeDrop(
                crate::replication::RangeDrop::from_engine(_drop),
            ));
            false
        }
        // Without the feature no feed includes feed-silent records, so none gets a drop.
        #[cfg(not(feature = "__unstable-replication"))]
        true
    }

    fn note_delivery(&mut self) {
        let after = stream_position(&self.reader);
        self.span = (self.span.1, after);
        // A spanning commit's xid (D329 2b), which the engine's reader keeps beside the
        // commit: into the commit just delivered, as an event or on its own.
        if self.xid_out || self.reader.xid().is_some() {
            self.deliver_xid();
        }
    }

    /// [`note_delivery`](Self::note_delivery)'s xid, out of line: only once a spanning
    /// commit's share has been delivered.
    #[cold]
    #[inline(never)]
    fn deliver_xid(&mut self) {
        let xid = self.reader.xid().cloned();
        self.xid_out = xid.is_some();
        match &mut self.out.event {
            Some(FeedEvent::Commit(c)) => c.xid = xid,
            // Not a commit: nothing carries an xid, and the commit buffer's (the last
            // commit's, which `fill` leaves) is cleared, so `xid_out` is set exactly when the
            // buffer holds one. Otherwise a reader replaced since that commit (a resubscribe,
            // its `xid()` none) would let the next plain commit skip this and go out with the
            // old xid (audit120's X1 on #2076).
            Some(_) => {
                self.out.commit.xid = None;
                self.xid_out = false;
            }
            None => self.out.commit.xid = xid,
        }
    }

    /// The error that ended the feed, again.
    fn check_failed(&self) -> Result<()> {
        match &self.out.failed {
            Some(e) => Err(e.clone()),
            None => Ok(()),
        }
    }

    /// A handle to the feed's position, for another thread (D316 A4, ICR 0116): it stays
    /// current as the feed reads, and reports [`is_live`](FeedProgress::is_live) `false`
    /// once the feed is dropped. Cheap: two `Arc` clones.
    pub fn progress(&self) -> FeedProgress {
        self.progress.clone()
    }

    /// Where the feed is: [`FeedBuilder::resume`] continues after the last commit delivered.
    pub fn token(&self) -> FeedToken {
        FeedToken(self.reader.token())
    }

    /// How far the feed has covered its history (ICR 0114 amendment), for a server that
    /// fans one feed out to many clients (`phdb serve`'s hubs): every commit of the feed's
    /// tables at or below [`FeedPosition::seqno`] was delivered or passed over, or precedes
    /// its start, including the seqnos no commit of its tables holds (it moves while only
    /// other tables are written). In a feed of every table, a catalog change was delivered
    /// or passed over iff its sequence is at most [`FeedPosition::catalog_sequence`]; the
    /// seqno says nothing about catalog changes. Neither part ever goes back. Not part of the
    /// stable API.
    #[doc(hidden)]
    pub fn position(&self) -> FeedPosition {
        let p = self.covered.join(self.reader.position());
        FeedPosition {
            seqno: p.seqno,
            catalog: p.catalog,
        }
    }

    /// Once the feed expired: the oldest commit seqno its history still holds, when known.
    pub fn oldest_retained(&self) -> Option<u64> {
        self.out.oldest_retained
    }

    /// `Closed` once the database closed. After an automatic recovery onto a new engine
    /// (D265, [`Options::auto_recover`](crate::Options::auto_recover)) it resumes on that
    /// engine from the feed's own token, which the new engine checks: a durable feed
    /// continues, and a visible one that delivered what the failure lost expires. One load
    /// otherwise.
    fn follow_recovery(&mut self) -> Result<()> {
        match self.db.check_generation(self.generation) {
            Ok(()) => return Ok(()),
            Err(e) if e.code() == ErrorCode::SnapshotExpired => {}
            Err(e) => return Err(e),
        }
        self.resubscribe()
    }

    /// Subscribes again from the feed's own token, on the current engine (after a recovery)
    /// or a fresh attachment (a reader process after its writer restarted, D310 PR 4): the
    /// engine checks the token, so a durable feed continues and a visible one that delivered
    /// what was lost expires.
    fn resubscribe(&mut self) -> Result<()> {
        let mut spec = self.spec.clone();
        spec.start = FeedStart::Token(self.reader.token());
        let (mut reader, generation) = subscribe(&self.db, spec)?;
        // Nothing of the spec lies undelivered between the token and the old reader's
        // position, so it stays covered.
        self.covered = self.covered.join(self.reader.position());
        reader.set_progress(Arc::clone(&self.progress.covered));
        if self.include_silent {
            reader.include_silent();
        }
        self.reader = reader;
        self.generation = generation;
        Ok(())
    }
}

/// What the last call delivered, and the names that fill it.
#[derive(Debug)]
struct Delivery {
    names: Names,
    /// The last commit [`Feed::next`] delivered, or the buffer the next is read into.
    commit: Commit,
    /// The last event [`Feed::next_event`] delivered. A commit's buffer comes back to
    /// `commit` for the next one.
    event: Option<FeedEvent>,
    /// The oldest seqno still held, from the last expiry ([`Feed::oldest_retained`]).
    oldest_retained: Option<u64>,
    /// The error that ended the feed, returned by every later call (simp724 on #1321): the
    /// reader had already moved past the commit it was delivering, so going on would skip
    /// it.
    failed: Option<Error>,
}

/// What one of the engine's answers comes to.
enum Step {
    /// Delivered into the [`Delivery`].
    Ready,
    /// Nothing for this call; ask the engine again at once.
    Again,
    /// Nothing ready.
    Pending,
}

/// `next` into `out`: catalog changes only if `events`, though their names are always
/// noted. An expiry is noted in `out` and returned; any other error is the feed's failure.
fn step(
    out: &mut Delivery,
    db: &Db,
    generation: u64,
    next: Next<'_>,
    events: bool,
) -> Result<Step> {
    // The last event's commit buffer, for this one.
    if let Some(FeedEvent::Commit(c)) = out.event.take() {
        out.commit = c;
    }
    match next {
        Next::Commit(c) => {
            if let Err(e) = fill(&mut out.commit, &mut out.names, db, c) {
                return Err(fail(&mut out.failed, e));
            }
            if events {
                let commit = std::mem::replace(&mut out.commit, Commit::empty());
                out.event = Some(FeedEvent::Commit(commit));
            }
            Ok(Step::Ready)
        }
        Next::Catalog(ev) => {
            let change = catalog_change(&mut out.names, ev);
            if !events {
                return Ok(Step::Again);
            }
            out.event = Some(FeedEvent::Catalog(change));
            Ok(Step::Ready)
        }
        // The old engine's reader, still waiting as a recovery swapped in a new engine,
        // reads the new session's records as outside its history: the new engine's reader
        // decides from the token instead (cli692's S2 on #1321).
        Next::Expired(_) if swapped(db, generation) => Ok(Step::Again),
        Next::Expired(e) => {
            out.oldest_retained = e.oldest_retained;
            Err(expired(e))
        }
        Next::Pending => Ok(Step::Pending),
    }
}

/// `ev` as the public [`CatalogChange`], noting the names of the families it adds and
/// forgetting those of the tables it drops. A `CreateTable` and the `PutFamily` edits of
/// its table are one [`CatalogEdit::TableCreated`].
fn catalog_change(names: &mut Names, ev: &CatalogEvent) -> CatalogChange {
    // Every table the edits name: created among them, or named by the event (the
    // writer's rule, D315 2b).
    let mut tables: HashMap<TableId, Arc<str>> = ev
        .names
        .iter()
        .map(|(t, n)| (*t, Arc::from(n.as_str())))
        .collect();
    // Where each table created here sits in `edits`.
    let mut created: HashMap<TableId, usize> = HashMap::new();
    let mut edits = Vec::with_capacity(ev.edits.len());
    for e in &ev.edits {
        match e {
            Edit::CreateTable { table, name } => {
                tables.insert(*table, Arc::from(name.as_str()));
                created.insert(*table, edits.len());
                edits.push(CatalogEdit::TableCreated {
                    table: name.clone(),
                    families: Vec::new(),
                });
            }
            Edit::PutFamily {
                table,
                family,
                name,
                options,
            } => {
                let table_name = tables.get(table).cloned().unwrap_or_else(|| Arc::from(""));
                names.insert(
                    (*table, *family),
                    (Arc::clone(&table_name), Arc::from(name.as_str())),
                );
                let info = FamilyInfo::from_parts(name, options);
                match created.get(table).and_then(|&i| edits.get_mut(i)) {
                    Some(CatalogEdit::TableCreated { families, .. }) => families.push(info),
                    _ => edits.push(CatalogEdit::FamilyAdded {
                        table: table_name.to_string(),
                        family: info,
                    }),
                }
            }
            Edit::DropTable { table } => {
                names.retain(|(t, _), _| t != table);
                created.remove(table);
                let name = tables
                    .get(table)
                    .map_or_else(String::new, |n| n.to_string());
                edits.push(CatalogEdit::TableDropped { table: name });
            }
            // The writer stages only the three above (D315).
            _ => {}
        }
    }
    CatalogChange {
        seqno: ev.seqno_ceiling,
        ts: ev.timestamp,
        edits,
        raw: ev.clone(),
    }
}

/// `c` into `out`, with its tables' and families' names.
fn fill(out: &mut Commit, names: &mut Names, db: &Db, c: &pigeonhole_engine::Commit) -> Result<()> {
    out.seqno = c.seqno;
    out.ts = c.ts;
    // The commit's `Change`s are reused: their buffers keep their capacity across commits.
    out.changes.truncate(c.changes.len());
    for (i, ch) in c.changes.iter().enumerate() {
        let key = (ch.table, ch.family);
        if !names.contains_key(&key) {
            // A family created after the feed opened.
            if let Some(info) = db.engine().table_by_id(ch.table) {
                note_names(names, &info);
            }
        }
        // Unnamed only if the family was created after the feed opened and its table was
        // dropped before the feed reached this commit: the names went with the table.
        let (table, family) = names
            .get(&key)
            .cloned()
            .unwrap_or_else(|| (Arc::from(""), Arc::from("")));
        let kind = ChangeKind::of(ch.kind);
        // Admission decoded every value before it was logged; one that doesn't decode now is
        // damage, never an empty value (simp724 on #1321).
        if !kind.is_delete()
            && let Err(e) = decode_value(&ch.value)
        {
            out.changes.clear();
            return Err(Error::new(
                ErrorCode::Corruption,
                format!(
                    "a change feed value at seqno {} doesn't decode: {e}",
                    c.seqno
                ),
            ));
        }
        if let Some(slot) = out.changes.get_mut(i) {
            slot.table = table;
            slot.family = family;
            slot.ids = key;
            slot.kind = kind;
            slot.ts = ch.ts;
            for (to, from) in [
                (&mut slot.row, &ch.row),
                (&mut slot.qualifier, &ch.qualifier),
                (&mut slot.stored, &ch.value),
            ] {
                to.clear();
                to.extend_from_slice(from);
            }
        } else {
            out.changes.push(Change {
                table,
                family,
                kind,
                ts: ch.ts,
                row: ch.row.clone(),
                qualifier: ch.qualifier.clone(),
                stored: ch.value.clone(),
                ids: key,
            });
        }
    }
    Ok(())
}

/// Whether the engine of `generation` was replaced by a recovery (or the database closed)
/// since the feed's reader subscribed: an error from that reader then is the old engine's,
/// not the feed's (simp724 on #1321), and `Feed::follow_recovery` decides what follows.
fn swapped(db: &Db, generation: u64) -> bool {
    db.check_generation(generation).is_err()
}

/// Ends the feed with `e`: kept for every later call, and returned now.
fn fail(failed: &mut Option<Error>, e: Error) -> Error {
    failed.get_or_insert(e).clone()
}

fn expired(e: &pigeonhole_engine::Expiry) -> Error {
    Error::new(
        ErrorCode::FeedExpired,
        format!("the change feed expired: {}", e.reason),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Family, FeedRetention, Options, Pigeonhole};

    /// simp724 on #1321: a value that doesn't decode is `Corruption`, never an empty value,
    /// and it ends the feed: every later call returns it, so the damaged commit is never
    /// passed over.
    #[test]
    fn an_undecodable_value_fails_the_feed_for_good() {
        let dir = crate::doc_support::temp_dir();
        let db = Pigeonhole::open(
            dir.join("db.phdb"),
            Options::default().change_feed(FeedRetention::bytes(16 << 20)),
        )
        .unwrap();
        let t = db
            .table("t")
            .unwrap()
            .family("f", Family::default())
            .create_if_missing()
            .unwrap();
        let mut feed = t.feed().open().unwrap();
        let info = &t.core.info;
        let bad = pigeonhole_engine::Commit {
            seqno: 9,
            ts: 1,
            changes: vec![pigeonhole_engine::Change {
                table: info.id,
                family: info.families[0].id,
                kind: Kind::Put,
                ts: 1,
                row: b"r".to_vec(),
                qualifier: b"q".to_vec(),
                // A tag byte no build writes.
                value: vec![0xEE, 1, 2],
            }],
        };
        let e = fill(&mut feed.out.commit, &mut feed.out.names, &feed.db, &bad).unwrap_err();
        assert_eq!(e.code(), ErrorCode::Corruption, "{e}");
        assert!(feed.out.commit.changes.is_empty());
        // What `next` does with it: kept, and returned by every later call.
        let e = fail(&mut feed.out.failed, e);
        t.mutate(b"after").put("f", b"q", b"v").commit().unwrap();
        for _ in 0..2 {
            assert_eq!(feed.next(Duration::from_secs(5)).unwrap_err(), e);
            assert_eq!(feed.try_next().unwrap_err(), e);
        }
        drop(feed);
        db.close().unwrap();
    }

    /// audit120's X1 on #2076: a feed of every table delivers a spanning commit's share with
    /// its xid, then resubscribes (as after a recovery or its writer's restart: the new
    /// reader's `xid()` is none), then delivers a catalog change and a plain commit. The plain
    /// commit carries no xid, as an event and as a replica would apply it, so no replica
    /// logs it as a share of the earlier transaction.
    #[cfg(feature = "__unstable-txn-prepare")]
    #[test]
    fn a_plain_commit_after_a_resubscribe_and_a_catalog_change_carries_no_xid() {
        let dir = crate::doc_support::temp_dir();
        let db = Pigeonhole::open(
            dir.join("db.phdb"),
            Options::default().change_feed(FeedRetention::bytes(16 << 20)),
        )
        .unwrap();
        let t = db
            .table("t")
            .unwrap()
            .family("f", Family::default())
            .create_if_missing()
            .unwrap();
        let mut feed = db.feed().open().unwrap();
        let wait = Duration::from_secs(5);
        let next_commit = |feed: &mut Feed| loop {
            match feed.next_event(wait).unwrap().expect("an event") {
                FeedEvent::Commit(c) => return c.xid().map(<[u8]>::to_vec),
                _ => continue,
            }
        };
        let xid = b"p0:h1-0123456789abcdef0123456789abcdef";
        let mut txn = db.transaction().unwrap();
        txn.put(&t, b"share", "f", b"q", b"v");
        txn.tag_xid(xid);
        txn.commit().unwrap();
        assert_eq!(next_commit(&mut feed).as_deref(), Some(&xid[..]));
        feed.resubscribe().unwrap();
        assert!(
            feed.reader.xid().is_none(),
            "a fresh reader has delivered nothing"
        );
        db.table("u")
            .unwrap()
            .family("f", Family::default())
            .create_if_missing()
            .unwrap();
        assert!(
            matches!(feed.next_event(wait).unwrap(), Some(FeedEvent::Catalog(_))),
            "the table's creation"
        );
        t.mutate(b"plain").put("f", b"q", b"v").commit().unwrap();
        assert_eq!(
            next_commit(&mut feed),
            None,
            "the plain commit carries no xid"
        );
        #[cfg(feature = "__unstable-replication")]
        assert_eq!(
            feed.replicated().expect("the commit").xid(),
            None,
            "nor as a replica applies it"
        );
        // A later share still carries its own.
        let mut txn = db.transaction().unwrap();
        txn.put(&t, b"again", "f", b"q", b"v");
        txn.tag_xid(xid);
        txn.commit().unwrap();
        assert_eq!(next_commit(&mut feed).as_deref(), Some(&xid[..]));
        drop(feed);
        db.close().unwrap();
    }
}