chronix-engine 0.4.0

Storage engine for Chronix — WAL, memtable, columnar segments, indexes, compaction, and caches
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
//! Segment catalog with manifest persistence.
//!
//! The [`SegmentCatalog`] tracks metadata for all segments in the database,
//! organized by shard. Changes are logged to a manifest WAL for crash-safe
//! persistence, with periodic snapshots to bound recovery time.
//!
//! # Manifest format
//!
//! The manifest WAL uses a **length-prefixed postcard** binary format:
//! each entry is `[u32-le length][postcard payload]`. This provides:
//!
//! - **Fast serialization**: postcard is far faster than JSON and
//!   produces ~3x smaller output.
//! - **Crash-safe framing**: length prefix + CRC32c integrity check
//!   detects truncated or corrupt entries reliably.
//! - **Bounded replay**: binary parsing is O(entries), not O(bytes).
//!
//! Snapshots use the same postcard format (single blob).

use std::collections::{BTreeMap, HashMap};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use tracing::{debug, warn};

use crate::segment::stats::ColumnStats;
use chronix_core::{
    MeasurementSchema, SegmentId, SegmentState, ShardId, Timestamp, Tombstone, TombstoneSet,
};

use crate::index::error::{IndexError, Result};

/// Per-column statistics stored in the catalog for pruning.
///
/// Contains the column name, data type, and min/max statistics so the
/// pruning pipeline can eliminate segments without opening any file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CatalogColumnStats {
    /// Column name (e.g. "temperature", "host").
    pub name: String,
    /// Column data type tag (from `crate::segment::metadata::data_types`).
    pub data_type: u8,
    /// Column role tag (0= timestamp, 1= tag, 2= field).
    pub role: u8,
    /// Digits after the decimal point, for a decimal column; `None`
    /// otherwise.
    ///
    /// Here as well as in the segment because the schema repair at open
    /// works from *this* summary and never opens a `.csx` file: without the
    /// scale, a decimal column the manifest had lost could only be restored
    /// as some other type, which is worse than not restoring it.
    #[serde(default)]
    pub decimal_scale: Option<u8>,
    /// Min/max/null statistics.
    pub stats: ColumnStats,
}

/// Metadata for a single segment in the catalog.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SegmentCatalogEntry {
    /// Unique segment identifier.
    pub segment_id: SegmentId,
    /// The shard this segment belongs to.
    pub shard_id: ShardId,
    /// Measurement name this segment contains data for.
    pub measurement: String,
    /// Filesystem path to the `.csx` file.
    pub path: PathBuf,
    /// Minimum timestamp in the segment (inclusive).
    pub min_timestamp: Timestamp,
    /// Maximum timestamp in the segment (inclusive).
    pub max_timestamp: Timestamp,
    /// Total number of rows in the segment.
    pub row_count: u64,
    /// Number of unique series in the segment.
    pub series_count: u32,
    /// File size in bytes.
    pub byte_size: u64,
    /// Number of row groups.
    pub row_group_count: u32,
    /// Number of columns.
    pub column_count: u16,
    /// Per-column statistics for predicate pushdown pruning.
    #[serde(default)]
    pub column_stats: Vec<CatalogColumnStats>,
    /// Lifecycle state of this segment.
    #[serde(default)]
    pub state: SegmentState,
}

/// Manifest entry types for WAL-style persistence.
#[derive(Debug, Clone, Serialize, Deserialize)]
enum ManifestEntry {
    /// A segment was added.
    AddSegment(SegmentCatalogEntry),
    /// A segment was removed.
    RemoveSegment(u64),
    /// A schema was registered or updated.
    SetSchema(MeasurementSchema),
    /// A schema was removed.
    RemoveSchema(String),
    /// A tombstone was recorded by a delete.
    AddTombstone(Tombstone),
    /// A tombstone was reclaimed — every segment it was issued against is gone.
    RemoveTombstone(Tombstone),
    /// Every WAL record with a sequence number at or below this is in a
    /// segment. Replay starts after it.
    SetWalFloor(u64),
    /// Compaction merged `inputs` into `output`: every tombstone that named
    /// an input now names the output too.
    Compacted {
        /// The input segment ids.
        inputs: Vec<u64>,
        /// The output segment id.
        output: u64,
    },
    /// A rollup definition was created or replaced. The payload is the
    /// facade's `RollupConfig`, opaque here — the catalog persists it, the
    /// facade interprets it.
    SetRollup {
        /// The rollup's name, its identity.
        name: String,
        /// Postcard-encoded definition.
        definition: Vec<u8>,
    },
    /// A rollup definition was deleted.
    RemoveRollup(String),
    /// A rollup's materialisation state changed: its watermark advanced, or
    /// a write below the watermark invalidated some of its buckets.
    SetRollupState {
        /// The rollup's name.
        name: String,
        /// Postcard-encoded state.
        state: Vec<u8>,
    },
    /// A measurement was soft-deleted: it is pending a hard delete at
    /// `deadline_ms` unless cancelled first.
    ///
    /// Durable for the same reason a tombstone is: an in-memory-only
    /// pending-drop map is undone by every restart, silently un-dropping a
    /// measurement an operator was told was gone and forgetting the deadline
    /// that was supposed to reclaim its disk.
    SetPendingMeasurementDrop {
        /// The measurement pending deletion.
        measurement: String,
        /// Unix-ms deadline after which the next GC pass hard-deletes it.
        deadline_ms: u64,
    },
    /// A pending drop was cancelled — by a restore, or by the hard delete
    /// that finally acted on it.
    CancelPendingMeasurementDrop(String),
}

/// A rollup's persisted definition and state, as opaque payloads.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RollupRecord {
    /// Postcard-encoded definition, absent while only state is known.
    #[serde(default)]
    pub definition: Vec<u8>,
    /// Postcard-encoded materialisation state.
    #[serde(default)]
    pub state: Vec<u8>,
}

/// Segment metadata catalog with manifest persistence.
///
/// Tracks all segment metadata organized by shard, along with measurement
/// schemas. Changes are persisted to a manifest WAL file, with periodic
/// snapshots to prevent unbounded manifest growth.
///
/// # Persistence
///
/// Changes are appended to `manifest.wal` as length-prefixed, CRC-32C
/// framed postcard entries.
/// Periodic snapshots written to `manifest.snapshot.bin`.
/// On startup: load latest snapshot, replay WAL entries.
///
/// # Concurrency
///
/// The catalog currently uses a single `&mut self` borrow (i.e. external
/// synchronisation via an `RwLock` or `Mutex`) for all shards.  This is
/// acceptable because catalog mutations (segment add/remove, schema
/// updates) are infrequent (flush/compaction cadence) and short-lived.
///
/// If catalog contention ever becomes measurable under very high shard
/// counts, the internal `BTreeMap<ShardId, Vec<…>>` can be replaced with
/// a `DashMap<ShardId, Vec<…>>` to allow per-shard concurrent access
/// without changing the external API.
#[derive(Debug)]
pub struct SegmentCatalog {
    /// Segments organized by shard.
    segments: BTreeMap<ShardId, Vec<SegmentCatalogEntry>>,
    /// Measurement schemas.
    schemas: HashMap<String, MeasurementSchema>,
    /// Tombstones recorded by deletes.
    ///
    /// These live in the catalog rather than in the data WAL, and that is the
    /// fix for a delete that did not survive a restart. The data WAL is
    /// truncated once the memtable it covers has been flushed, so a delete
    /// logged before a flush was discarded by it — the tombstone existed only
    /// in memory from then on, and the deleted rows came back at the next
    /// open. The manifest is only ever rewritten by a snapshot that carries
    /// its full contents forward.
    tombstones: TombstoneSet,
    /// The WAL floor: every data-WAL record with `sequence_no <= wal_floor`
    /// has been flushed into a segment that this catalog registers.
    ///
    /// Recorded here rather than inferred from the WAL files, because the
    /// active WAL file is never deleted by truncation. Without a floor every
    /// restart replayed that file — up to 32 MB of already-flushed points —
    /// into the memtable, and the next flush wrote them to disk a second
    /// time. Dedup hid the duplicates from queries; the flash wear was real.
    wal_floor: u64,
    /// Rollup definitions and state, persisted with everything else that
    /// a restart must not lose. They used to live in a hand-written JSON
    /// file beside the data directory with no fsync and no CRC, and a
    /// failure to parse it was logged and swallowed — leaving a database
    /// that believed it had no rollups, and a retention pass that then
    /// dropped the raw data those rollups existed to preserve.
    rollups: BTreeMap<String, RollupRecord>,
    /// Measurements pending a hard delete, by the unix-ms deadline a GC pass
    /// acts on. See [`ManifestEntry::SetPendingMeasurementDrop`].
    pending_measurement_drops: BTreeMap<String, u64>,
    /// Monotonically increasing catalog version.
    manifest_seq: u64,
    /// Directory for manifest files.
    manifest_dir: PathBuf,
    /// Number of changes since last snapshot.
    changes_since_snapshot: u64,
    /// Next segment ID to assign.
    next_segment_id: u64,
    /// Persistent WAL file handle (kept open for append).
    manifest_wal_file: Option<std::fs::File>,
    /// Number of appends written but not yet `sync_data()`d.
    ///
    /// Normally at most one: every append syncs. It grows only inside
    /// [`in_one_sync`](Self::in_one_sync).
    pending_sync: u64,
    /// Depth of the [`in_one_sync`](Self::in_one_sync) nesting.
    ///
    /// Non-zero means "this transition is not finished; do not fsync yet".
    defer_sync: u32,
    /// How many times the manifest has actually been fsynced.
    ///
    /// Exported as `chronix_catalog_fsync_total`, beside the WAL's own
    /// counter: on flash-backed storage the fsync rate *is* the wear rate,
    /// and the catalog was paying one per row of bookkeeping. It is also what
    /// makes the batching testable — a claim about a number of syscalls that
    /// nothing counts is a claim that rots.
    manifest_syncs: u64,
}

/// Snapshot interval: take a snapshot every N changes.
const SNAPSHOT_INTERVAL: u64 = 1000;

/// Sync on **every** manifest append, so no catalog mutation is lost to a
/// power failure.
///
/// A single mutation — registering a segment, updating a schema — is
/// infrequent enough that its fsync is free. What is not free is a mutation
/// made of *many* appends: a compaction of four segments is six, and a delete
/// producing a hundred tombstones is a hundred. Those are batched by
/// [`SegmentCatalog::in_one_sync`], which is where the count belongs — a
/// global batch size would defer the appends nobody is going to sync.
const SYNC_BATCH_SIZE: u64 = 1;

// Compile-time guarantee: SegmentCatalog is safe to share across threads.
const _: () = {
    const fn _assert_send<T: Send + Sync>() {}
    _assert_send::<SegmentCatalog>();
};

impl SegmentCatalog {
    /// Create a new empty catalog persisted in `manifest_dir`.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest directory cannot be created.
    pub fn new(manifest_dir: impl Into<PathBuf>) -> Result<Self> {
        let manifest_dir = manifest_dir.into();
        std::fs::create_dir_all(&manifest_dir)?;

        Ok(Self {
            segments: BTreeMap::new(),
            schemas: HashMap::new(),
            tombstones: TombstoneSet::new(),
            wal_floor: 0,
            rollups: BTreeMap::new(),
            pending_measurement_drops: BTreeMap::new(),
            manifest_seq: 0,
            manifest_dir,
            changes_since_snapshot: 0,
            next_segment_id: 1,
            manifest_wal_file: None,
            pending_sync: 0,
            defer_sync: 0,
            manifest_syncs: 0,
        })
    }

    /// Open an existing catalog, loading from snapshot + replaying manifest WAL.
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot or manifest cannot be read/parsed.
    pub fn open(manifest_dir: impl Into<PathBuf>) -> Result<Self> {
        let manifest_dir = manifest_dir.into();
        std::fs::create_dir_all(&manifest_dir)?;

        let bin_snapshot_path = manifest_dir.join("manifest.snapshot.bin");
        let mut catalog = if bin_snapshot_path.exists() {
            let data = std::fs::read(&bin_snapshot_path)?;
            let snapshot: CatalogSnapshot = postcard::from_bytes(&data)
                .map_err(|e| IndexError::BinarySerialization(e.to_string()))?;
            // Reject snapshots from future versions we can't parse.
            if snapshot.format_version > CATALOG_FORMAT_VERSION {
                return Err(IndexError::BinarySerialization(format!(
                    "catalog snapshot format version {} is newer than supported version {CATALOG_FORMAT_VERSION}",
                    snapshot.format_version
                )));
            }
            debug!(
                seq = snapshot.manifest_seq,
                segments = snapshot.segments.len(),
                format_version = snapshot.format_version,
                "loaded catalog snapshot (postcard)"
            );
            Self {
                segments: snapshot.segments,
                schemas: snapshot.schemas,
                tombstones: snapshot.tombstones,
                wal_floor: snapshot.wal_floor,
                rollups: snapshot.rollups,
                pending_measurement_drops: snapshot.pending_measurement_drops,
                manifest_seq: snapshot.manifest_seq,
                manifest_dir: manifest_dir.clone(),
                changes_since_snapshot: 0,
                next_segment_id: snapshot.next_segment_id,
                manifest_wal_file: None,
                pending_sync: 0,
                defer_sync: 0,
                manifest_syncs: 0,
            }
        } else {
            Self {
                segments: BTreeMap::new(),
                schemas: HashMap::new(),
                tombstones: TombstoneSet::new(),
                wal_floor: 0,
                rollups: BTreeMap::new(),
                pending_measurement_drops: BTreeMap::new(),
                manifest_seq: 0,
                manifest_dir: manifest_dir.clone(),
                changes_since_snapshot: 0,
                next_segment_id: 1,
                manifest_wal_file: None,
                pending_sync: 0,
                defer_sync: 0,
                manifest_syncs: 0,
            }
        };

        // Replay manifest WAL
        let wal_path = manifest_dir.join("manifest.wal");
        if wal_path.exists() {
            catalog.replay_manifest(&wal_path)?;
        }

        Ok(catalog)
    }

    /// Add a segment to the catalog.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn add_segment(&mut self, entry: SegmentCatalogEntry) -> Result<()> {
        let manifest_entry = ManifestEntry::AddSegment(entry.clone());
        self.append_manifest(&manifest_entry)?;

        self.segments.entry(entry.shard_id).or_default().push(entry);

        self.maybe_snapshot()?;
        Ok(())
    }

    /// Remove a segment from the catalog by its ID.
    ///
    /// Returns the removed entry if found.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn remove_segment(&mut self, segment_id: SegmentId) -> Result<Option<SegmentCatalogEntry>> {
        let manifest_entry = ManifestEntry::RemoveSegment(segment_id.0);
        self.append_manifest(&manifest_entry)?;

        for entries in self.segments.values_mut() {
            if let Some(pos) = entries.iter().position(|e| e.segment_id == segment_id) {
                let removed = entries.remove(pos);
                self.maybe_snapshot()?;
                return Ok(Some(removed));
            }
        }

        self.maybe_snapshot()?;
        Ok(None)
    }

    /// Get all segments for a specific shard.
    #[must_use]
    pub fn get_segments_for_shard(&self, shard_id: &ShardId) -> &[SegmentCatalogEntry] {
        self.segments.get(shard_id).map_or(&[], Vec::as_slice)
    }

    /// Mark a segment as soft-deleted.
    ///
    /// The segment remains in the catalog and is still queryable by code
    /// that explicitly opts in to soft-deleted segments — but the default
    /// query path (via `active_segments_for_measurement`) hides it.
    /// A subsequent call to `remove_segment` will hard-delete it.
    pub fn soft_delete_segment(&mut self, segment_id: SegmentId, now_ms: u64) -> Result<bool> {
        // Find which measurement key and entry index contains this segment.
        let location = self.segments.iter().find_map(|(measurement, entries)| {
            entries
                .iter()
                .position(|e| e.segment_id == segment_id)
                .map(|idx| (*measurement, idx))
        });

        let Some((measurement, idx)) = location else {
            return Ok(false);
        };

        // Persist FIRST, then mutate in-memory state.
        // If append_manifest fails, the in-memory state remains
        // unchanged and the segment stays Active.
        let entry = &self.segments[&measurement][idx];
        let mut updated_entry = entry.clone();
        updated_entry.state = SegmentState::SoftDeleted {
            deleted_at_ms: now_ms,
        };
        let manifest_entry = ManifestEntry::AddSegment(updated_entry);
        self.append_manifest(&manifest_entry)?;

        // Now safe to mutate in-memory state.
        if let Some(entries) = self.segments.get_mut(&measurement) {
            entries[idx].state = SegmentState::SoftDeleted {
                deleted_at_ms: now_ms,
            };
        }
        Ok(true)
    }

    /// Get all *active* segments belonging to a specific measurement.
    ///
    /// Excludes segments that are soft-deleted (waiting for GC), and every
    /// segment of a measurement pending a hard delete — a "drop" that leaves
    /// its rows scannable for the whole grace period is not a drop. The
    /// segments themselves are untouched, so a restore before the deadline
    /// costs nothing and loses nothing.
    #[must_use]
    pub fn active_segments_for_measurement(&self, measurement: &str) -> Vec<&SegmentCatalogEntry> {
        if self.pending_measurement_drops.contains_key(measurement) {
            return Vec::new();
        }
        self.segments
            .values()
            .flat_map(|v| v.iter())
            .filter(|e| e.measurement == measurement && e.state == SegmentState::Active)
            .collect()
    }

    /// Get segments that are past the soft-delete grace period and can
    /// be hard-deleted.
    #[must_use]
    pub fn expired_soft_deleted(
        &self,
        now_ms: u64,
        grace_period_ms: u64,
    ) -> Vec<&SegmentCatalogEntry> {
        self.segments
            .values()
            .flat_map(|v| v.iter())
            .filter(|e| {
                if let SegmentState::SoftDeleted { deleted_at_ms } = e.state {
                    now_ms.saturating_sub(deleted_at_ms) >= grace_period_ms
                } else {
                    false
                }
            })
            .collect()
    }

    /// Get all segments across all shards.
    #[must_use]
    pub fn all_segments(&self) -> Vec<&SegmentCatalogEntry> {
        self.segments.values().flat_map(|v| v.iter()).collect()
    }

    /// Get all segments belonging to a specific measurement.
    #[must_use]
    pub fn segments_for_measurement(&self, measurement: &str) -> Vec<&SegmentCatalogEntry> {
        self.segments
            .values()
            .flat_map(|v| v.iter())
            .filter(|e| e.measurement == measurement)
            .collect()
    }

    /// Get the total number of segments.
    /// The largest number of active segments any one `(shard, measurement)`
    /// holds — the count a compaction pass can actually reduce, and so the
    /// number write backpressure is keyed on.
    #[must_use]
    pub fn max_segments_per_shard_measurement(&self) -> usize {
        let mut counts: std::collections::HashMap<(i64, &str), usize> =
            std::collections::HashMap::new();
        for e in self.all_segments() {
            if e.state == chronix_core::SegmentState::Active {
                *counts
                    .entry((e.shard_id.0, e.measurement.as_str()))
                    .or_default() += 1;
            }
        }
        counts.into_values().max().unwrap_or(0)
    }

    /// Approximate heap bytes held by the catalog.
    ///
    /// One entry per segment, each carrying a measurement name, a path and its
    /// per-column statistics — so this grows with segment count, not with row
    /// count, and it is the term that a long-running gateway accumulates
    /// between compactions. The schema registry and the tombstone set are
    /// counted with it: all three live for the process's lifetime, which is
    /// what makes them worth a number rather than an estimate.
    #[must_use]
    pub fn memory_bytes(&self) -> usize {
        let entries: usize = self
            .segments
            .values()
            .map(|v| {
                v.capacity() * std::mem::size_of::<SegmentCatalogEntry>()
                    + v.iter()
                        .map(|e| {
                            e.measurement.capacity()
                                + e.path.as_os_str().len()
                                + e.column_stats.capacity()
                                    * std::mem::size_of::<CatalogColumnStats>()
                                + e.column_stats
                                    .iter()
                                    .map(|c| c.name.capacity())
                                    .sum::<usize>()
                        })
                        .sum::<usize>()
            })
            .sum();

        let schemas: usize = self
            .schemas
            .iter()
            .map(|(name, ms)| {
                name.capacity()
                    + ms.columns()
                        .iter()
                        .map(|c| c.name.capacity() + std::mem::size_of_val(c))
                        .sum::<usize>()
            })
            .sum();

        entries + schemas + self.tombstones.len() * std::mem::size_of::<u64>() * 4
    }

    /// Total number of segments the catalog holds, in any state.
    #[must_use]
    pub fn segment_count(&self) -> usize {
        self.segments.values().map(Vec::len).sum()
    }

    /// Allocate the next segment ID.
    pub fn next_segment_id(&mut self) -> SegmentId {
        let id = SegmentId(self.next_segment_id);
        self.next_segment_id += 1;
        id
    }

    /// Get the current manifest sequence number.
    #[must_use]
    pub fn manifest_seq(&self) -> u64 {
        self.manifest_seq
    }

    /// Every persisted rollup, by name.
    #[must_use]
    pub fn rollups(&self) -> &BTreeMap<String, RollupRecord> {
        &self.rollups
    }

    /// Persist a rollup definition, durably.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written or synced.
    pub fn set_rollup(&mut self, name: &str, definition: Vec<u8>) -> Result<()> {
        self.append_manifest(&ManifestEntry::SetRollup {
            name: name.to_string(),
            definition: definition.clone(),
        })?;
        self.rollups.entry(name.to_string()).or_default().definition = definition;
        self.sync_manifest()?;
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Persist a rollup's materialisation state, durably.
    ///
    /// Called after the rollup's points are durable, never before: a
    /// watermark that outlives the rows it claims is a permanent hole in
    /// the tier, because nothing recomputes a bucket the watermark has
    /// already passed.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written or synced.
    pub fn set_rollup_state(&mut self, name: &str, state: Vec<u8>) -> Result<()> {
        self.append_manifest(&ManifestEntry::SetRollupState {
            name: name.to_string(),
            state: state.clone(),
        })?;
        self.rollups.entry(name.to_string()).or_default().state = state;
        self.sync_manifest()?;
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Delete a rollup definition and its state.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn remove_rollup(&mut self, name: &str) -> Result<bool> {
        if !self.rollups.contains_key(name) {
            return Ok(false);
        }
        self.append_manifest(&ManifestEntry::RemoveRollup(name.to_string()))?;
        self.rollups.remove(name);
        self.sync_manifest()?;
        self.maybe_snapshot()?;
        Ok(true)
    }

    /// Every measurement pending a hard delete, and the unix-ms deadline
    /// each was given.
    #[must_use]
    pub fn pending_measurement_drops(&self) -> &BTreeMap<String, u64> {
        &self.pending_measurement_drops
    }

    /// Whether `measurement` is pending a hard delete.
    #[must_use]
    pub fn is_measurement_pending_drop(&self, measurement: &str) -> bool {
        self.pending_measurement_drops.contains_key(measurement)
    }

    /// Mark `measurement` pending a hard delete at `deadline_ms`, durably.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written or synced.
    pub fn set_measurement_pending_drop(
        &mut self,
        measurement: &str,
        deadline_ms: u64,
    ) -> Result<()> {
        self.append_manifest(&ManifestEntry::SetPendingMeasurementDrop {
            measurement: measurement.to_string(),
            deadline_ms,
        })?;
        self.pending_measurement_drops
            .insert(measurement.to_string(), deadline_ms);
        self.sync_manifest()?;
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Cancel a pending drop \u2014 a restore, or the hard delete that finally
    /// acted on it \u2014 durably.
    ///
    /// Returns whether `measurement` was pending.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written or synced.
    pub fn cancel_measurement_pending_drop(&mut self, measurement: &str) -> Result<bool> {
        if !self.pending_measurement_drops.contains_key(measurement) {
            return Ok(false);
        }
        self.append_manifest(&ManifestEntry::CancelPendingMeasurementDrop(
            measurement.to_string(),
        ))?;
        self.pending_measurement_drops.remove(measurement);
        self.sync_manifest()?;
        self.maybe_snapshot()?;
        Ok(true)
    }

    /// The tombstones recorded by deletes.
    #[must_use]
    pub fn tombstones(&self) -> &TombstoneSet {
        &self.tombstones
    }

    /// Record the tombstones produced by a delete, durably.
    ///
    /// The manifest append is fsynced before this returns, so a delete that
    /// has been acknowledged has been persisted — which is the property the
    /// previous design lacked, because it kept tombstones only in memory and
    /// in a data WAL that the next flush was free to truncate.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written or synced.
    pub fn record_tombstones(&mut self, tombstones: &[Tombstone]) -> Result<()> {
        // One fsync for the delete, not one per tombstone: a delete over a
        // measurement with a hundred series produces a hundred of them.
        self.in_one_sync(|catalog| {
            for tombstone in tombstones {
                catalog.append_manifest(&ManifestEntry::AddTombstone(tombstone.clone()))?;
                catalog.tombstones.insert(tombstone.clone());
            }
            Ok(())
        })?;
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Register a compaction's output and retire its inputs, as one
    /// durable step.
    ///
    /// Adds `output`, soft-deletes every input, and extends every tombstone
    /// that named an input to the output. That last part is what closes the
    /// window in which a delete issued *while* the merge ran was undone: the
    /// merge applied the tombstones it snapshotted, the late tombstone named
    /// only the inputs, and once GC removed them the tombstone was reclaimed
    /// with its rows alive in the output.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn complete_compaction(
        &mut self,
        output: SegmentCatalogEntry,
        inputs: &[SegmentId],
        now_ms: u64,
    ) -> Result<()> {
        let output_id = output.segment_id.0;
        let input_ids: Vec<u64> = inputs.iter().map(|id| id.0).collect();
        // One fsync for the whole transition, not one per input segment.
        self.in_one_sync(|catalog| {
            catalog.add_segment(output)?;
            for input in inputs {
                catalog.soft_delete_segment(*input, now_ms)?;
            }
            catalog.append_manifest(&ManifestEntry::Compacted {
                inputs: input_ids.clone(),
                output: output_id,
            })
        })?;
        self.tombstones
            .extend_to_compaction_output(&input_ids, output_id);
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Reclaim tombstones whose segments have all left the catalog.
    ///
    /// A segment leaves the catalog only by being rewritten — compaction
    /// applies tombstones as it merges — or by being deleted outright, so once
    /// none of a tombstone's segments remains, no stored row can still match
    /// it. Returns the number reclaimed.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn reclaim_tombstones(&mut self) -> Result<usize> {
        let live: std::collections::HashSet<u64> = self
            .segments
            .values()
            .flatten()
            .map(|e| e.segment_id.0)
            .collect();

        // A tombstone with no recorded segments predates nothing we can prove
        // about, so it is kept. Every tombstone this engine writes records the
        // segments it was issued against.
        let removed = self.tombstones.retain_tombstones(|t| {
            t.segments.is_empty() || t.segments.iter().any(|id| live.contains(id))
        });

        for tombstone in &removed {
            self.append_manifest(&ManifestEntry::RemoveTombstone(tombstone.clone()))?;
        }
        if !removed.is_empty() {
            self.sync_manifest()?;
            self.maybe_snapshot()?;
        }
        Ok(removed.len())
    }

    /// Register or update a measurement schema.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn set_schema(&mut self, schema: MeasurementSchema) -> Result<()> {
        let entry = ManifestEntry::SetSchema(schema.clone());
        self.append_manifest(&entry)?;
        self.schemas
            .insert(schema.measurement().to_string(), schema);
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Remove a measurement schema.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written.
    pub fn remove_schema(&mut self, measurement: &str) -> Result<Option<MeasurementSchema>> {
        let entry = ManifestEntry::RemoveSchema(measurement.to_string());
        self.append_manifest(&entry)?;
        let removed = self.schemas.remove(measurement);
        self.maybe_snapshot()?;
        Ok(removed)
    }

    /// The WAL floor: the highest data-WAL sequence number known to be
    /// fully represented by the segments this catalog registers.
    ///
    /// `open()` replays only records above it.
    #[must_use]
    pub fn wal_floor(&self) -> u64 {
        self.wal_floor
    }

    /// Raise the WAL floor to `sequence_no`.
    ///
    /// Persisted before it is applied, like every other catalog change. A
    /// floor never moves backwards; a lower value is a no-op.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest append fails.
    pub fn set_wal_floor(&mut self, sequence_no: u64) -> Result<()> {
        if sequence_no <= self.wal_floor {
            return Ok(());
        }
        self.append_manifest(&ManifestEntry::SetWalFloor(sequence_no))?;
        self.wal_floor = sequence_no;
        self.maybe_snapshot()?;
        Ok(())
    }

    /// Look up a measurement schema.
    #[must_use]
    pub fn get_schema(&self, measurement: &str) -> Option<&MeasurementSchema> {
        self.schemas.get(measurement)
    }

    /// Returns all schema names.
    #[must_use]
    pub fn schema_names(&self) -> Vec<String> {
        self.schemas.keys().cloned().collect()
    }

    /// Returns an iterator over all `(name, schema)` pairs.
    pub fn all_schemas(&self) -> impl Iterator<Item = (&String, &MeasurementSchema)> {
        self.schemas.iter()
    }

    /// Force a snapshot of the current catalog state.
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot cannot be written.
    pub fn force_snapshot(&mut self) -> Result<()> {
        self.write_snapshot()?;
        self.changes_since_snapshot = 0;
        Ok(())
    }

    /// Append a manifest entry to the WAL file.
    ///
    /// Format: `[u32-le length][postcard payload][u32-le CRC32c]`
    fn append_manifest(&mut self, entry: &ManifestEntry) -> Result<()> {
        self.manifest_seq += 1;

        // Lazily open the WAL file handle and keep it for future appends.
        if self.manifest_wal_file.is_none() {
            let wal_path = self.manifest_dir.join("manifest.wal");
            let f = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&wal_path)?;
            self.manifest_wal_file = Some(f);
        }
        let file = self
            .manifest_wal_file
            .as_mut()
            .ok_or_else(|| IndexError::BinarySerialization("WAL file not opened".into()))?;

        let payload = postcard::to_stdvec(entry)
            .map_err(|e| IndexError::BinarySerialization(e.to_string()))?;
        let len = payload.len() as u32;
        let crc = crc32c::crc32c(&payload);
        file.write_all(&len.to_le_bytes())?;
        file.write_all(&payload)?;
        file.write_all(&crc.to_le_bytes())?;
        // Always flush to kernel buffers so data is ordered.
        file.flush()?;

        // Synced here unless a caller has declared that this append is one
        // step of a larger transition (`in_one_sync`), in which case that
        // caller's single `sync_manifest()` covers it. Data reaches the
        // kernel either way.
        self.pending_sync += 1;
        if self.defer_sync == 0 && self.pending_sync >= SYNC_BATCH_SIZE {
            file.sync_data()?;
            self.pending_sync = 0;
            self.manifest_syncs += 1;
            metrics::counter!("chronix_catalog_fsync_total").increment(1);
        }

        self.changes_since_snapshot += 1;
        Ok(())
    }

    /// How many times the manifest has been fsynced since this catalog was
    /// opened.
    ///
    /// One per catalog *transition*, not per append: a compaction retiring
    /// four segments is one, and so is a delete however many tombstones it
    /// produces. Also exported as `chronix_catalog_fsync_total`.
    #[must_use]
    pub fn manifest_syncs(&self) -> u64 {
        self.manifest_syncs
    }

    /// Run `body` as one durable manifest transition: the appends it makes are
    /// written but fsynced **once**, when it returns.
    ///
    /// A compaction of four segments is six appends — the output, four
    /// soft-deletes and the `Compacted` record — and a delete is one per
    /// tombstone. On flash-backed storage the fsync rate *is* the wear rate,
    /// which is why the WAL has a periodic policy.
    ///
    /// Everything `body` appended is durable when this returns, on the error
    /// path as much as the success path, so a transition that failed half-way
    /// is as persistent as it would be if each append had synced. A crash
    /// *during* `body` leaves what it always could: the manifest is a replayed
    /// log, so a partial transition means an input segment still live beside
    /// its compaction output, which reads deduplicate and the next compaction
    /// clears.
    ///
    /// **Only for a transition that ends in a sync.** The retention, GC and
    /// cold-tier loops call `remove_segment` without one and rely on the
    /// per-append fsync, which is why this is opt-in rather than a batch size.
    fn in_one_sync<T>(&mut self, body: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        self.defer_sync += 1;
        let out = body(self);
        self.defer_sync -= 1;
        // Before `out?`: a half-finished transition must be as durable as it
        // was when each of its appends synced on its own.
        self.sync_manifest()?;
        out
    }

    /// Flush any pending manifest writes to durable storage.
    ///
    /// Call this after a batch of mutations to ensure all appended entries
    /// survive a power failure.  This is a no-op if there are no pending
    /// un-synced writes.
    pub fn sync_manifest(&mut self) -> Result<()> {
        if self.pending_sync > 0 {
            if let Some(ref f) = self.manifest_wal_file {
                f.sync_data()?;
            }
            self.pending_sync = 0;
            self.manifest_syncs += 1;
            metrics::counter!("chronix_catalog_fsync_total").increment(1);
        }
        Ok(())
    }

    /// Replay manifest WAL entries from a file.
    ///
    /// Reads length-prefixed postcard records with CRC32c integrity.
    /// Truncated tail records (common crash artefact) are skipped
    /// with a warning. Mid-stream corruption returns an error.
    fn replay_manifest(&mut self, wal_path: &Path) -> Result<()> {
        let mut file = std::fs::File::open(wal_path)?;
        let file_len = file.metadata()?.len();

        let mut replayed = 0u64;
        let mut tail_skipped = 0u64;
        let mut pos = 0u64;

        loop {
            if pos >= file_len {
                break;
            }
            // Read length header (4 bytes)
            let mut len_buf = [0u8; 4];
            match file.read_exact(&mut len_buf) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    tail_skipped += 1;
                    warn!(
                        offset = pos,
                        "manifest replay: truncated length header at tail"
                    );
                    break;
                }
                Err(e) => return Err(e.into()),
            }
            let payload_len = u32::from_le_bytes(len_buf) as usize;
            pos += 4;

            // Sanity check payload length
            if payload_len == 0 || payload_len > 64 * 1024 * 1024 {
                if pos + (payload_len as u64) + 4 > file_len {
                    tail_skipped += 1;
                    warn!(
                        offset = pos - 4,
                        payload_len, "manifest replay: truncated entry at tail"
                    );
                    break;
                }
                return Err(IndexError::Manifest {
                    detail: format!(
                        "invalid manifest entry length {payload_len} at offset {}",
                        pos - 4
                    ),
                });
            }

            // Read payload + CRC
            let total = payload_len + 4; // payload + CRC32c
            if pos + total as u64 > file_len {
                tail_skipped += 1;
                warn!(
                    offset = pos - 4,
                    "manifest replay: truncated payload at tail"
                );
                break;
            }

            let mut buf = vec![0u8; total];
            if let Err(e) = file.read_exact(&mut buf) {
                if e.kind() == std::io::ErrorKind::UnexpectedEof {
                    tail_skipped += 1;
                    warn!(offset = pos - 4, "manifest replay: truncated read at tail");
                    break;
                }
                return Err(e.into());
            }

            let payload = &buf[..payload_len];
            let stored_crc = u32::from_le_bytes([
                buf[payload_len],
                buf[payload_len + 1],
                buf[payload_len + 2],
                buf[payload_len + 3],
            ]);
            let computed_crc = crc32c::crc32c(payload);

            if stored_crc != computed_crc {
                // Check if there are more valid records after this
                let remaining = file_len - pos - total as u64;
                if remaining > 8 {
                    return Err(IndexError::Manifest {
                        detail: format!(
                            "CRC mismatch at offset {} (stored={stored_crc:#x}, computed={computed_crc:#x}) — mid-stream corruption",
                            pos - 4,
                        ),
                    });
                }
                tail_skipped += 1;
                warn!(
                    offset = pos - 4,
                    "manifest replay: CRC mismatch at tail, skipping"
                );
                break;
            }

            match postcard::from_bytes::<ManifestEntry>(payload) {
                Ok(entry) => {
                    self.apply_manifest_entry(entry);
                    self.manifest_seq += 1;
                    replayed += 1;
                }
                Err(e) => {
                    // Check if remaining data could contain valid entries
                    let remaining = file_len - pos - total as u64;
                    if remaining > 8 {
                        return Err(IndexError::Manifest {
                            detail: format!("deserialization error at offset {}: {e}", pos - 4,),
                        });
                    }
                    tail_skipped += 1;
                    warn!(offset = pos - 4, error = %e, "manifest replay: skipping corrupt tail entry");
                    break;
                }
            }

            pos += total as u64;
        }

        if tail_skipped > 0 {
            warn!(
                tail_skipped,
                "manifest replay: truncated tail entries skipped"
            );
        }
        if replayed > 0 {
            debug!(replayed, "replayed manifest entries");
        }

        Ok(())
    }

    /// Apply a manifest entry to the in-memory state (no persistence).
    fn apply_manifest_entry(&mut self, entry: ManifestEntry) {
        match entry {
            ManifestEntry::AddSegment(seg) => {
                // Track next_segment_id
                if seg.segment_id.0 >= self.next_segment_id {
                    self.next_segment_id = seg.segment_id.0 + 1;
                }
                // Dedup: remove any existing entry with the same segment_id
                // before pushing. This handles WAL replay of soft_delete_segment
                // which re-adds segments with updated state.
                let shard_entries = self.segments.entry(seg.shard_id).or_default();
                shard_entries.retain(|e| e.segment_id != seg.segment_id);
                shard_entries.push(seg);
            }
            ManifestEntry::RemoveSegment(id) => {
                for entries in self.segments.values_mut() {
                    entries.retain(|e| e.segment_id.0 != id);
                }
            }
            ManifestEntry::SetSchema(schema) => {
                self.schemas
                    .insert(schema.measurement().to_string(), schema);
            }
            ManifestEntry::RemoveSchema(name) => {
                self.schemas.remove(&name);
            }
            ManifestEntry::AddTombstone(t) => {
                self.tombstones.insert(t);
            }
            ManifestEntry::RemoveTombstone(t) => {
                self.tombstones.retain_tombstones(|existing| existing != &t);
            }
            ManifestEntry::SetWalFloor(seq) => {
                self.wal_floor = self.wal_floor.max(seq);
            }
            ManifestEntry::SetRollup { name, definition } => {
                self.rollups.entry(name).or_default().definition = definition;
            }
            ManifestEntry::RemoveRollup(name) => {
                self.rollups.remove(&name);
            }
            ManifestEntry::SetRollupState { name, state } => {
                self.rollups.entry(name).or_default().state = state;
            }
            ManifestEntry::Compacted { inputs, output } => {
                self.tombstones.extend_to_compaction_output(&inputs, output);
            }
            ManifestEntry::SetPendingMeasurementDrop {
                measurement,
                deadline_ms,
            } => {
                self.pending_measurement_drops
                    .insert(measurement, deadline_ms);
            }
            ManifestEntry::CancelPendingMeasurementDrop(measurement) => {
                self.pending_measurement_drops.remove(&measurement);
            }
        }
    }

    /// Write a full snapshot and truncate the WAL.
    fn write_snapshot(&mut self) -> Result<()> {
        let snapshot = CatalogSnapshot {
            format_version: CATALOG_FORMAT_VERSION,
            segments: self.segments.clone(),
            schemas: self.schemas.clone(),
            tombstones: self.tombstones.clone(),
            wal_floor: self.wal_floor,
            rollups: self.rollups.clone(),
            pending_measurement_drops: self.pending_measurement_drops.clone(),
            manifest_seq: self.manifest_seq,
            next_segment_id: self.next_segment_id,
        };

        let data = postcard::to_stdvec(&snapshot)
            .map_err(|e| IndexError::BinarySerialization(e.to_string()))?;

        // Atomic snapshot write: write temp → fsync → rename → fsync parent.
        let snapshot_path = self.manifest_dir.join("manifest.snapshot.bin");
        let tmp_path = self.manifest_dir.join("manifest.snapshot.bin.tmp");
        // The temp file is removed on failure. The segment writer and the
        // local storage backend both do this; the catalog did not, so a
        // snapshot interrupted by `ENOSPC` left a partial `.tmp` behind —
        // consuming the space whose absence caused the failure, on the one
        // file the database cannot afford to lose.
        let write_tmp = (|| -> std::io::Result<()> {
            let mut file = std::fs::File::create(&tmp_path)?;
            file.write_all(&data)?;
            file.sync_all()
        })();
        if let Err(e) = write_tmp {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(e.into());
        }
        if let Err(e) = std::fs::rename(&tmp_path, &snapshot_path) {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(e.into());
        }

        // Fsync parent directory to make the rename durable.
        // This MUST succeed before truncating the WAL; otherwise a crash
        // could leave us with the old snapshot and an empty WAL → data loss.
        let dir = std::fs::File::open(&self.manifest_dir).map_err(|e| {
            std::io::Error::new(
                e.kind(),
                format!("failed to open manifest dir for fsync: {e}"),
            )
        })?;
        dir.sync_all()?;

        // Truncate WAL and invalidate the persistent file handle so it
        // gets re-opened on the next append.
        let wal_path = self.manifest_dir.join("manifest.wal");
        if wal_path.exists() {
            let file = std::fs::OpenOptions::new()
                .write(true)
                .truncate(true)
                .open(&wal_path)?;
            // The truncation must be durable too. Replay is idempotent for
            // every entry kind, so a resurrected entry is harmless — but an
            // unsynced truncation is exactly the kind of "probably fine"
            // this catalog does not deal in.
            file.sync_all()?;
        }
        self.manifest_wal_file = None;

        debug!(seq = self.manifest_seq, "catalog snapshot written");
        Ok(())
    }

    /// Take a snapshot if the change count exceeds the threshold.
    fn maybe_snapshot(&mut self) -> Result<()> {
        if self.changes_since_snapshot >= SNAPSHOT_INTERVAL {
            self.write_snapshot()?;
            self.changes_since_snapshot = 0;
        }
        Ok(())
    }
}

/// Current catalog snapshot format version — 1, the first that ships.
///
/// Unlike the segment header this is compared with `>`: a snapshot from a
/// *newer* Chronix is refused, an older one is read.
const CATALOG_FORMAT_VERSION: u32 = 1;

/// Serializable snapshot of the catalog state.
#[derive(Debug, Serialize, Deserialize)]
struct CatalogSnapshot {
    /// Format version for forward compatibility.
    #[serde(default)]
    format_version: u32,
    segments: BTreeMap<ShardId, Vec<SegmentCatalogEntry>>,
    schemas: HashMap<String, MeasurementSchema>,
    /// Tombstones, as of this snapshot. A snapshot that omitted them would
    /// undo every delete the moment the manifest WAL was folded into it.
    #[serde(default)]
    tombstones: TombstoneSet,
    /// See [`SegmentCatalog::wal_floor`].
    #[serde(default)]
    wal_floor: u64,
    /// Rollup definitions and their materialisation state, by name. Opaque
    /// bytes: the catalog is where they are durable, the facade is where
    /// they mean something.
    #[serde(default)]
    rollups: BTreeMap<String, RollupRecord>,
    /// See [`SegmentCatalog::pending_measurement_drops`].
    #[serde(default)]
    pending_measurement_drops: BTreeMap<String, u64>,
    manifest_seq: u64,
    next_segment_id: u64,
}

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

    fn test_entry(id: u64, shard: i64, min_ts: i64, max_ts: i64) -> SegmentCatalogEntry {
        SegmentCatalogEntry {
            segment_id: SegmentId(id),
            shard_id: ShardId(shard),
            measurement: "cpu".to_string(),
            path: PathBuf::from(format!("shard_{shard}/seg_{id}.csx")),
            min_timestamp: min_ts,
            max_timestamp: max_ts,
            row_count: 1000,
            series_count: 10,
            byte_size: 4096,
            row_group_count: 1,
            column_count: 5,
            column_stats: Vec::new(),
            state: SegmentState::default(),
        }
    }

    /// A compaction is **one** fsync, whatever it retires.
    ///
    /// It used to be one per append: the output, one per input segment, and
    /// the `Compacted` record — six for a four-segment merge, and compaction
    /// runs every maintenance interval. On the flash the design partner
    /// writes to, the fsync rate is the wear rate.
    #[test]
    fn a_compaction_costs_one_manifest_fsync() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();

        let inputs: Vec<SegmentId> = (1..=4i64)
            .map(|i| {
                #[allow(clippy::cast_sign_loss)]
                let e = test_entry(i as u64, 0, i * 100, i * 100 + 50);
                let id = e.segment_id;
                catalog.add_segment(e).unwrap();
                id
            })
            .collect();

        let before = catalog.manifest_syncs();
        catalog
            .complete_compaction(test_entry(99, 0, 100, 450), &inputs, 0)
            .unwrap();
        assert_eq!(
            catalog.manifest_syncs() - before,
            1,
            "one transition, one fsync — it was six"
        );

        // …and it is durable: a reopen sees the output live and the inputs
        // soft-deleted, which is the property the per-append fsync bought.
        drop(catalog);
        let reopened = SegmentCatalog::open(dir.path()).unwrap();
        let live: Vec<u64> = reopened
            .active_segments_for_measurement("cpu")
            .iter()
            .map(|e| e.segment_id.0)
            .collect();
        assert_eq!(live, vec![99], "only the compaction output survives");
    }

    /// A delete is one fsync, not one per tombstone.
    #[test]
    fn a_delete_costs_one_manifest_fsync() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
        let tombstones: Vec<Tombstone> = (0..25)
            .map(|i| Tombstone::ranged(format!("cpu,host=h{i}"), 0, 1_000))
            .collect();

        let before = catalog.manifest_syncs();
        catalog.record_tombstones(&tombstones).unwrap();
        assert_eq!(
            catalog.manifest_syncs() - before,
            1,
            "25 tombstones, 1 fsync"
        );

        drop(catalog);
        let reopened = SegmentCatalog::open(dir.path()).unwrap();
        assert_eq!(
            reopened.tombstones().len(),
            25,
            "every tombstone survived the reopen"
        );
    }

    /// A single mutation still syncs on its own — the batching is opt-in, and
    /// the retention, GC and cold-tier loops rely on that.
    #[test]
    fn a_lone_append_still_syncs() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
        let before = catalog.manifest_syncs();
        catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
        assert_eq!(catalog.manifest_syncs() - before, 1);
        catalog.soft_delete_segment(SegmentId(1), 0).unwrap();
        assert_eq!(catalog.manifest_syncs() - before, 2);
    }

    #[test]
    fn add_and_get_segments() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();

        catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
        catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();
        catalog.add_segment(test_entry(3, 1, 100, 200)).unwrap();

        assert_eq!(catalog.get_segments_for_shard(&ShardId(0)).len(), 2);
        assert_eq!(catalog.get_segments_for_shard(&ShardId(1)).len(), 1);
        assert_eq!(catalog.get_segments_for_shard(&ShardId(99)).len(), 0);
        assert_eq!(catalog.segment_count(), 3);
    }

    #[test]
    fn remove_segment() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();

        catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
        catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();

        let removed = catalog.remove_segment(SegmentId(1)).unwrap();
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().segment_id, SegmentId(1));
        assert_eq!(catalog.segment_count(), 1);

        // Remove non-existent
        let removed = catalog.remove_segment(SegmentId(99)).unwrap();
        assert!(removed.is_none());
    }

    #[test]
    fn persist_and_reload() {
        let dir = tempfile::tempdir().unwrap();

        // Create catalog and add segments
        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
            catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();
            catalog.add_segment(test_entry(3, 1, 500, 600)).unwrap();
        }

        // Reload from manifest
        let catalog = SegmentCatalog::open(dir.path()).unwrap();
        assert_eq!(catalog.segment_count(), 3);
        assert_eq!(catalog.get_segments_for_shard(&ShardId(0)).len(), 2);
        assert_eq!(catalog.get_segments_for_shard(&ShardId(1)).len(), 1);
    }

    #[test]
    fn snapshot_and_reload() {
        let dir = tempfile::tempdir().unwrap();

        // Create, populate, snapshot
        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
            catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();
            catalog.force_snapshot().unwrap();
            // Add more after snapshot
            catalog.add_segment(test_entry(3, 1, 500, 600)).unwrap();
        }

        // Reload—should see all 3 from snapshot + WAL
        let catalog = SegmentCatalog::open(dir.path()).unwrap();
        assert_eq!(catalog.segment_count(), 3);
    }

    #[test]
    fn schema_persistence() {
        let dir = tempfile::tempdir().unwrap();

        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            let schema = MeasurementSchema::new("cpu");
            catalog.set_schema(schema).unwrap();
        }

        let catalog = SegmentCatalog::open(dir.path()).unwrap();
        assert!(catalog.get_schema("cpu").is_some());
        assert_eq!(catalog.get_schema("cpu").unwrap().measurement(), "cpu");
    }

    #[test]
    fn remove_schema() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
        catalog.set_schema(MeasurementSchema::new("cpu")).unwrap();
        assert!(catalog.get_schema("cpu").is_some());

        catalog.remove_schema("cpu").unwrap();
        assert!(catalog.get_schema("cpu").is_none());
    }

    #[test]
    fn next_segment_id_monotonic() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();

        assert_eq!(catalog.next_segment_id(), SegmentId(1));
        assert_eq!(catalog.next_segment_id(), SegmentId(2));
        assert_eq!(catalog.next_segment_id(), SegmentId(3));
    }

    #[test]
    fn next_segment_id_survives_reload() {
        let dir = tempfile::tempdir().unwrap();

        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(5, 0, 100, 200)).unwrap();
            catalog.add_segment(test_entry(10, 0, 300, 400)).unwrap();
        }

        let mut catalog = SegmentCatalog::open(dir.path()).unwrap();
        // next_segment_id should be 11 (max existing + 1)
        let next = catalog.next_segment_id();
        assert!(
            next.0 >= 11,
            "next_segment_id should be >= 11, got {}",
            next.0
        );
    }

    #[test]
    fn add_remove_add_roundtrip() {
        let dir = tempfile::tempdir().unwrap();

        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
            catalog.remove_segment(SegmentId(1)).unwrap();
            catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();
        }

        let catalog = SegmentCatalog::open(dir.path()).unwrap();
        assert_eq!(catalog.segment_count(), 1);
        assert_eq!(
            catalog.get_segments_for_shard(&ShardId(0))[0].segment_id,
            SegmentId(2)
        );
    }

    #[test]
    fn all_segments() {
        let dir = tempfile::tempdir().unwrap();
        let mut catalog = SegmentCatalog::new(dir.path()).unwrap();

        catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
        catalog.add_segment(test_entry(2, 1, 300, 400)).unwrap();
        catalog.add_segment(test_entry(3, 2, 500, 600)).unwrap();

        let all = catalog.all_segments();
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn manifest_replay_tail_truncation_tolerated() {
        // Corrupt entries at the end (tail truncation from a crash) should be
        // skipped with a warning — not an error.
        let dir = tempfile::tempdir().unwrap();

        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
            catalog.add_segment(test_entry(2, 0, 300, 400)).unwrap();
        }

        // Append a truncated binary frame at the tail to simulate a crash mid-write.
        let wal_path = dir.path().join("manifest.wal");
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&wal_path)
            .unwrap();
        // Write a length header but no payload — simulates crash after partial write
        let fake_len: u32 = 128;
        f.write_all(&fake_len.to_le_bytes()).unwrap();
        f.write_all(&[0xDE, 0xAD]).unwrap(); // partial payload
        drop(f);

        // Replay should succeed — tail corruption is tolerated.
        let catalog = SegmentCatalog::open(dir.path()).unwrap();
        assert_eq!(catalog.segment_count(), 2);
    }

    #[test]
    fn manifest_replay_midstream_corruption_errors() {
        // A corrupt entry in the middle (valid entries follow it) is real
        // corruption and must cause an error.
        let dir = tempfile::tempdir().unwrap();

        {
            let mut catalog = SegmentCatalog::new(dir.path()).unwrap();
            catalog.add_segment(test_entry(1, 0, 100, 200)).unwrap();
        }

        // Write a corrupt binary frame (valid length, bad CRC) followed by a valid frame.
        let wal_path = dir.path().join("manifest.wal");
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&wal_path)
            .unwrap();

        // Corrupt frame: valid-looking length, garbage payload, wrong CRC
        let corrupt_payload = b"CORRUPT_DATA_HERE_1234";
        let corrupt_len = corrupt_payload.len() as u32;
        let wrong_crc: u32 = 0xDEADBEEF;
        f.write_all(&corrupt_len.to_le_bytes()).unwrap();
        f.write_all(corrupt_payload).unwrap();
        f.write_all(&wrong_crc.to_le_bytes()).unwrap();

        // Valid frame after the corrupt one
        let valid_entry = ManifestEntry::AddSegment(test_entry(3, 0, 500, 600));
        let valid_payload = postcard::to_stdvec(&valid_entry).unwrap();
        let valid_len = valid_payload.len() as u32;
        let valid_crc = crc32c::crc32c(&valid_payload);
        f.write_all(&valid_len.to_le_bytes()).unwrap();
        f.write_all(&valid_payload).unwrap();
        f.write_all(&valid_crc.to_le_bytes()).unwrap();
        drop(f);

        // Replay should fail with a Manifest error.
        let result = SegmentCatalog::open(dir.path());
        assert!(result.is_err(), "expected error for mid-stream corruption");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("mid-stream corruption"),
            "error should mention mid-stream corruption, got: {err_msg}"
        );
    }
}