traverse-runtime 0.10.1

Core execution engine for the Traverse capability runtime.
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
//! Durable, append-only segmented event journal.
//!
//! Governed by spec 066-durable-identity-event-delivery (FR-005..FR-009) and
//! spec 067-durable-journal-retention-and-write-limits (FR-001, FR-002).
//!
//! The bounded publish write path that drives this journal lives in
//! [`super::durable`].

use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};

use serde::{Deserialize, Serialize};

use super::broker::BrokerClock;
use super::types::TraverseEvent;

const SEGMENT_PREFIX: &str = "segment-";
const SEGMENT_SUFFIX: &str = ".jsonl";

/// Journal runtime configuration (067 FR-001 defaults: 64 MB / 10 minutes).
#[derive(Debug, Clone)]
pub struct JournalConfig {
    /// Maximum bytes in a segment before it rolls over.
    pub max_segment_bytes: u64,
    /// Maximum age of a segment before it rolls over, in seconds.
    pub max_segment_age_secs: u64,
    /// Retention by age: events older than this may be reclaimed.
    pub retention_max_age_secs: Option<u64>,
    /// Retention by size: total journal bytes above this may be reclaimed.
    pub retention_max_total_bytes: Option<u64>,
}

impl Default for JournalConfig {
    fn default() -> Self {
        Self {
            max_segment_bytes: 64 * 1024 * 1024,
            max_segment_age_secs: 600,
            retention_max_age_secs: None,
            retention_max_total_bytes: None,
        }
    }
}

/// Errors surfaced by the durable journal.
#[derive(Debug, PartialEq, Eq)]
pub enum JournalError {
    /// Filesystem operation failed.
    Io(String),
    /// A completed journal record is malformed (066 FR-009: fail loudly).
    Corrupt {
        path: String,
        line: usize,
        message: String,
    },
    /// Cursor string could not be parsed.
    InvalidCursor(String),
    /// The requested cursor points before the retained history (066 FR-008).
    CursorExpired { oldest_available_cursor: String },
    /// Journal was configured with invalid limits.
    InvalidConfig(String),
}

impl std::fmt::Display for JournalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(msg) => write!(f, "journal io failure: {msg}"),
            Self::Corrupt {
                path,
                line,
                message,
            } => write!(f, "journal corrupt at {path}:{line}: {message}"),
            Self::InvalidCursor(msg) => write!(f, "invalid journal cursor: {msg}"),
            Self::CursorExpired {
                oldest_available_cursor,
            } => write!(
                f,
                "journal cursor expired: oldest available cursor is {oldest_available_cursor}"
            ),
            Self::InvalidConfig(msg) => write!(f, "invalid journal config: {msg}"),
        }
    }
}

impl std::error::Error for JournalError {}

/// One durable record: an acknowledged event with its journal sequence, or a
/// revocation suppressing a previously written sequence from replay
/// (067 FR-004: a rejected event must not be delivered through any path).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct JournalRecordV1 {
    seq: u64,
    written_at_secs: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    event: Option<TraverseEvent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    revokes: Option<u64>,
}

/// Metadata for one on-disk segment, derived entirely from its contents so
/// cursors stay independent of segment layout (066 FR-007).
#[derive(Debug, Clone)]
struct SegmentMeta {
    path: PathBuf,
    first_seq: u64,
    last_seq: u64,
    created_at_secs: u64,
    last_written_at_secs: u64,
    bytes: u64,
}

/// Incrementally accumulated parse state for one on-disk segment, keyed by
/// path in [`DurableEventJournal::read_cache`]. A sealed segment is read to
/// completion once and never re-read; the active (still-growing) segment
/// only has the bytes appended since the previous call re-read and parsed,
/// so repeated `replay_from` polling does not re-read and re-parse the
/// whole segment on every call.
#[derive(Debug, Default)]
struct SegmentReadCache {
    consumed_bytes: u64,
    consumed_lines: usize,
    records: Vec<JournalRecordV1>,
}

/// Append-only segmented journal with fsync-before-acknowledgement.
pub struct DurableEventJournal {
    root: PathBuf,
    config: JournalConfig,
    clock: Arc<dyn BrokerClock>,
    sealed: Vec<SegmentMeta>,
    active: Option<(SegmentMeta, fs::File)>,
    next_seq: u64,
    read_cache: Mutex<HashMap<PathBuf, SegmentReadCache>>,
}

impl DurableEventJournal {
    /// Open (or create) the journal under `root`, recovering existing
    /// segments. Recovery ignores only an incomplete final record of the
    /// newest segment and fails loudly on any malformed completed record
    /// (066 FR-009).
    ///
    /// # Errors
    ///
    /// Returns [`JournalError::InvalidConfig`] for zero limits,
    /// [`JournalError::Io`] on filesystem failures, and
    /// [`JournalError::Corrupt`] when a completed record is malformed.
    pub fn open(
        root: &Path,
        config: JournalConfig,
        clock: Arc<dyn BrokerClock>,
    ) -> Result<Self, JournalError> {
        validate_config(&config)?;
        fs::create_dir_all(root).map_err(|e| io_err("create journal root", &e))?;

        let mut segment_paths = Vec::new();
        let entries = fs::read_dir(root).map_err(|e| io_err("list journal segments", &e))?;
        for entry in entries {
            let entry = entry.map_err(|e| io_err("read journal segment entry", &e))?;
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with(SEGMENT_PREFIX) && name.ends_with(SEGMENT_SUFFIX) {
                segment_paths.push(entry.path());
            }
        }
        segment_paths.sort();

        let mut sealed = Vec::new();
        let mut next_seq = 1_u64;
        let last_index = segment_paths.len().saturating_sub(1);
        for (index, path) in segment_paths.iter().enumerate() {
            let allow_torn_tail = index == last_index;
            let records = read_segment_records(path, allow_torn_tail)?;
            let Some((first, last)) = records.first().zip(records.last()) else {
                // Nothing in this segment was ever acknowledged (fsync happens
                // before ack), so dropping the file loses no durable data.
                fs::remove_file(path).map_err(|e| io_err("remove empty journal segment", &e))?;
                continue;
            };
            if first.seq < next_seq {
                return Err(JournalError::Corrupt {
                    path: path.display().to_string(),
                    line: 1,
                    message: format!(
                        "sequence {} is not greater than prior segment sequence {}",
                        first.seq,
                        next_seq - 1
                    ),
                });
            }
            let bytes = fs::metadata(path)
                .map_err(|e| io_err("stat journal segment", &e))?
                .len();
            sealed.push(SegmentMeta {
                path: path.clone(),
                first_seq: first.seq,
                last_seq: last.seq,
                created_at_secs: first.written_at_secs,
                last_written_at_secs: last.written_at_secs,
                bytes,
            });
            next_seq = last.seq + 1;
        }

        Ok(Self {
            root: root.to_path_buf(),
            config,
            clock,
            sealed,
            active: None,
            next_seq,
            read_cache: Mutex::new(HashMap::new()),
        })
    }

    /// Append an event, fsync it, and return its cursor (066 FR-006: the
    /// record is durable before this returns). Rolls the active segment over
    /// at the configured size or age bound, whichever occurs first
    /// (067 FR-001).
    ///
    /// # Errors
    ///
    /// Returns [`JournalError::Io`] when the durable write fails; the event
    /// is not acknowledged in that case.
    pub fn append(&mut self, event: &TraverseEvent) -> Result<String, JournalError> {
        self.append_line(Some(event), None)
    }

    /// Durably record that the event at `revoked_cursor` was rejected and
    /// must never be delivered through replay (067 FR-004). Used when a
    /// caller abandoned a write that later completed, or when a durably
    /// written event could not be delivered.
    ///
    /// # Errors
    ///
    /// Returns [`JournalError::InvalidCursor`] for unparseable cursors and
    /// [`JournalError::Io`] when the durable write fails.
    pub fn append_revocation(&mut self, revoked_cursor: &str) -> Result<String, JournalError> {
        let revoked = revoked_cursor.parse::<u64>().map_err(|e| {
            JournalError::InvalidCursor(format!("revoked cursor `{revoked_cursor}`: {e}"))
        })?;
        self.append_line(None, Some(revoked))
    }

    fn append_line(
        &mut self,
        event: Option<&TraverseEvent>,
        revokes: Option<u64>,
    ) -> Result<String, JournalError> {
        let now_secs = self.now_secs()?;

        let needs_rollover = self.active.as_ref().is_some_and(|(meta, _)| {
            meta.bytes >= self.config.max_segment_bytes
                || now_secs.saturating_sub(meta.created_at_secs) >= self.config.max_segment_age_secs
        });
        if needs_rollover && let Some((meta, file)) = self.active.take() {
            drop(file);
            self.sealed.push(meta);
        }

        let mut active = match self.active.take() {
            Some(active) => active,
            None => self.open_segment(now_secs)?,
        };
        let result = append_record(&mut active, self.next_seq, now_secs, event, revokes);
        self.active = Some(active);
        let cursor = result?;
        self.next_seq += 1;
        Ok(cursor)
    }

    fn open_segment(&self, now_secs: u64) -> Result<(SegmentMeta, fs::File), JournalError> {
        let path = self.root.join(format!(
            "{SEGMENT_PREFIX}{:020}{SEGMENT_SUFFIX}",
            self.next_seq
        ));
        let file = fs::OpenOptions::new()
            .create_new(true)
            .append(true)
            .open(&path)
            .map_err(|e| io_err("create journal segment", &e))?;
        Ok((
            SegmentMeta {
                path,
                first_seq: self.next_seq,
                last_seq: self.next_seq,
                created_at_secs: now_secs,
                last_written_at_secs: now_secs,
                bytes: 0,
            },
            file,
        ))
    }

    /// Replay up to `max_events` events strictly after `cursor`.
    ///
    /// `"0"` replays from the start of retained history. Cursors are opaque
    /// monotonic sequence identifiers independent of segment layout
    /// (066 FR-007).
    ///
    /// # Errors
    ///
    /// Returns [`JournalError::InvalidCursor`] for unparseable cursors,
    /// [`JournalError::CursorExpired`] with the oldest available cursor when
    /// the requested history was reclaimed (066 FR-008), and
    /// [`JournalError::Io`] / [`JournalError::Corrupt`] on read failures.
    pub fn replay_from(
        &self,
        cursor: &str,
        max_events: usize,
    ) -> Result<Vec<(String, TraverseEvent)>, JournalError> {
        let after = cursor
            .parse::<u64>()
            .map_err(|e| JournalError::InvalidCursor(format!("cursor `{cursor}`: {e}")))?;

        let oldest = self.oldest_retained_seq();
        if let Some(oldest_seq) = oldest
            && after + 1 < oldest_seq
        {
            return Err(JournalError::CursorExpired {
                oldest_available_cursor: (oldest_seq - 1).to_string(),
            });
        }

        // Revocations always carry a later sequence than the record they
        // suppress, so the full scan must finish before results are final.
        let mut revoked = std::collections::HashSet::new();
        let mut collected: Vec<(u64, TraverseEvent)> = Vec::new();
        let last_index = self.segment_count().saturating_sub(1);
        for (index, meta) in self.segments().enumerate() {
            if meta.last_seq <= after {
                continue;
            }
            let allow_torn_tail = index == last_index;
            for record in self.cached_segment_records(&meta.path, allow_torn_tail)? {
                if let Some(revoked_seq) = record.revokes {
                    let _ = revoked.insert(revoked_seq);
                } else if record.seq > after
                    && let Some(event) = record.event
                {
                    collected.push((record.seq, event));
                }
            }
        }
        collected.retain(|(seq, _)| !revoked.contains(seq));
        collected.truncate(max_events);
        Ok(collected
            .into_iter()
            .map(|(seq, event)| (seq.to_string(), event))
            .collect())
    }

    /// The cursor from which the oldest retained event replays; callers that
    /// receive [`JournalError::CursorExpired`] resume from here.
    #[must_use]
    pub fn oldest_available_cursor(&self) -> String {
        match self.oldest_retained_seq() {
            Some(seq) => (seq - 1).to_string(),
            None => (self.next_seq - 1).to_string(),
        }
    }

    /// The most recent cursor ever durably assigned, or `0` when nothing has
    /// been written yet. [`super::durable::DurableBroker::open`] uses this to
    /// seed a freshly constructed in-memory broker's restart floor (spec 066
    /// FR-007), so it correctly defers cursors it cannot itself vouch for to
    /// durable replay instead of accepting them by default.
    #[must_use]
    pub(crate) fn latest_cursor(&self) -> u64 {
        self.next_seq.saturating_sub(1)
    }

    /// Reclaim expired history by deleting whole sealed segments only — never
    /// rewriting or truncating in place (067 FR-002). A segment is deleted
    /// only once every event in it falls outside the retention window; the
    /// active segment is never deleted, bounding the overhang to one rollover
    /// period.
    ///
    /// # Errors
    ///
    /// Returns [`JournalError::Io`] when a reclaimable segment cannot be
    /// deleted.
    pub fn prune(&mut self) -> Result<Vec<PathBuf>, JournalError> {
        let now_secs = self.now_secs()?;
        let mut deleted = Vec::new();

        if let Some(max_age) = self.config.retention_max_age_secs {
            while let Some(meta) = self.sealed.first() {
                if now_secs.saturating_sub(meta.last_written_at_secs) <= max_age {
                    break;
                }
                let meta = self.sealed.remove(0);
                fs::remove_file(&meta.path)
                    .map_err(|e| io_err("remove expired journal segment", &e))?;
                deleted.push(meta.path);
            }
        }

        if let Some(max_total) = self.config.retention_max_total_bytes {
            let mut total: u64 = self.segments().map(|meta| meta.bytes).sum();
            while total > max_total && !self.sealed.is_empty() {
                let meta = self.sealed.remove(0);
                fs::remove_file(&meta.path)
                    .map_err(|e| io_err("remove oversized journal segment", &e))?;
                total -= meta.bytes;
                deleted.push(meta.path);
            }
        }

        if !deleted.is_empty() {
            let mut cache = self
                .read_cache
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            for path in &deleted {
                cache.remove(path);
            }
        }

        Ok(deleted)
    }

    fn now_secs(&self) -> Result<u64, JournalError> {
        let now = self.clock.now();
        let elapsed = now
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| JournalError::Io(format!("system time before epoch: {e}")))?;
        Ok(elapsed.as_secs())
    }

    fn segments(&self) -> impl Iterator<Item = &SegmentMeta> {
        self.sealed
            .iter()
            .chain(self.active.iter().map(|(meta, _)| meta))
    }

    fn segment_count(&self) -> usize {
        self.sealed.len() + usize::from(self.active.is_some())
    }

    fn oldest_retained_seq(&self) -> Option<u64> {
        self.segments().map(|meta| meta.first_seq).next()
    }

    /// Returns `path`'s parsed records, reading and parsing from disk only
    /// the bytes appended since the previous call for this path.
    fn cached_segment_records(
        &self,
        path: &Path,
        allow_torn_tail: bool,
    ) -> Result<Vec<JournalRecordV1>, JournalError> {
        let mut cache = self
            .read_cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let entry = cache.entry(path.to_path_buf()).or_default();
        refresh_segment_cache(entry, path, allow_torn_tail)?;
        Ok(entry.records.clone())
    }
}

fn validate_config(config: &JournalConfig) -> Result<(), JournalError> {
    if config.max_segment_bytes == 0 {
        return Err(JournalError::InvalidConfig(
            "max_segment_bytes must be at least 1".to_string(),
        ));
    }
    if config.max_segment_age_secs == 0 {
        return Err(JournalError::InvalidConfig(
            "max_segment_age_secs must be at least 1".to_string(),
        ));
    }
    if config.retention_max_age_secs == Some(0) {
        return Err(JournalError::InvalidConfig(
            "retention_max_age_secs must be at least 1 when set".to_string(),
        ));
    }
    if config.retention_max_total_bytes == Some(0) {
        return Err(JournalError::InvalidConfig(
            "retention_max_total_bytes must be at least 1 when set".to_string(),
        ));
    }
    Ok(())
}

/// Serialize, durably write, and acknowledge one record into the active
/// segment, returning its cursor.
fn append_record(
    active: &mut (SegmentMeta, fs::File),
    seq: u64,
    now_secs: u64,
    event: Option<&TraverseEvent>,
    revokes: Option<u64>,
) -> Result<String, JournalError> {
    let record = JournalRecordV1 {
        seq,
        written_at_secs: now_secs,
        event: event.cloned(),
        revokes,
    };
    let mut line = serde_json::to_vec(&record)
        .map_err(|e| JournalError::Io(format!("serialize journal record: {e}")))?;
    line.push(b'\n');

    let (meta, file) = active;
    write_durable(file, &line)?;
    meta.bytes += line.len() as u64;
    meta.last_seq = seq;
    meta.last_written_at_secs = now_secs;
    Ok(seq.to_string())
}

/// Write and fsync one record line; the record is only acknowledged after
/// both succeed (066 FR-006).
fn write_durable(file: &mut fs::File, line: &[u8]) -> Result<(), JournalError> {
    let write_then_sync = |file: &mut fs::File| -> std::io::Result<()> {
        file.write_all(line)?;
        file.sync_data()
    };
    write_then_sync(file).map_err(|e| io_err("append journal record", &e))
}

/// Reads and parses only the bytes appended to `path` since `cache` was last
/// refreshed (tracked by `cache.consumed_bytes`), appending newly parsed
/// records to `cache.records`. Applies exactly the same corrupt/torn-tail
/// semantics as [`read_segment_records`] to the incremental slice, using
/// `cache`'s prior state (consumed line count, last parsed sequence) as
/// context. On error, `cache` is left unmodified so a retry re-parses the
/// same bytes rather than duplicating already-cached records.
fn refresh_segment_cache(
    cache: &mut SegmentReadCache,
    path: &Path,
    allow_torn_tail: bool,
) -> Result<(), JournalError> {
    use std::io::{Read, Seek, SeekFrom};

    let mut file = fs::File::open(path).map_err(|e| io_err("read journal segment", &e))?;
    let file_len = file
        .metadata()
        .map_err(|e| io_err("read journal segment", &e))?
        .len();
    if file_len <= cache.consumed_bytes {
        return Ok(());
    }

    file.seek(SeekFrom::Start(cache.consumed_bytes))
        .map_err(|e| io_err("read journal segment", &e))?;
    let mut new_bytes =
        Vec::with_capacity(usize::try_from(file_len - cache.consumed_bytes).unwrap_or(0));
    file.read_to_end(&mut new_bytes)
        .map_err(|e| io_err("read journal segment", &e))?;

    let ends_with_newline = new_bytes.last() == Some(&b'\n');
    let chunks: Vec<&[u8]> = new_bytes
        .split(|byte| *byte == b'\n')
        .filter(|chunk| !chunk.is_empty())
        .collect();

    let mut new_records: Vec<JournalRecordV1> = Vec::new();
    let mut bytes_advanced = 0u64;
    let mut last_seq = cache.records.last().map(|record| record.seq);
    for (offset, chunk) in chunks.iter().enumerate() {
        let is_torn_tail = !ends_with_newline && offset + 1 == chunks.len();
        let line = cache.consumed_lines + offset;
        match serde_json::from_slice::<JournalRecordV1>(chunk) {
            Ok(record) => {
                if is_torn_tail {
                    // A record is only acknowledged once its full line
                    // (including the terminator) is fsynced; a tail without a
                    // terminator was never acknowledged, even if it parses.
                    if allow_torn_tail {
                        break;
                    }
                    return Err(corrupt(path, line, "unterminated record"));
                }
                if let Some(previous_seq) = last_seq
                    && record.seq <= previous_seq
                {
                    return Err(corrupt(
                        path,
                        line,
                        &format!(
                            "sequence {} is not greater than prior sequence {}",
                            record.seq, previous_seq
                        ),
                    ));
                }
                bytes_advanced += chunk.len() as u64 + 1;
                last_seq = Some(record.seq);
                new_records.push(record);
            }
            Err(error) => {
                if is_torn_tail && allow_torn_tail {
                    break;
                }
                return Err(corrupt(path, line, &format!("malformed record: {error}")));
            }
        }
    }

    cache.consumed_lines += new_records.len();
    cache.consumed_bytes += bytes_advanced;
    cache.records.extend(new_records);
    Ok(())
}

/// Parse every record in a segment. A trailing chunk without a newline
/// terminator is an incomplete final record: ignored when `allow_torn_tail`
/// (the newest segment interrupted mid-write), corrupt otherwise. Any
/// newline-terminated record that fails to parse is corrupt (066 FR-009).
///
/// Used only for the one-time recovery scan in [`DurableEventJournal::open`];
/// [`DurableEventJournal::replay_from`] uses the incremental
/// [`refresh_segment_cache`] instead.
fn read_segment_records(
    path: &Path,
    allow_torn_tail: bool,
) -> Result<Vec<JournalRecordV1>, JournalError> {
    let bytes = fs::read(path).map_err(|e| io_err("read journal segment", &e))?;
    let ends_with_newline = bytes.last() == Some(&b'\n');

    let mut records: Vec<JournalRecordV1> = Vec::new();
    let chunks: Vec<&[u8]> = bytes
        .split(|byte| *byte == b'\n')
        .filter(|chunk| !chunk.is_empty())
        .collect();
    for (index, chunk) in chunks.iter().enumerate() {
        let is_torn_tail = !ends_with_newline && index + 1 == chunks.len();
        match serde_json::from_slice::<JournalRecordV1>(chunk) {
            Ok(record) => {
                if is_torn_tail {
                    // A record is only acknowledged once its full line
                    // (including the terminator) is fsynced; a tail without a
                    // terminator was never acknowledged, even if it parses.
                    if allow_torn_tail {
                        break;
                    }
                    return Err(corrupt(path, index, "unterminated record"));
                }
                if let Some(previous) = records.last()
                    && record.seq <= previous.seq
                {
                    return Err(corrupt(
                        path,
                        index,
                        &format!(
                            "sequence {} is not greater than prior sequence {}",
                            record.seq, previous.seq
                        ),
                    ));
                }
                records.push(record);
            }
            Err(error) => {
                if is_torn_tail && allow_torn_tail {
                    break;
                }
                return Err(corrupt(path, index, &format!("malformed record: {error}")));
            }
        }
    }
    Ok(records)
}

fn corrupt(path: &Path, index: usize, message: &str) -> JournalError {
    JournalError::Corrupt {
        path: path.display().to_string(),
        line: index + 1,
        message: message.to_string(),
    }
}

fn io_err(action: &str, error: &std::io::Error) -> JournalError {
    JournalError::Io(format!("{action}: {error}"))
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use crate::events::types::LifecycleStatus;
    use std::sync::Mutex;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};
    use uuid::Uuid;

    struct TestClock {
        now: Mutex<SystemTime>,
    }

    impl TestClock {
        fn at_secs(secs: u64) -> Arc<Self> {
            Arc::new(Self {
                now: Mutex::new(UNIX_EPOCH + Duration::from_secs(secs)),
            })
        }

        fn before_epoch() -> Arc<Self> {
            Arc::new(Self {
                now: Mutex::new(UNIX_EPOCH - Duration::from_secs(1)),
            })
        }

        fn advance(&self, secs: u64) {
            let mut now = self.now.lock().expect("test clock lock must not poison");
            *now += Duration::from_secs(secs);
        }
    }

    impl BrokerClock for TestClock {
        fn now(&self) -> SystemTime {
            *self.now.lock().expect("test clock lock must not poison")
        }
    }

    fn test_root(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("traverse-journal-{name}-{}", Uuid::new_v4()))
    }

    fn test_event(marker: &str) -> TraverseEvent {
        TraverseEvent {
            id: Uuid::new_v4().to_string(),
            source: "traverse-runtime/test.capability".to_string(),
            event_type: "dev.traverse.test.journaled".to_string(),
            datacontenttype: "application/json".to_string(),
            time: "2026-07-13T00:00:00Z".to_string(),
            data: serde_json::json!({ "marker": marker }),
            owner: "test.capability".to_string(),
            version: "1.0.0".to_string(),
            lifecycle_status: LifecycleStatus::Active,
            deduplication_id: Some(marker.to_string()),
            ordering_scope: Some("test".to_string()),
            correlation_id: Some("correlation-test".to_string()),
            causation_id: Some("command-test".to_string()),
            subject_id: None,
            actor_id: None,
        }
    }

    fn open_journal(
        root: &Path,
        config: JournalConfig,
        clock: Arc<TestClock>,
    ) -> DurableEventJournal {
        DurableEventJournal::open(root, config, clock).expect("journal must open")
    }

    #[test]
    fn config_limits_are_validated() {
        let clock = TestClock::at_secs(1_000);
        let cases = [
            JournalConfig {
                max_segment_bytes: 0,
                ..JournalConfig::default()
            },
            JournalConfig {
                max_segment_age_secs: 0,
                ..JournalConfig::default()
            },
            JournalConfig {
                retention_max_age_secs: Some(0),
                ..JournalConfig::default()
            },
            JournalConfig {
                retention_max_total_bytes: Some(0),
                ..JournalConfig::default()
            },
        ];
        for config in cases {
            let err = DurableEventJournal::open(&test_root("bad-config"), config, clock.clone())
                .map(|_| ())
                .expect_err("zero limits must be rejected");
            assert!(matches!(err, JournalError::InvalidConfig(_)), "{err}");
        }
    }

    #[test]
    fn append_and_replay_round_trip() {
        let root = test_root("round-trip");
        let clock = TestClock::at_secs(1_000);
        let mut journal = open_journal(&root, JournalConfig::default(), clock);

        assert_eq!(journal.oldest_available_cursor(), "0");
        assert!(
            journal
                .replay_from("0", 10)
                .expect("empty journal must replay nothing")
                .is_empty()
        );

        let first = journal
            .append(&test_event("a"))
            .expect("append must succeed");
        let second = journal
            .append(&test_event("b"))
            .expect("append must succeed");
        assert_eq!(first, "1");
        assert_eq!(second, "2");

        let all = journal.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(all.len(), 2);
        assert_eq!(all[0].0, "1");
        assert_eq!(all[0].1.data["marker"], "a");

        let tail = journal.replay_from("1", 10).expect("replay must succeed");
        assert_eq!(tail.len(), 1);
        assert_eq!(tail[0].0, "2");

        let head = journal.replay_from("2", 10).expect("replay must succeed");
        assert!(head.is_empty());

        let capped = journal.replay_from("0", 1).expect("replay must succeed");
        assert_eq!(capped.len(), 1, "max_events must bound the replay");
    }

    #[test]
    fn replay_from_does_not_reread_previously_returned_records() {
        let root = test_root("incremental-replay");
        let clock = TestClock::at_secs(1_000);
        let mut journal = open_journal(&root, JournalConfig::default(), clock);

        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        let second = journal
            .append(&test_event("b"))
            .expect("append must succeed");

        let first_pass = journal.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(first_pass.len(), 2, "both records must replay initially");

        // Corrupt the on-disk bytes for the already-consumed prefix (the
        // first record). If a later call re-reads and re-parses the whole
        // segment from byte 0 (the pre-fix behavior), this now-invalid JSON
        // makes it fail with JournalError::Corrupt. If it correctly reuses
        // its cached parse of the consumed prefix and only reads bytes
        // appended after it, this corruption is never touched again.
        let segment_path = root.join(format!("{SEGMENT_PREFIX}{:020}{SEGMENT_SUFFIX}", 1));
        let mut contents = fs::read(&segment_path).expect("segment must be readable");
        let first_newline = contents
            .iter()
            .position(|byte| *byte == b'\n')
            .expect("first record must be newline-terminated");
        for byte in &mut contents[..first_newline] {
            *byte = b'x';
        }
        fs::write(&segment_path, &contents).expect("segment must be writable");

        // Advancing the cursor past the corrupted prefix must succeed: only
        // the bytes after `second` are new, and nothing new has been
        // appended yet, so this must return empty without touching disk.
        let empty = journal
            .replay_from(&second, 10)
            .expect("replay of an already-corrupted, already-cached prefix must not re-read it");
        assert!(empty.is_empty());

        // Appending and replaying a genuinely new record must also succeed,
        // proving only the newly appended bytes were read and parsed.
        let third = journal
            .append(&test_event("c"))
            .expect("append must succeed");
        let tail = journal
            .replay_from(&second, 10)
            .expect("replay must only read bytes appended after the cached prefix");
        assert_eq!(tail.len(), 1);
        assert_eq!(tail[0].0, third);
        assert_eq!(tail[0].1.data["marker"], "c");
    }

    #[test]
    fn segments_roll_over_by_size_and_age() {
        let root = test_root("rollover");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            ..JournalConfig::default()
        };
        let mut journal = open_journal(&root, config, clock.clone());
        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        journal
            .append(&test_event("b"))
            .expect("append must succeed");
        journal
            .append(&test_event("c"))
            .expect("append must succeed");
        assert_eq!(journal.sealed.len(), 2, "size bound must seal segments");

        let across = journal.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(across.len(), 3, "replay must cross segment boundaries");
        let capped = journal.replay_from("0", 2).expect("replay must succeed");
        assert_eq!(capped.len(), 2, "max_events must stop mid-journal");

        let age_root = test_root("rollover-age");
        let mut aged = open_journal(&age_root, JournalConfig::default(), clock.clone());
        aged.append(&test_event("a")).expect("append must succeed");
        clock.advance(601);
        aged.append(&test_event("b")).expect("append must succeed");
        assert_eq!(aged.sealed.len(), 1, "age bound must seal segments");
    }

    #[test]
    fn reopen_recovers_segments_and_continues_sequences() {
        let root = test_root("reopen");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            ..JournalConfig::default()
        };
        {
            let mut journal = open_journal(&root, config.clone(), clock.clone());
            journal
                .append(&test_event("a"))
                .expect("append must succeed");
            journal
                .append(&test_event("b"))
                .expect("append must succeed");
        }

        let mut reopened = open_journal(&root, config, clock);
        assert_eq!(reopened.oldest_available_cursor(), "0");
        let cursor = reopened
            .append(&test_event("c"))
            .expect("append must succeed");
        assert_eq!(cursor, "3", "sequence must continue across restart");
        let all = reopened.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(all.len(), 3);
        assert_eq!(all[2].1.data["marker"], "c");
    }

    #[test]
    fn recovery_tolerates_only_an_incomplete_final_record() {
        let root = test_root("torn-tail");
        let clock = TestClock::at_secs(1_000);
        {
            let mut journal = open_journal(&root, JournalConfig::default(), clock.clone());
            journal
                .append(&test_event("a"))
                .expect("append must succeed");
        }
        let segment = fs::read_dir(&root)
            .expect("root must list")
            .next()
            .expect("segment must exist")
            .expect("entry must read")
            .path();

        let original = fs::read(&segment).expect("segment must read");
        let mut torn = original.clone();
        torn.extend_from_slice(b"{\"seq\":2,\"truncated");
        fs::write(&segment, &torn).expect("torn tail must write");
        let journal = open_journal(&root, JournalConfig::default(), clock.clone());
        let recovered = journal.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(recovered.len(), 1, "unparseable torn tail must be ignored");

        let newline = original
            .iter()
            .position(|byte| *byte == b'\n')
            .expect("newline");
        let mut unterminated = original.clone();
        unterminated.extend_from_slice(&original[..newline]);
        fs::write(&segment, &unterminated).expect("unterminated record must write");
        let journal = open_journal(&root, JournalConfig::default(), clock);
        let recovered = journal.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(
            recovered.len(),
            1,
            "a parseable but unterminated tail was never acknowledged and must be ignored"
        );
    }

    #[test]
    fn recovery_fails_loudly_on_malformed_completed_records() {
        let clock = TestClock::at_secs(1_000);

        let corrupt_root = test_root("corrupt-interior");
        fs::create_dir_all(&corrupt_root).expect("root must be creatable");
        fs::write(
            corrupt_root.join("segment-00000000000000000001.jsonl"),
            b"not-json\n",
        )
        .expect("corrupt segment must write");
        let err = DurableEventJournal::open(&corrupt_root, JournalConfig::default(), clock.clone())
            .map(|_| ())
            .expect_err("malformed completed record must fail");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");

        let torn_old_root = test_root("torn-old-segment");
        {
            let config = JournalConfig {
                max_segment_bytes: 1,
                ..JournalConfig::default()
            };
            let mut journal = open_journal(&torn_old_root, config, clock.clone());
            journal
                .append(&test_event("a"))
                .expect("append must succeed");
            journal
                .append(&test_event("b"))
                .expect("append must succeed");
        }
        let oldest = fs::read_dir(&torn_old_root)
            .expect("root must list")
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .min()
            .expect("oldest segment must exist");
        let mut torn = fs::read(&oldest).expect("segment must read");
        torn.extend_from_slice(b"{\"seq\":9,\"truncated");
        fs::write(&oldest, &torn).expect("torn tail must write");
        let err =
            DurableEventJournal::open(&torn_old_root, JournalConfig::default(), clock.clone())
                .map(|_| ())
                .expect_err("a torn tail in an older segment must fail");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");

        let original = fs::read(&oldest).expect("segment must read");
        let unterminated_end = original
            .iter()
            .position(|byte| *byte == b'\n')
            .expect("newline");
        fs::write(&oldest, &original[..unterminated_end])
            .expect("unterminated valid record must write");
        let err =
            DurableEventJournal::open(&torn_old_root, JournalConfig::default(), clock.clone())
                .map(|_| ())
                .expect_err("a parseable unterminated record in an older segment must fail");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");
    }

    #[test]
    fn recovery_rejects_non_monotonic_sequences() {
        let clock = TestClock::at_secs(1_000);
        let record = |seq: u64| {
            let mut line = serde_json::to_vec(&JournalRecordV1 {
                seq,
                written_at_secs: 1_000,
                event: Some(test_event("x")),
                revokes: None,
            })
            .expect("record must serialize");
            line.push(b'\n');
            line
        };

        let within_root = test_root("non-monotonic-within");
        fs::create_dir_all(&within_root).expect("root must be creatable");
        let mut lines = record(2);
        lines.extend_from_slice(&record(2));
        fs::write(
            within_root.join("segment-00000000000000000002.jsonl"),
            &lines,
        )
        .expect("segment must write");
        let err = DurableEventJournal::open(&within_root, JournalConfig::default(), clock.clone())
            .map(|_| ())
            .expect_err("non-monotonic records within a segment must fail");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");

        let across_root = test_root("non-monotonic-across");
        fs::create_dir_all(&across_root).expect("root must be creatable");
        fs::write(
            across_root.join("segment-00000000000000000001.jsonl"),
            record(5),
        )
        .expect("segment must write");
        fs::write(
            across_root.join("segment-00000000000000000002.jsonl"),
            record(3),
        )
        .expect("segment must write");
        let err = DurableEventJournal::open(&across_root, JournalConfig::default(), clock)
            .map(|_| ())
            .expect_err("non-monotonic records across segments must fail");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");
    }

    /// Appends `raw` directly to `path`'s bytes, bypassing `DurableEventJournal`
    /// entirely. Used to simulate a segment corrupted after the journal last
    /// validated it, so the first `replay_from` for that segment (not
    /// `DurableEventJournal::open`'s recovery scan) is what encounters it.
    fn append_raw_bytes(path: &Path, raw: &[u8]) {
        let mut contents = fs::read(path).expect("segment must be readable");
        contents.extend_from_slice(raw);
        fs::write(path, &contents).expect("segment must be writable");
    }

    #[test]
    fn replay_from_rejects_a_torn_tail_in_a_non_final_segment() {
        let root = test_root("replay-torn-non-final");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            ..JournalConfig::default()
        };
        let mut journal = open_journal(&root, config, clock);
        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        journal
            .append(&test_event("b"))
            .expect("append must succeed");

        let oldest = fs::read_dir(&root)
            .expect("root must list")
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .min()
            .expect("oldest segment must exist");
        // A syntactically valid record with no trailing newline: parseable,
        // but only acknowledged once fsynced with its terminator, so this
        // must still be rejected as an unterminated tail (not malformed).
        let unterminated = serde_json::to_vec(&JournalRecordV1 {
            seq: 9,
            written_at_secs: 1_000,
            event: Some(test_event("x")),
            revokes: None,
        })
        .expect("record must serialize");
        append_raw_bytes(&oldest, &unterminated);

        let err = journal
            .replay_from("0", 10)
            .expect_err("a torn tail in a non-final segment must fail on first replay");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");
    }

    #[test]
    fn replay_from_rejects_a_non_monotonic_sequence_on_first_read() {
        let root = test_root("replay-non-monotonic");
        let clock = TestClock::at_secs(1_000);
        let mut journal = open_journal(&root, JournalConfig::default(), clock);
        let first = journal
            .append(&test_event("a"))
            .expect("append must succeed");

        let mut line = serde_json::to_vec(&JournalRecordV1 {
            seq: first.parse().expect("cursor must be numeric"),
            written_at_secs: 1_000,
            event: Some(test_event("x")),
            revokes: None,
        })
        .expect("record must serialize");
        line.push(b'\n');
        let segment = fs::read_dir(&root)
            .expect("root must list")
            .next()
            .expect("segment must exist")
            .expect("entry must read")
            .path();
        append_raw_bytes(&segment, &line);

        let err = journal
            .replay_from("0", 10)
            .expect_err("a non-increasing sequence must fail on first replay");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");
    }

    #[test]
    fn replay_from_rejects_a_malformed_completed_record_on_first_read() {
        let root = test_root("replay-malformed");
        let clock = TestClock::at_secs(1_000);
        let mut journal = open_journal(&root, JournalConfig::default(), clock);
        journal
            .append(&test_event("a"))
            .expect("append must succeed");

        let segment = fs::read_dir(&root)
            .expect("root must list")
            .next()
            .expect("segment must exist")
            .expect("entry must read")
            .path();
        append_raw_bytes(&segment, b"not-json\n");

        let err = journal
            .replay_from("0", 10)
            .expect_err("a malformed completed record must fail on first replay");
        assert!(matches!(err, JournalError::Corrupt { .. }), "{err}");
    }

    #[test]
    fn recovery_drops_segments_with_no_acknowledged_records() {
        let clock = TestClock::at_secs(1_000);
        let root = test_root("empty-segment");
        fs::create_dir_all(&root).expect("root must be creatable");
        let empty = root.join("segment-00000000000000000001.jsonl");
        fs::write(&empty, b"").expect("empty segment must write");
        fs::write(root.join("ignored.txt"), b"not a segment").expect("stray file must write");
        let journal = open_journal(&root, JournalConfig::default(), clock);
        assert!(!empty.exists(), "unacknowledged segment must be removed");
        assert_eq!(journal.oldest_available_cursor(), "0");
    }

    #[test]
    fn filesystem_failures_surface_as_io_errors() {
        let clock = TestClock::at_secs(1_000);

        let blocked_parent = test_root("blocked-parent");
        fs::create_dir_all(&blocked_parent).expect("parent must be creatable");
        fs::write(blocked_parent.join("root"), b"file").expect("squatting file must write");
        let err = DurableEventJournal::open(
            &blocked_parent.join("root"),
            JournalConfig::default(),
            clock.clone(),
        )
        .map(|_| ())
        .expect_err("root creation over a file must fail");
        assert!(matches!(err, JournalError::Io(_)), "{err}");

        let dir_segment_root = test_root("dir-segment");
        fs::create_dir_all(dir_segment_root.join("segment-00000000000000000001.jsonl"))
            .expect("directory squatting on a segment must be creatable");
        let err =
            DurableEventJournal::open(&dir_segment_root, JournalConfig::default(), clock.clone())
                .map(|_| ())
                .expect_err("reading a directory as a segment must fail");
        assert!(matches!(err, JournalError::Io(_)), "{err}");

        let squat_root = test_root("squat-next-segment");
        fs::create_dir_all(squat_root.join("segment-00000000000000000001.jsonl"))
            .expect("squatting directory must be creatable");
        let mut journal =
            open_journal(&test_root("fresh"), JournalConfig::default(), clock.clone());
        journal.root = squat_root;
        let err = journal
            .append(&test_event("a"))
            .expect_err("creating a segment over a directory must fail");
        assert!(matches!(err, JournalError::Io(_)), "{err}");

        let read_only_root = test_root("read-only-file");
        fs::create_dir_all(&read_only_root).expect("root must be creatable");
        let path = read_only_root.join("segment.jsonl");
        fs::write(&path, b"").expect("file must write");
        let mut file = fs::OpenOptions::new()
            .read(true)
            .open(&path)
            .expect("file must open read-only");
        let err = write_durable(&mut file, b"line\n")
            .expect_err("writing through a read-only handle must fail");
        assert!(matches!(err, JournalError::Io(_)), "{err}");
    }

    #[test]
    fn pre_epoch_clock_fails_closed() {
        let root = test_root("pre-epoch");
        let clock = TestClock::before_epoch();
        let mut journal = open_journal(&root, JournalConfig::default(), clock);
        let append_err = journal
            .append(&test_event("a"))
            .expect_err("append with a pre-epoch clock must fail");
        assert!(matches!(append_err, JournalError::Io(_)), "{append_err}");
        let prune_err = journal
            .prune()
            .expect_err("prune with a pre-epoch clock must fail");
        assert!(matches!(prune_err, JournalError::Io(_)), "{prune_err}");
    }

    #[test]
    fn cursors_are_validated_and_expire_after_pruning() {
        let root = test_root("cursor-expiry");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            retention_max_age_secs: Some(10),
            ..JournalConfig::default()
        };
        let mut journal = open_journal(&root, config, clock.clone());

        let invalid = journal
            .replay_from("not-a-cursor", 10)
            .expect_err("malformed cursor must be rejected");
        assert!(
            matches!(invalid, JournalError::InvalidCursor(_)),
            "{invalid}"
        );

        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        journal
            .append(&test_event("b"))
            .expect("append must succeed");
        journal
            .append(&test_event("c"))
            .expect("append must succeed");

        clock.advance(100);
        let deleted = journal.prune().expect("prune must succeed");
        assert_eq!(deleted.len(), 2, "expired sealed segments must be deleted");
        for path in &deleted {
            assert!(!path.exists(), "pruned segment file must be removed");
        }

        let expired = journal
            .replay_from("0", 10)
            .expect_err("cursor before retained history must expire");
        assert_eq!(
            expired,
            JournalError::CursorExpired {
                oldest_available_cursor: "2".to_string(),
            }
        );
        assert_eq!(journal.oldest_available_cursor(), "2");

        let resumed = journal
            .replay_from("2", 10)
            .expect("oldest available cursor must replay");
        assert_eq!(resumed.len(), 1);
        assert_eq!(resumed[0].1.data["marker"], "c");
    }

    #[test]
    fn prune_reclaims_whole_segments_only_and_spares_the_active_one() {
        let root = test_root("prune-rules");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            retention_max_age_secs: Some(1_000_000),
            retention_max_total_bytes: Some(1),
            ..JournalConfig::default()
        };
        let mut journal = open_journal(&root, config, clock.clone());
        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        journal
            .append(&test_event("b"))
            .expect("append must succeed");

        let deleted = journal.prune().expect("prune must succeed");
        assert_eq!(
            deleted.len(),
            1,
            "size retention must delete oldest sealed segments only"
        );
        assert!(
            journal.active.is_some(),
            "the active segment must never be pruned"
        );
        let survivors = journal.replay_from(&journal.oldest_available_cursor(), 10);
        assert_eq!(survivors.expect("replay must succeed").len(), 1);

        let unlimited_root = test_root("prune-unlimited");
        let mut unlimited = open_journal(&unlimited_root, JournalConfig::default(), clock.clone());
        unlimited
            .append(&test_event("a"))
            .expect("append must succeed");
        assert!(
            unlimited
                .prune()
                .expect("prune without retention must succeed")
                .is_empty(),
            "no retention configured means nothing is reclaimed"
        );

        let missing_root = test_root("prune-missing-file");
        let config = JournalConfig {
            max_segment_bytes: 1,
            retention_max_age_secs: Some(1),
            ..JournalConfig::default()
        };
        let mut missing = open_journal(&missing_root, config, clock.clone());
        missing
            .append(&test_event("a"))
            .expect("append must succeed");
        missing
            .append(&test_event("b"))
            .expect("append must succeed");
        let sealed_path = missing.sealed[0].path.clone();
        fs::remove_file(&sealed_path).expect("sealed segment must be removable");
        clock.advance(100);
        let err = missing
            .prune()
            .expect_err("pruning an already-missing segment must surface an io error");
        assert!(matches!(err, JournalError::Io(_)), "{err}");
    }

    #[test]
    fn prune_size_rule_surfaces_removal_failures() {
        let root = test_root("prune-size-missing");
        let clock = TestClock::at_secs(1_000);
        let config = JournalConfig {
            max_segment_bytes: 1,
            retention_max_total_bytes: Some(1),
            ..JournalConfig::default()
        };
        let mut journal = open_journal(&root, config, clock);
        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        journal
            .append(&test_event("b"))
            .expect("append must succeed");
        let sealed_path = journal.sealed[0].path.clone();
        fs::remove_file(&sealed_path).expect("sealed segment must be removable");
        let err = journal
            .prune()
            .expect_err("size pruning an already-missing segment must surface an io error");
        assert!(matches!(err, JournalError::Io(_)), "{err}");
    }

    #[test]
    fn revocations_suppress_events_from_replay() {
        let root = test_root("revocation");
        let clock = TestClock::at_secs(1_000);
        let mut journal = open_journal(&root, JournalConfig::default(), clock.clone());
        journal
            .append(&test_event("a"))
            .expect("append must succeed");
        let second = journal
            .append(&test_event("b"))
            .expect("append must succeed");
        journal
            .append(&test_event("c"))
            .expect("append must succeed");

        journal
            .append_revocation(&second)
            .expect("revocation must be durable");

        let replayed = journal.replay_from("0", 10).expect("replay must succeed");
        let markers: Vec<_> = replayed
            .iter()
            .map(|(_, event)| event.data["marker"].clone())
            .collect();
        assert_eq!(
            markers,
            vec![serde_json::json!("a"), serde_json::json!("c")],
            "the revoked event must not be delivered and the revocation record itself must not appear"
        );

        let capped = journal.replay_from("0", 2).expect("replay must succeed");
        assert_eq!(
            capped.len(),
            2,
            "max_events must apply after revocation filtering"
        );

        let reopened = open_journal(&root, JournalConfig::default(), clock);
        let recovered = reopened.replay_from("0", 10).expect("replay must succeed");
        assert_eq!(
            recovered.len(),
            2,
            "revocations must keep suppressing events across restart"
        );

        let mut invalid = reopened;
        let err = invalid
            .append_revocation("not-a-cursor")
            .expect_err("unparseable revoked cursor must be rejected");
        assert!(matches!(err, JournalError::InvalidCursor(_)), "{err}");
    }

    #[test]
    fn errors_render_stable_messages() {
        let cases: Vec<(JournalError, &str)> = vec![
            (JournalError::Io("boom".to_string()), "journal io failure"),
            (
                JournalError::Corrupt {
                    path: "p".to_string(),
                    line: 3,
                    message: "bad".to_string(),
                },
                "journal corrupt at p:3",
            ),
            (
                JournalError::InvalidCursor("bad".to_string()),
                "invalid journal cursor",
            ),
            (
                JournalError::CursorExpired {
                    oldest_available_cursor: "7".to_string(),
                },
                "oldest available cursor is 7",
            ),
            (
                JournalError::InvalidConfig("bad".to_string()),
                "invalid journal config",
            ),
        ];
        for (error, expected) in cases {
            assert!(
                error.to_string().contains(expected),
                "{error} must mention {expected}"
            );
        }
    }
}