zeppelin-embed 0.7.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
//! Write-ahead logging, checked recovery, and self-tuning group commit.

use std::collections::VecDeque;
use std::io::IoSlice;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex, MutexGuard};

use crate::format::RegistryError;
use crate::lifecycle::durability::{DurabilityPolicy, SyncRequirement};
use crate::manifest::io::DurableLog;
use crate::vfs::{SyncKind, Vfs, VfsFile};

pub mod header;
pub mod record;
pub mod replay;

use header::encode_header;
use record::{
    RecordEncodeError, RecordError, WalRecord, append_record_into, encode_record_into,
    encoded_record_len,
};
use replay::{ReplayTerminator, replay};

/// Default upper bound for one group append, in encoded bytes.
pub const DEFAULT_MAX_GROUP_BYTES: usize = 1_048_576;
/// Default upper bound for a full-sync group append, in encoded bytes.
///
/// Fixed sync cost dominates, while the memory cost is one bounded buffer per
/// writer. Sixteen MiB follows the InnoDB, PostgreSQL, and Lucene convention.
/// Sync cost above one MiB is modeled, not yet measured; the plan 02 sweep is
/// pending.
pub const DEFAULT_MAX_GROUP_BYTES_DURABLE: usize = 16 * 1_048_576;

/// Monotonic write-ahead-log sequence number.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct LogSeq(u64);

impl LogSeq {
    /// Creates a sequence number from its persisted integer.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the persisted integer.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Number of fixed group-size histogram buckets.
pub const GROUP_SIZE_HISTOGRAM_BUCKETS: usize = 18;
/// Maximum number of completed groups retained exactly for diagnostics/tests.
pub const RECENT_GROUP_LIMIT: usize = 64;

/// One record visible from in-memory state before its group reaches storage.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VisibleRecord {
    /// Assigned monotonic sequence.
    pub seq: LogSeq,
    /// Caller-defined operation identifier.
    pub op: u16,
    encoded: Arc<Vec<u8>>,
    encoded_range: Range<usize>,
}

impl VisibleRecord {
    fn writer_owned(
        seq: LogSeq,
        op: u16,
        encoded: Arc<Vec<u8>>,
        encoded_range: Range<usize>,
    ) -> Self {
        Self {
            seq,
            op,
            encoded,
            encoded_range,
        }
    }

    fn recovered(seq: LogSeq, op: u16, encoded: Arc<Vec<u8>>, encoded_range: Range<usize>) -> Self {
        Self {
            seq,
            op,
            encoded,
            encoded_range,
        }
    }

    /// Returns the checked payload borrowed from the encoded WAL allocation.
    pub fn payload(&self) -> Result<&[u8], VisibleRecordError> {
        let encoded = self.encoded.get(self.encoded_range.clone()).ok_or(
            VisibleRecordError::InvalidEncodedRange {
                start: self.encoded_range.start,
                end: self.encoded_range.end,
                available: self.encoded.len(),
            },
        )?;
        decode_visible(encoded).map_err(VisibleRecordError::Record)
    }

    /// Returns the complete encoded record bytes, exactly as appended.
    pub(crate) fn encoded(&self) -> Result<&[u8], VisibleRecordError> {
        self.encoded.get(self.encoded_range.clone()).ok_or(
            VisibleRecordError::InvalidEncodedRange {
                start: self.encoded_range.start,
                end: self.encoded_range.end,
                available: self.encoded.len(),
            },
        )
    }

    /// Returns the complete encoded width retained for this record.
    #[must_use]
    pub fn encoded_len(&self) -> usize {
        self.encoded_range
            .end
            .saturating_sub(self.encoded_range.start)
    }
}

fn decode_visible(encoded: &[u8]) -> Result<&[u8], RecordError> {
    record::decode_record(encoded).map(|decoded| decoded.record.payload)
}

/// One exact completed group retained in the bounded recent-group ring.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CompletedGroup {
    /// Number of records in the group.
    pub records: usize,
    /// Complete encoded bytes appended for the group.
    pub encoded_bytes: usize,
}

/// Fixed-size logarithmic distribution of completed group record counts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GroupSizeHistogram {
    /// Counts for `1`, `2..=3`, `4..=7`, through a final overflow bucket.
    pub buckets: [u64; GROUP_SIZE_HISTOGRAM_BUCKETS],
}

impl GroupSizeHistogram {
    const fn new() -> Self {
        Self {
            buckets: [0; GROUP_SIZE_HISTOGRAM_BUCKETS],
        }
    }

    fn record(&mut self, records: usize) {
        let bucket = if records == 0 {
            0
        } else {
            (usize::BITS
                .saturating_sub(records.leading_zeros())
                .saturating_sub(1) as usize)
                .min(GROUP_SIZE_HISTOGRAM_BUCKETS.saturating_sub(1))
        };
        if let Some(count) = self.buckets.get_mut(bucket) {
            *count = count.saturating_add(1);
        }
    }
}

/// Deterministic group-composition and progress snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WalWriterStats {
    /// Total append groups whose flush returned.
    pub completed_groups: u64,
    /// Total records across completed append groups.
    pub completed_records: u64,
    /// Total encoded bytes across completed append groups.
    pub completed_bytes: u64,
    /// Fixed-size logarithmic group-size distribution.
    pub group_size_histogram: GroupSizeHistogram,
    /// Exact most-recent groups, oldest to newest, capped by [`RECENT_GROUP_LIMIT`].
    pub recent_groups: Vec<CompletedGroup>,
    /// Records waiting behind the currently in-flight group.
    pub pending_records: usize,
    /// Largest sequence visible in memory.
    pub visible_end: Option<LogSeq>,
    /// Largest sequence whose tier-specific flush returned.
    pub durable_end: Option<LogSeq>,
    /// Records still retained for in-memory visibility.
    pub retained_records: usize,
    /// Encoded bytes still retained for in-memory visibility.
    pub retained_bytes: usize,
    /// Shared encoded record buffers created by successful staging calls.
    pub encoded_buffer_allocations: u64,
}

#[derive(Clone, Debug)]
struct Failure {
    kind: std::io::ErrorKind,
    detail: Arc<str>,
}

#[derive(Debug)]
struct WriterState {
    next_seq: u64,
    visible: VecDeque<VisibleRecord>,
    retained_bytes: usize,
    durable_end: Option<LogSeq>,
    pending_groups: VecDeque<Group>,
    spare_chunks: Vec<EncodedChunk>,
    barrier_in_flight: bool,
    failure: Option<Arc<Failure>>,
    completed_groups: u64,
    completed_records: u64,
    completed_bytes: u64,
    encoded_buffer_allocations: u64,
    group_size_histogram: GroupSizeHistogram,
    recent_groups: VecDeque<CompletedGroup>,
}

#[derive(Debug)]
struct EncodedChunk {
    encoded: Arc<Vec<u8>>,
    range: Range<usize>,
}

impl EncodedChunk {
    fn bytes(&self) -> std::io::Result<&[u8]> {
        self.encoded
            .get(self.range.clone())
            .ok_or_else(|| std::io::Error::other("invalid WAL pending chunk range"))
    }
}

#[derive(Debug)]
struct Group {
    chunks: Vec<EncodedChunk>,
    encoded_bytes: usize,
    records: usize,
    last_seq: Option<LogSeq>,
}

/// Single-store WAL writer using caller threads as leader and followers.
///
/// There is no timer and no background flusher. An idle arrival immediately
/// becomes leader. Arrivals observed while its barrier is in flight form the
/// next byte-bounded group, which that leader issues immediately afterward.
pub struct WalWriter {
    file: Mutex<Box<dyn VfsFile>>,
    created_directory_sync: Mutex<Option<CreatedDirectorySync>>,
    state: Mutex<WriterState>,
    changed: Condvar,
    sync: SyncRequirement,
    max_group_bytes: usize,
    durable_progress: AtomicU64,
    io_work: [AtomicU64; 4],
}

struct CreatedDirectorySync {
    vfs: Arc<dyn Vfs>,
    directory: PathBuf,
    kind: SyncKind,
}

impl WalWriter {
    /// Creates a writer over a new or empty WAL path.
    ///
    /// A resolved full-sync data-file requirement uses the 16 MiB durable group
    /// bound. Barrier and skip requirements retain the 1 MiB default.
    pub fn create(
        vfs: &dyn Vfs,
        path: &Path,
        first_seq: LogSeq,
        policy: DurabilityPolicy,
    ) -> Result<Self, WalWriteError> {
        let max_group_bytes = default_max_group_bytes(policy);
        Self::create_with_max_group_bytes(vfs, path, first_seq, policy, max_group_bytes)
    }

    pub(crate) fn resume(
        vfs: &dyn Vfs,
        path: &Path,
        recovered: CleanWalReader,
        policy: DurabilityPolicy,
    ) -> Result<Self, WalWriteError> {
        let max_group_bytes = default_max_group_bytes(policy);
        let next_seq = recovered.next_seq;
        let durable_end = recovered.durable_end;
        let durable_progress = durable_end.map_or(0, LogSeq::get);
        let visible = VecDeque::from(recovered.records);
        let retained_bytes = visible.iter().try_fold(0_usize, |total, record| {
            total
                .checked_add(record.encoded_len())
                .ok_or(WalWriteError::RecoveredBytesOverflow)
        })?;
        let file = vfs.open_append(path).map_err(WalWriteError::from_io)?;
        Ok(Self {
            file: Mutex::new(file),
            created_directory_sync: Mutex::new(None),
            state: Mutex::new(WriterState {
                next_seq,
                visible,
                retained_bytes,
                durable_end,
                pending_groups: VecDeque::with_capacity(2),
                spare_chunks: Vec::with_capacity(16),
                barrier_in_flight: false,
                failure: None,
                completed_groups: 0,
                completed_records: 0,
                completed_bytes: 0,
                encoded_buffer_allocations: 0,
                group_size_histogram: GroupSizeHistogram::new(),
                recent_groups: VecDeque::with_capacity(RECENT_GROUP_LIMIT),
            }),
            changed: Condvar::new(),
            sync: policy.data_file_sync(),
            max_group_bytes,
            durable_progress: AtomicU64::new(durable_progress),
            io_work: std::array::from_fn(|_| AtomicU64::new(0)),
        })
    }

    /// Creates a writer with an explicit encoded-byte group bound.
    pub fn create_with_max_group_bytes(
        vfs: &dyn Vfs,
        path: &Path,
        first_seq: LogSeq,
        policy: DurabilityPolicy,
        max_group_bytes: usize,
    ) -> Result<Self, WalWriteError> {
        match vfs.open(path) {
            Ok(0) => {}
            Ok(length) => return Err(WalWriteError::NonEmptyWal { length }),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(WalWriteError::from_io(error)),
        }
        let header = encode_header(first_seq).map_err(WalWriteError::Header)?;
        if max_group_bytes < header.len() {
            return Err(WalWriteError::GroupTooLarge {
                encoded_bytes: header.len(),
                max_group_bytes,
            });
        }
        let file = vfs.open_append(path).map_err(WalWriteError::from_io)?;
        let header_len = header.len();
        let header = Arc::new(header);
        let mut header_chunks = Vec::with_capacity(16);
        header_chunks.push(EncodedChunk {
            range: 0..header_len,
            encoded: header,
        });
        let mut pending_groups = VecDeque::with_capacity(2);
        pending_groups.push_back(Group {
            chunks: header_chunks,
            encoded_bytes: header_len,
            records: 0,
            last_seq: None,
        });
        let spare_chunks = Vec::with_capacity(16);
        let recent_groups = VecDeque::with_capacity(RECENT_GROUP_LIMIT);
        Ok(Self {
            file: Mutex::new(file),
            created_directory_sync: Mutex::new(None),
            state: Mutex::new(WriterState {
                next_seq: first_seq.get(),
                visible: VecDeque::new(),
                retained_bytes: 0,
                durable_end: None,
                pending_groups,
                spare_chunks,
                barrier_in_flight: false,
                failure: None,
                completed_groups: 0,
                completed_records: 0,
                completed_bytes: 0,
                encoded_buffer_allocations: 0,
                group_size_histogram: GroupSizeHistogram::new(),
                recent_groups,
            }),
            changed: Condvar::new(),
            sync: policy.data_file_sync(),
            max_group_bytes,
            durable_progress: AtomicU64::new(first_seq.get().saturating_sub(1)),
            io_work: std::array::from_fn(|_| AtomicU64::new(0)),
        })
    }

    pub(crate) fn create_store_wal(
        vfs: Arc<dyn Vfs>,
        directory: &Path,
        path: &Path,
        first_seq: LogSeq,
        policy: DurabilityPolicy,
    ) -> Result<Self, WalWriteError> {
        let mut writer = Self::create(vfs.as_ref(), path, first_seq, policy)?;
        if let SyncRequirement::Sync(kind) = policy.directory_sync() {
            writer.created_directory_sync = Mutex::new(Some(CreatedDirectorySync {
                vfs,
                directory: directory.to_path_buf(),
                kind,
            }));
        }
        Ok(writer)
    }

    /// Makes one record visible and returns without waiting when another
    /// caller already owns the in-flight barrier.
    pub fn commit(&self, op: u16, payload: &[u8]) -> Result<LogSeq, WalWriteError> {
        let (seq, leader) = self.stage(op, payload)?;
        if leader {
            self.flush_as_leader()?;
        }
        Ok(seq)
    }

    /// Makes one record visible, then waits until its tier-specific flush returns.
    pub fn commit_durable(&self, op: u16, payload: &[u8]) -> Result<LogSeq, WalWriteError> {
        let (seq, leader) = self.stage(op, payload)?;
        if leader {
            self.flush_as_leader()?;
        }
        self.wait_until_durable(seq)?;
        Ok(seq)
    }

    /// Makes every record in one caller batch visible in input order.
    ///
    /// Returns after every record is visible. As with [`Self::commit`], an
    /// idle caller that becomes leader runs the pending flushes inline before
    /// returning. An empty batch returns the empty range at the next sequence
    /// and performs no I/O.
    ///
    /// The returned half-open range contains exactly the assigned sequences.
    /// If staging fails, the batch consumes no sequence and publishes no
    /// visibility. After staging succeeds, an append or flush failure follows
    /// the existing poisoned-writer path: the staged records remain visible,
    /// this call returns [`WalWriteError::Failed`], and the writer rejects
    /// subsequent work.
    pub fn commit_many(&self, records: &[(u16, &[u8])]) -> Result<Range<LogSeq>, WalWriteError> {
        let (range, leader) = self.stage_many(records)?;
        if leader {
            self.flush_as_leader()?;
        }
        Ok(range)
    }

    /// Makes every record in one caller batch visible in input order, then
    /// waits until the tier-specific flush covering the final record returns.
    ///
    /// An empty batch returns the empty range at the next sequence and performs
    /// no I/O.
    ///
    /// The returned half-open range contains exactly the assigned sequences.
    /// If staging fails, the batch consumes no sequence and publishes no
    /// visibility. After staging succeeds, an append or flush failure follows
    /// the existing poisoned-writer path: the staged records remain visible,
    /// this call returns [`WalWriteError::Failed`], and the writer rejects
    /// subsequent work.
    pub fn commit_many_durable(
        &self,
        records: &[(u16, &[u8])],
    ) -> Result<Range<LogSeq>, WalWriteError> {
        let (range, leader) = self.stage_many(records)?;
        if leader {
            self.flush_as_leader()?;
        }
        if range.start != range.end {
            let last = LogSeq::new(range.end.get().saturating_sub(1));
            self.wait_until_durable(last)?;
        }
        Ok(range)
    }

    fn stage_many(&self, records: &[(u16, &[u8])]) -> Result<(Range<LogSeq>, bool), WalWriteError> {
        self.stage_many_with_encoder(records, append_record_into)
    }

    fn stage_many_with_encoder<F>(
        &self,
        records: &[(u16, &[u8])],
        mut encode: F,
    ) -> Result<(Range<LogSeq>, bool), WalWriteError>
    where
        F: for<'a> FnMut(WalRecord<'a>, &mut Vec<u8>) -> Result<(), RecordEncodeError>,
    {
        if records.is_empty() {
            let state = self.lock_state()?;
            if let Some(failure) = &state.failure {
                return Err(WalWriteError::failed(failure));
            }
            let next = LogSeq::new(state.next_seq);
            return Ok((next..next, false));
        }
        let encoded_lengths = records
            .iter()
            .map(|&(op, payload)| {
                let encoded_len =
                    encoded_record_len(payload.len()).map_err(WalWriteError::Record)?;
                Ok((op, payload, encoded_len))
            })
            .collect::<Result<Vec<_>, WalWriteError>>()?;
        let batch_bytes = encoded_lengths
            .iter()
            .fold(0_usize, |total, record| total.saturating_add(record.2));
        if let Some((_, _, encoded_bytes)) = encoded_lengths
            .iter()
            .find(|(_, _, encoded_bytes)| *encoded_bytes > self.max_group_bytes)
        {
            return Err(WalWriteError::GroupTooLarge {
                encoded_bytes: *encoded_bytes,
                max_group_bytes: self.max_group_bytes,
            });
        }
        let mut encoded = Arc::new(Vec::with_capacity(batch_bytes));
        let mut state = self.lock_state()?;
        if let Some(failure) = &state.failure {
            return Err(WalWriteError::failed(failure));
        }
        Self::ensure_pending_group(&mut state);
        let first_encoded_len = encoded_lengths
            .first()
            .map(|(_, _, encoded_len)| *encoded_len)
            .ok_or(WalWriteError::Poisoned("non-empty WAL batch"))?;
        let first_required = state
            .pending_groups
            .back()
            .map(|group| group.encoded_bytes.saturating_add(first_encoded_len))
            .ok_or(WalWriteError::Poisoned("pending WAL group"))?;
        if state
            .pending_groups
            .back()
            .is_some_and(|group| group.records == 0 && first_required > self.max_group_bytes)
        {
            return Err(WalWriteError::GroupTooLarge {
                encoded_bytes: first_required,
                max_group_bytes: self.max_group_bytes,
            });
        }
        let count = u64::try_from(records.len()).map_err(|_| WalWriteError::SequenceExhausted)?;
        let start = state.next_seq;
        let end = start
            .checked_add(count)
            .ok_or(WalWriteError::SequenceExhausted)?;
        let mut seq = start;
        let storage = Arc::get_mut(&mut encoded)
            .ok_or(WalWriteError::Poisoned("unique preallocated WAL batch"))?;
        for (op, payload, _) in &encoded_lengths {
            encode(
                WalRecord {
                    seq: LogSeq::new(seq),
                    op: *op,
                    payload,
                },
                storage,
            )
            .map_err(WalWriteError::Record)?;
            seq = seq.saturating_add(1);
        }

        seq = start;
        let mut offset = 0_usize;
        let mut chunk_start = 0_usize;
        for (op, _, encoded_len) in encoded_lengths {
            let record_seq = LogSeq::new(seq);
            let record_start = offset;
            let record_end = offset.saturating_add(encoded_len);
            while offset < record_end {
                let available = self
                    .max_group_bytes
                    .saturating_sub(Self::current_group_ref(&state)?.encoded_bytes);
                if available == 0 {
                    if chunk_start < offset {
                        let group = Self::current_group(&mut state)?;
                        group.chunks.push(EncodedChunk {
                            encoded: Arc::clone(&encoded),
                            range: chunk_start..offset,
                        });
                    }
                    Self::push_empty_pending_group(&mut state);
                    chunk_start = offset;
                    continue;
                }
                let written = available.min(record_end.saturating_sub(offset));
                let group = Self::current_group(&mut state)?;
                group.encoded_bytes = group.encoded_bytes.saturating_add(written);
                offset = offset.saturating_add(written);
            }
            let group = Self::current_group(&mut state)?;
            group.records = group.records.saturating_add(1);
            group.last_seq = Some(record_seq);
            state.retained_bytes = state.retained_bytes.saturating_add(encoded_len);
            state.visible.push_back(VisibleRecord::writer_owned(
                record_seq,
                op,
                Arc::clone(&encoded),
                record_start..record_end,
            ));
            seq = seq.saturating_add(1);
        }
        let group = Self::current_group(&mut state)?;
        group.chunks.push(EncodedChunk {
            encoded,
            range: chunk_start..offset,
        });
        state.next_seq = end;
        state.encoded_buffer_allocations = state.encoded_buffer_allocations.saturating_add(1);
        let leader = !state.barrier_in_flight;
        if leader {
            state.barrier_in_flight = true;
        }
        Ok((LogSeq::new(start)..LogSeq::new(end), leader))
    }

    #[inline(always)]
    fn current_group(state: &mut WriterState) -> Result<&mut Group, WalWriteError> {
        state
            .pending_groups
            .back_mut()
            .ok_or(WalWriteError::Poisoned("pending WAL group"))
    }

    #[inline(always)]
    fn current_group_ref(state: &WriterState) -> Result<&Group, WalWriteError> {
        state
            .pending_groups
            .back()
            .ok_or(WalWriteError::Poisoned("pending WAL group"))
    }

    fn ensure_pending_group(state: &mut WriterState) {
        if state.pending_groups.is_empty() {
            Self::push_empty_pending_group(state);
        }
    }

    fn push_empty_pending_group(state: &mut WriterState) {
        let chunks = std::mem::take(&mut state.spare_chunks);
        state.pending_groups.push_back(Group {
            chunks,
            encoded_bytes: 0,
            records: 0,
            last_seq: None,
        });
    }

    /// Permanently fails this writer after its file was replaced underneath it,
    /// so every later commit reports `error` instead of appending to a file
    /// that recovery will never read.
    pub(crate) fn poison(&self, error: &std::io::Error) -> Result<(), WalWriteError> {
        let mut state = self.lock_state()?;
        state.failure.get_or_insert_with(|| {
            Arc::new(Failure {
                kind: error.kind(),
                detail: Arc::from(error.to_string()),
            })
        });
        self.changed.notify_all();
        Ok(())
    }

    /// Waits until every record visible when this call observes the writer has flushed.
    ///
    /// No record is appended solely to force progress. If pending records have
    /// no current leader, this caller assumes leadership and drains them.
    pub fn flush(&self) -> Result<(), WalWriteError> {
        let (target, leader) = {
            let mut state = self.lock_state()?;
            if let Some(failure) = &state.failure {
                return Err(WalWriteError::failed(failure));
            }
            let Some(target) = state.visible.back().map(|record| record.seq) else {
                return Ok(());
            };
            if state
                .durable_end
                .is_some_and(|durable_end| durable_end >= target)
            {
                return Ok(());
            }
            let leader = if state.barrier_in_flight {
                false
            } else if state.pending_groups.iter().any(|group| group.records != 0) {
                state.barrier_in_flight = true;
                true
            } else {
                return Err(WalWriteError::Poisoned(
                    "non-durable WAL record has neither a pending group nor a leader",
                ));
            };
            (target, leader)
        };
        if leader {
            self.flush_as_leader()?;
        }
        self.wait_until_durable(target)
    }

    /// Returns at most `limit` retained records at or after `first_seq`.
    ///
    /// Clones share the encoded WAL allocations. The explicit bound prevents
    /// test-support callers from copying metadata for the writer's history.
    pub fn visible_records(
        &self,
        first_seq: LogSeq,
        limit: usize,
    ) -> Result<Vec<VisibleRecord>, WalWriteError> {
        let mut visible = Vec::with_capacity(limit);
        let state = self.lock_state()?;
        visible.extend(
            state
                .visible
                .iter()
                .filter(|record| record.seq >= first_seq)
                .take(limit)
                .cloned(),
        );
        Ok(visible)
    }

    /// Releases retained visibility records through an absorbed durable sequence.
    ///
    /// The ingest owner calls this only after incorporating the records into
    /// its own in-memory state. Requests beyond the tier-specific durable end
    /// fail explicitly and never clamp.
    pub fn retire_visible_through(
        &self,
        absorbed_through: LogSeq,
    ) -> Result<WalRetirement, WalRetireError> {
        let capacity = {
            let state = self.lock_state().map_err(WalRetireError::Writer)?;
            if state
                .durable_end
                .is_none_or(|durable_end| absorbed_through > durable_end)
            {
                return Err(WalRetireError::BeyondDurable {
                    requested: absorbed_through,
                    durable_end: state.durable_end,
                });
            }
            state
                .visible
                .iter()
                .take_while(|record| record.seq <= absorbed_through)
                .count()
        };
        let mut retired = Vec::with_capacity(capacity);
        let retirement = {
            let mut state = self.lock_state().map_err(WalRetireError::Writer)?;
            if state
                .durable_end
                .is_none_or(|durable_end| absorbed_through > durable_end)
            {
                return Err(WalRetireError::BeyondDurable {
                    requested: absorbed_through,
                    durable_end: state.durable_end,
                });
            }
            while state
                .visible
                .front()
                .is_some_and(|record| record.seq <= absorbed_through)
            {
                let Some(record) = state.visible.pop_front() else {
                    break;
                };
                state.retained_bytes = state.retained_bytes.saturating_sub(record.encoded_len());
                retired.push(record);
            }
            WalRetirement {
                absorbed_through,
                records_released: retired.len(),
                encoded_bytes_released: retired.iter().fold(0_usize, |total, record| {
                    total.saturating_add(record.encoded_len())
                }),
                retained_records: state.visible.len(),
                retained_bytes: state.retained_bytes,
                durable_end: state.durable_end,
            }
        };
        drop(retired);
        Ok(retirement)
    }

    /// Returns deterministic progress and completed-group statistics.
    pub fn stats(&self) -> Result<WalWriterStats, WalWriteError> {
        let mut recent_groups = Vec::with_capacity(RECENT_GROUP_LIMIT);
        let state = self.lock_state()?;
        recent_groups.extend(state.recent_groups.iter().copied());
        let pending_records = state
            .pending_groups
            .iter()
            .fold(0_usize, |total, group| total.saturating_add(group.records));
        Ok(WalWriterStats {
            completed_groups: state.completed_groups,
            completed_records: state.completed_records,
            completed_bytes: state.completed_bytes,
            group_size_histogram: state.group_size_histogram,
            recent_groups,
            pending_records,
            visible_end: state.visible.back().map(|record| record.seq),
            durable_end: state.durable_end,
            retained_records: state.visible.len(),
            retained_bytes: state.retained_bytes,
            encoded_buffer_allocations: state.encoded_buffer_allocations,
        })
    }

    fn stage(&self, op: u16, payload: &[u8]) -> Result<(LogSeq, bool), WalWriteError> {
        let encoded_len = encoded_record_len(payload.len()).map_err(WalWriteError::Record)?;
        let mut encoded = Arc::new(Vec::with_capacity(encoded_len));
        let mut state = self.lock_state()?;
        loop {
            if let Some(failure) = &state.failure {
                return Err(WalWriteError::failed(failure));
            }
            Self::ensure_pending_group(&mut state);
            let seq = LogSeq::new(state.next_seq);
            let (required, pending_records) = state
                .pending_groups
                .back()
                .map(|group| {
                    (
                        group.encoded_bytes.saturating_add(encoded_len),
                        group.records,
                    )
                })
                .ok_or(WalWriteError::Poisoned("pending WAL group"))?;
            if required <= self.max_group_bytes {
                let next_seq = state
                    .next_seq
                    .checked_add(1)
                    .ok_or(WalWriteError::SequenceExhausted)?;
                let storage = Arc::get_mut(&mut encoded)
                    .ok_or(WalWriteError::Poisoned("unique preallocated WAL record"))?;
                encode_record_into(WalRecord { seq, op, payload }, storage)
                    .map_err(WalWriteError::Record)?;
                state.next_seq = next_seq;
                state.encoded_buffer_allocations =
                    state.encoded_buffer_allocations.saturating_add(1);
                let group = state
                    .pending_groups
                    .back_mut()
                    .ok_or(WalWriteError::Poisoned("pending WAL group"))?;
                group.chunks.push(EncodedChunk {
                    encoded: Arc::clone(&encoded),
                    range: 0..encoded_len,
                });
                group.encoded_bytes = required;
                group.records = group.records.saturating_add(1);
                group.last_seq = Some(seq);
                state.retained_bytes = state.retained_bytes.saturating_add(encoded_len);
                state.visible.push_back(VisibleRecord::writer_owned(
                    seq,
                    op,
                    encoded,
                    0..encoded_len,
                ));
                let leader = !state.barrier_in_flight;
                if leader {
                    state.barrier_in_flight = true;
                }
                return Ok((seq, leader));
            }
            if pending_records == 0 {
                return Err(WalWriteError::GroupTooLarge {
                    encoded_bytes: required,
                    max_group_bytes: self.max_group_bytes,
                });
            }
            state = self
                .changed
                .wait(state)
                .map_err(|_| WalWriteError::Poisoned("WAL state mutex"))?;
        }
    }

    fn flush_as_leader(&self) -> Result<(), WalWriteError> {
        loop {
            let (group, last_seq) = {
                let mut state = self.lock_state()?;
                let group = state
                    .pending_groups
                    .pop_front()
                    .ok_or(WalWriteError::Poisoned("WAL leader found no pending group"))?;
                let last_seq = group.last_seq.ok_or(WalWriteError::Poisoned(
                    "WAL leader found no pending sequence",
                ))?;
                self.changed.notify_all();
                (group, last_seq)
            };
            let failure = self.write_group(&group).err().map(|error| {
                Arc::new(Failure {
                    kind: error.kind(),
                    detail: Arc::from(error.to_string()),
                })
            });
            let completed = CompletedGroup {
                records: group.records,
                encoded_bytes: group.encoded_bytes,
            };
            let mut reusable_chunks = group.chunks;
            reusable_chunks.clear();
            let mut state = self.lock_state()?;
            state.spare_chunks = reusable_chunks;
            match failure {
                None => {
                    state.durable_end = Some(last_seq);
                    self.durable_progress
                        .store(last_seq.get(), Ordering::Release);
                    state.completed_groups = state.completed_groups.saturating_add(1);
                    state.completed_records = state
                        .completed_records
                        .saturating_add(completed.records as u64);
                    state.completed_bytes = state
                        .completed_bytes
                        .saturating_add(completed.encoded_bytes as u64);
                    state.group_size_histogram.record(completed.records);
                    if state.recent_groups.len() == RECENT_GROUP_LIMIT {
                        state.recent_groups.pop_front();
                    }
                    state.recent_groups.push_back(completed);
                    self.changed.notify_all();
                    if state.pending_groups.is_empty() {
                        state.barrier_in_flight = false;
                        return Ok(());
                    }
                }
                Some(failure) => {
                    state.failure = Some(Arc::clone(&failure));
                    state.barrier_in_flight = false;
                    self.changed.notify_all();
                    return Err(WalWriteError::failed(&failure));
                }
            }
        }
    }

    #[cfg(feature = "graph-cypher")]
    pub(crate) fn io_work(&self) -> [u64; 4] {
        std::array::from_fn(|index| {
            self.io_work
                .get(index)
                .map_or(0, |counter| counter.load(Ordering::Relaxed))
        })
    }

    /// Pending bytes (including a fresh header) and the actual group cap.
    #[cfg(feature = "graph-cypher")]
    pub(crate) fn atomic_run_bound(&self) -> Result<(usize, usize), WalWriteError> {
        let state = self.lock_state()?;
        let pending = state.pending_groups.iter().fold(0_usize, |sum, group| {
            sum.saturating_add(group.encoded_bytes)
        });
        Ok((pending, self.max_group_bytes))
    }

    fn write_group(&self, group: &Group) -> std::io::Result<()> {
        let mut buffers = Vec::with_capacity(group.chunks.len());
        for chunk in &group.chunks {
            buffers.push(IoSlice::new(chunk.bytes()?));
        }
        let mut file = self
            .file
            .lock()
            .map_err(|_| std::io::Error::other("WAL file mutex poisoned"))?;
        if let Some(counter) = self.io_work.first() {
            counter.fetch_add(1, Ordering::Relaxed);
        }
        file.append_vectored(&mut buffers)?;
        if let Some(counter) = self.io_work.get(1) {
            counter.fetch_add(group.encoded_bytes as u64, Ordering::Relaxed);
        }
        match self.sync {
            SyncRequirement::Skip => Ok(()),
            SyncRequirement::Sync(kind) => {
                if kind == SyncKind::Full
                    && let Some(counter) = self.io_work.get(2)
                {
                    counter.fetch_add(1, Ordering::Relaxed);
                }
                let result = file.sync(kind);
                if kind == SyncKind::Full
                    && result.is_ok()
                    && let Some(counter) = self.io_work.get(3)
                {
                    counter.fetch_add(1, Ordering::Relaxed);
                }
                result
            }
        }?;
        drop(file);
        let mut created_directory_sync = self
            .created_directory_sync
            .lock()
            .map_err(|_| std::io::Error::other("WAL directory-sync mutex poisoned"))?;
        if let Some(sync) = created_directory_sync.as_ref() {
            sync.vfs.sync(&sync.directory, sync.kind)?;
            created_directory_sync.take();
        }
        Ok(())
    }

    fn wait_until_durable(&self, seq: LogSeq) -> Result<(), WalWriteError> {
        let mut state = self.lock_state()?;
        while state
            .durable_end
            .is_none_or(|durable_end| durable_end < seq)
        {
            if let Some(failure) = &state.failure {
                return Err(WalWriteError::failed(failure));
            }
            state = self
                .changed
                .wait(state)
                .map_err(|_| WalWriteError::Poisoned("WAL state mutex"))?;
        }
        Ok(())
    }

    fn lock_state(&self) -> Result<MutexGuard<'_, WriterState>, WalWriteError> {
        self.state
            .lock()
            .map_err(|_| WalWriteError::Poisoned("WAL state mutex"))
    }
}

pub(crate) fn encode_wal_image(
    first_seq: LogSeq,
    records: &[(u16, Vec<u8>)],
) -> Result<Vec<u8>, WalWriteError> {
    let mut encoded = header::encode_header(first_seq).map_err(WalWriteError::Header)?;
    let mut sequence = first_seq.get();
    for (op, payload) in records {
        record::append_record_into(
            record::WalRecord {
                seq: LogSeq::new(sequence),
                op: *op,
                payload,
            },
            &mut encoded,
        )
        .map_err(WalWriteError::Record)?;
        sequence = sequence
            .checked_add(1)
            .ok_or(WalWriteError::SequenceExhausted)?;
    }
    Ok(encoded)
}

fn default_max_group_bytes(policy: DurabilityPolicy) -> usize {
    match policy.data_file_sync() {
        SyncRequirement::Sync(SyncKind::Full) => DEFAULT_MAX_GROUP_BYTES_DURABLE,
        SyncRequirement::Skip | SyncRequirement::Sync(SyncKind::Barrier) => DEFAULT_MAX_GROUP_BYTES,
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use std::path::Path;

    use super::{LogSeq, RecordEncodeError, WalWriteError, WalWriter, append_record_into};
    use crate::lifecycle::durability::{CommitTier, DurabilityMode, DurabilityPolicy};
    use crate::vfs::CountingVfs;
    use crate::vfs::crash::MemoryVfs;

    #[test]
    fn durable_policy_defaults_to_a_sixteen_mib_group_cap() {
        let counting = CountingVfs::new(MemoryVfs::new());
        let policy = DurabilityPolicy::new(DurabilityMode::Durable, CommitTier::Durable)
            .expect("durable policy");
        let writer = WalWriter::create(
            &counting,
            Path::new("/wal/default-durable-cap.ze"),
            LogSeq::new(1),
            policy,
        )
        .expect("writer");
        let payload = vec![0x5a; 1_024];
        let records = (0..1_024)
            .map(|_| (7, payload.as_slice()))
            .collect::<Vec<_>>();

        writer.commit_many(&records).expect("large durable batch");
        let stats = writer.stats().expect("writer stats");

        assert_eq!(
            (
                counting.append_calls(),
                counting.handle_full_sync_calls(),
                stats.completed_groups,
                stats.completed_records,
            ),
            (1, 1, 1, 1_024),
            "a 1,071,144-byte durable batch must share one append and full sync"
        );
    }

    #[test]
    fn ordered_and_skip_policies_keep_the_one_mib_default() {
        let payload = vec![0x6b; 1_024];
        let records = (0..1_024)
            .map(|_| (8, payload.as_slice()))
            .collect::<Vec<_>>();
        let mut actual = Vec::new();

        for (tier, path) in [
            (CommitTier::Ordered, "/wal/default-ordered-cap.ze"),
            (CommitTier::None, "/wal/default-skip-cap.ze"),
        ] {
            let counting = CountingVfs::new(MemoryVfs::new());
            let policy =
                DurabilityPolicy::new(DurabilityMode::Durable, tier).expect("supported policy");
            let writer = WalWriter::create(&counting, Path::new(path), LogSeq::new(1), policy)
                .expect("writer");

            writer.commit_many(&records).expect("large batch");
            let stats = writer.stats().expect("writer stats");
            actual.push((
                tier,
                counting.append_calls(),
                counting.handle_barrier_sync_calls(),
                counting.handle_full_sync_calls(),
                stats.completed_groups,
            ));
        }

        assert_eq!(
            actual,
            vec![
                (CommitTier::Ordered, 2, 2, 0, 2),
                (CommitTier::None, 2, 0, 0, 2),
            ],
            "ordered and skip policies must split a 1,071,144-byte batch at one MiB"
        );
    }

    #[test]
    fn an_explicit_group_cap_still_wins() {
        let counting = CountingVfs::new(MemoryVfs::new());
        let policy = DurabilityPolicy::new(DurabilityMode::Durable, CommitTier::Durable)
            .expect("durable policy");
        let writer = WalWriter::create_with_max_group_bytes(
            &counting,
            Path::new("/wal/explicit-group-cap.ze"),
            LogSeq::new(1),
            policy,
            128,
        )
        .expect("writer");
        writer.commit(0, &[0; 10]).expect("flush WAL header");
        let groups_before = writer.stats().expect("prime stats").recent_groups.len();
        counting.reset();
        let payload = [0x7c; 10];
        let records = (0..12).map(|_| (9, payload.as_slice())).collect::<Vec<_>>();

        writer.commit_many(&records).expect("explicit-cap batch");
        let stats = writer.stats().expect("batch stats");
        let groups = stats
            .recent_groups
            .iter()
            .skip(groups_before)
            .map(|group| (group.records, group.encoded_bytes))
            .collect::<Vec<_>>();

        assert_eq!(
            (
                counting.append_calls(),
                counting.handle_full_sync_calls(),
                groups,
            ),
            (3, 3, vec![(4, 128), (4, 128), (4, 128)]),
            "an explicit 128-byte cap must override the durable default"
        );
    }

    #[test]
    fn encoding_failure_in_middle_of_commit_many_is_atomic() {
        let policy = DurabilityPolicy::new(DurabilityMode::Durable, CommitTier::None)
            .expect("supported policy");
        let writer = WalWriter::create(
            &MemoryVfs::new(),
            Path::new("/wal/unit-encode-failure.ze"),
            LogSeq::new(1),
            policy,
        )
        .expect("writer");
        let records = [(51, b"first".as_slice()), (52, b"second".as_slice())];
        let mut encode_calls = 0_usize;

        let result = writer.stage_many_with_encoder(&records, |record, storage| {
            encode_calls = encode_calls.saturating_add(1);
            if encode_calls == 2 {
                Err(RecordEncodeError::PayloadTooLarge(usize::MAX))
            } else {
                append_record_into(record, storage)
            }
        });
        let failure = match result {
            Err(WalWriteError::Record(error)) => format!("error={error}"),
            other => format!("unexpected={other:?}"),
        };
        let visible = writer
            .visible_records(LogSeq::new(1), records.len())
            .expect("visibility after failed encoding")
            .len();
        let next = writer
            .commit(53, b"after")
            .expect("sequence remains reusable");

        assert_eq!(
            (failure, visible, next),
            (
                format!("error=WAL payload length {} exceeds u32", usize::MAX),
                0,
                LogSeq::new(1),
            ),
            "a failure encoding any batch record must consume no sequence and publish no visibility"
        );
    }
}

impl DurableLog for WalWriter {
    fn durable_end(&self) -> u64 {
        self.durable_progress.load(Ordering::Acquire)
    }
}

/// Checked access failure for a retained encoded record.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VisibleRecordError {
    /// The retained range does not fit its shared encoded allocation.
    InvalidEncodedRange {
        /// Inclusive byte offset.
        start: usize,
        /// Exclusive byte offset.
        end: usize,
        /// Bytes available in the allocation.
        available: usize,
    },
    /// The retained bytes no longer decode as the record published by the writer.
    Record(RecordError),
}

impl std::fmt::Display for VisibleRecordError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidEncodedRange {
                start,
                end,
                available,
            } => write!(
                formatter,
                "visible WAL encoded range {start}..{end} exceeds {available} bytes"
            ),
            Self::Record(error) => write!(formatter, "visible WAL record: {error}"),
        }
    }
}

impl std::error::Error for VisibleRecordError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidEncodedRange { .. } => None,
            Self::Record(error) => Some(error),
        }
    }
}

/// Exact effect of one visibility-retirement request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WalRetirement {
    /// Caller-declared sequence absorbed into its own in-memory state.
    pub absorbed_through: LogSeq,
    /// Retained records released by this call.
    pub records_released: usize,
    /// Encoded record bytes released by this call.
    pub encoded_bytes_released: usize,
    /// Records that remain retained by the writer.
    pub retained_records: usize,
    /// Encoded record bytes that remain retained by the writer.
    pub retained_bytes: usize,
    /// Durable end observed while applying retirement.
    pub durable_end: Option<LogSeq>,
}

/// Visibility retirement failure.
#[derive(Debug)]
pub enum WalRetireError {
    /// The caller asked to retire bytes whose tier-specific flush has not returned.
    BeyondDurable {
        /// Requested inclusive retirement sequence.
        requested: LogSeq,
        /// Largest sequence whose flush returned.
        durable_end: Option<LogSeq>,
    },
    /// Writer state could not be inspected safely.
    Writer(WalWriteError),
}

impl std::fmt::Display for WalRetireError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BeyondDurable {
                requested,
                durable_end: Some(durable_end),
            } => write!(
                formatter,
                "cannot retire WAL sequence {} past durable end {}",
                requested.get(),
                durable_end.get()
            ),
            Self::BeyondDurable {
                requested,
                durable_end: None,
            } => write!(
                formatter,
                "cannot retire WAL sequence {} before any sequence is durable",
                requested.get()
            ),
            Self::Writer(error) => write!(formatter, "cannot retire visible WAL records: {error}"),
        }
    }
}

impl std::error::Error for WalRetireError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::BeyondDurable { .. } => None,
            Self::Writer(error) => Some(error),
        }
    }
}

/// Owned checked WAL prefix recovered from a filesystem image.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WalReader {
    records: Vec<VisibleRecord>,
    next_seq: u64,
    durable_end: u64,
    terminator: Option<ReplayTerminator>,
}

pub(crate) struct CleanWalReader {
    records: Vec<VisibleRecord>,
    next_seq: u64,
    durable_end: Option<LogSeq>,
}

impl CleanWalReader {
    pub(crate) fn durable_end(&self) -> u64 {
        self.durable_end.map_or(0, LogSeq::get)
    }

    #[cfg(feature = "graph-cypher")]
    pub(crate) fn retained_first_seq(&self) -> u64 {
        self.records
            .first()
            .map_or(self.next_seq, |record| record.seq.get())
    }

    pub(crate) fn records(&self) -> &[VisibleRecord] {
        &self.records
    }
}

impl WalReader {
    /// Opens the largest checksum- and sequence-valid WAL prefix.
    pub fn open(vfs: &dyn Vfs, path: &Path) -> Result<Self, WalReadError> {
        let bytes = match vfs.read(path) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(Self {
                    records: Vec::new(),
                    next_seq: 0,
                    durable_end: 0,
                    terminator: None,
                });
            }
            Err(error) => return Err(WalReadError::Io(error)),
        };
        let replayed = replay(&bytes);
        let terminator = replayed.terminator;
        if matches!(terminator, ReplayTerminator::InvalidHeader(_)) {
            return Ok(Self {
                records: Vec::new(),
                next_seq: 0,
                durable_end: 0,
                terminator: Some(terminator),
            });
        }
        let header = header::decode_header(&bytes).map_err(WalReadError::Header)?;
        let mut offset = header::WAL_HEADER_LEN;
        let recovered = replayed
            .records
            .iter()
            .map(|record| {
                let encoded_len = record::MIN_RECORD_LEN.saturating_add(record.payload.len());
                let range = offset..offset.saturating_add(encoded_len);
                offset = range.end;
                (record.seq, record.op, range)
            })
            .collect::<Vec<_>>();
        drop(replayed);
        let records = recovered
            .into_iter()
            .map(|(seq, op, range)| {
                let start = range.start;
                let end = range.end;
                let encoded = bytes
                    .get(range)
                    .ok_or(WalReadError::InvalidRecoveredRange {
                        start,
                        end,
                        available: bytes.len(),
                    })?;
                let encoded = Arc::new(encoded.to_vec());
                let length = encoded.len();
                Ok(VisibleRecord::recovered(seq, op, encoded, 0..length))
            })
            .collect::<Result<Vec<_>, WalReadError>>()?;
        let durable_end = records.last().map_or_else(
            || header.first_seq.get().saturating_sub(1),
            |record| record.seq.get(),
        );
        let next_seq = records.last().map_or(header.first_seq.get(), |record| {
            record.seq.get().saturating_add(1)
        });
        Ok(Self {
            records,
            next_seq,
            durable_end,
            terminator: Some(terminator),
        })
    }

    /// Returns the recovered ordered prefix.
    #[must_use]
    pub fn records(&self) -> &[VisibleRecord] {
        &self.records
    }

    /// Returns the checked replay boundary, or `None` when no WAL path existed.
    #[must_use]
    pub const fn terminator(&self) -> Option<ReplayTerminator> {
        self.terminator
    }

    #[cfg(feature = "graph-cypher")]
    pub(crate) fn into_graph_prefix(mut self) -> Result<CleanWalReader, WalRecoveryError> {
        if matches!(
            self.terminator,
            Some(ReplayTerminator::CorruptAt {
                reason: replay::CorruptionReason::Record {
                    location: replay::CorruptionLocation::Tail,
                    error: RecordError::BodyTruncated { needed, .. },
                },
                ..
            }) if needed <= DEFAULT_MAX_GROUP_BYTES_DURABLE
        ) {
            self.terminator = Some(ReplayTerminator::CleanEnd);
        }
        self.into_clean()
    }

    pub(crate) fn into_clean(self) -> Result<CleanWalReader, WalRecoveryError> {
        match self.terminator {
            Some(ReplayTerminator::CleanEnd) => {
                let durable_end = Some(LogSeq::new(self.durable_end));
                Ok(CleanWalReader {
                    records: self.records,
                    next_seq: self.next_seq,
                    durable_end,
                })
            }
            Some(ReplayTerminator::InvalidHeader(error)) => {
                let error = WalRecoveryError::InvalidHeader(error);
                #[cfg(any(test, feature = "test-seams"))]
                crate::lifecycle::record_storage_wal_recovery_fault(&error);
                Err(error)
            }
            Some(ReplayTerminator::CorruptAt { offset, reason }) => {
                let error = WalRecoveryError::CorruptAt { offset, reason };
                #[cfg(any(test, feature = "test-seams"))]
                crate::lifecycle::record_storage_wal_recovery_fault(&error);
                Err(error)
            }
            None => Err(WalRecoveryError::MissingFile),
        }
    }
}

impl DurableLog for WalReader {
    fn durable_end(&self) -> u64 {
        self.durable_end
    }
}

/// WAL creation, staging, or group-flush failure.
#[derive(Debug)]
pub enum WalWriteError {
    /// The requested path already contains WAL bytes.
    NonEmptyWal {
        /// Existing byte length.
        length: u64,
    },
    /// Recovered record byte accounting exceeded the address space.
    RecoveredBytesOverflow,
    /// One encoded record cannot fit the configured byte bound.
    GroupTooLarge {
        /// Bytes required by the pending group and record.
        encoded_bytes: usize,
        /// Configured maximum.
        max_group_bytes: usize,
    },
    /// The u64 sequence space has no successor.
    SequenceExhausted,
    /// WAL header registry lookup failed.
    Header(RegistryError),
    /// Record framing failed.
    Record(RecordEncodeError),
    /// A shared writer mutex was poisoned.
    Poisoned(&'static str),
    /// The writer failed permanently after visibility was published.
    Failed {
        /// Underlying I/O error class.
        kind: std::io::ErrorKind,
        /// Stable error detail retained for followers.
        detail: Arc<str>,
    },
}

impl WalWriteError {
    fn from_io(error: std::io::Error) -> Self {
        Self::Failed {
            kind: error.kind(),
            detail: Arc::from(error.to_string()),
        }
    }

    fn failed(failure: &Failure) -> Self {
        Self::Failed {
            kind: failure.kind,
            detail: Arc::clone(&failure.detail),
        }
    }
}

impl std::fmt::Display for WalWriteError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NonEmptyWal { length } => {
                write!(formatter, "WAL path is not empty: {length} bytes")
            }
            Self::RecoveredBytesOverflow => {
                formatter.write_str("recovered WAL record bytes overflow usize")
            }
            Self::GroupTooLarge {
                encoded_bytes,
                max_group_bytes,
            } => write!(
                formatter,
                "WAL group needs {encoded_bytes} bytes, exceeding {max_group_bytes}"
            ),
            Self::SequenceExhausted => formatter.write_str("WAL sequence space exhausted"),
            Self::Header(error) => write!(formatter, "WAL header: {error}"),
            Self::Record(error) => write!(formatter, "WAL record: {error}"),
            Self::Poisoned(detail) => write!(formatter, "{detail} poisoned"),
            Self::Failed { kind, detail } => {
                write!(formatter, "WAL writer failed with {:?}: {}", kind, detail)
            }
        }
    }
}

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

/// A non-empty WAL cannot be resumed because replay did not reach a clean end.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WalRecoveryError {
    /// The requested WAL path did not exist and therefore cannot be resumed.
    MissingFile,
    /// The persisted WAL header is absent, truncated, or invalid.
    InvalidHeader(header::WalHeaderError),
    /// Record replay stopped at a typed corruption boundary.
    CorruptAt {
        /// Byte offset of the first invalid record.
        offset: usize,
        /// Exact framing, checksum, or sequence failure.
        reason: replay::CorruptionReason,
    },
}

impl std::fmt::Display for WalRecoveryError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingFile => formatter.write_str("WAL recovery path is missing"),
            Self::InvalidHeader(error) => write!(formatter, "WAL recovery header: {error}"),
            Self::CorruptAt { offset, reason } => {
                write!(
                    formatter,
                    "WAL recovery stopped at byte {offset}: {reason:?}"
                )
            }
        }
    }
}

impl std::error::Error for WalRecoveryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidHeader(error) => Some(error),
            Self::MissingFile | Self::CorruptAt { .. } => None,
        }
    }
}

/// WAL recovery failure requiring the caller to stop rather than hide corruption.
#[derive(Debug)]
pub enum WalReadError {
    /// Filesystem read failed.
    Io(std::io::Error),
    /// A header accepted by replay could not be decoded for resume state.
    Header(header::WalHeaderError),
    /// A replay-derived encoded record range exceeded the WAL image.
    InvalidRecoveredRange {
        /// First encoded byte of the recovered record.
        start: usize,
        /// Exclusive end of the recovered record.
        end: usize,
        /// Complete WAL image length.
        available: usize,
    },
}

impl std::fmt::Display for WalReadError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(error) => write!(formatter, "WAL read: {error}"),
            Self::Header(error) => write!(formatter, "WAL read header: {error}"),
            Self::InvalidRecoveredRange {
                start,
                end,
                available,
            } => write!(
                formatter,
                "WAL recovered range {start}..{end} exceeds {available} bytes"
            ),
        }
    }
}

impl std::error::Error for WalReadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::Header(error) => Some(error),
            Self::InvalidRecoveredRange { .. } => None,
        }
    }
}