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
//! The fold — an append-only, content-addressed piece store with block compression.
//!
//! Identical bytes are stored once, forever, wherever they appear. Everything above the fold refers to
//! content by [`Loc`], and **nothing above the fold ever rewrites it**: merges reorganize references
//! and columns, never content. That is what decouples compaction cost from data volume.
//!
//! # Two units, deliberately separated
//!
//! A **piece** is the unit of identity and dedup. A **block** is the unit of compression and I/O.
//! Pieces accumulate in an open buffer; at the configured block target the buffer is compressed as one
//! block and appended. This captures the cross-piece redundancy that dominates trace data, and because
//! a record's pieces are captured together they land in a handful of blocks — so reconstructing a
//! record costs a few large decompressions instead of dozens of tiny ones. Measured on two real
//! corpora, this is both smaller on disk and faster per record than framing each piece alone.
//!
//! # The durability contract, in one sentence
//!
//! No part may be committed naming a [`Loc`] at or beyond a tail that [`Fold::sync`] has not returned.
//!
//! The fold is deliberately *not* a commit point. The WAL makes a record's carved pieces durable before
//! the fold is touched, so a crash between a `put` and a `sync` loses nothing replay cannot regenerate
//! — which is why `put` never fsyncs. It is also why `sync` must stay tied to flush boundaries rather
//! than to individual records: every `sync` seals the open block early, and blocks sealed short
//! compress worse.
pub mod block;
pub mod codec;
pub mod dedup;
pub mod pipe;
pub mod segment;
pub use block::{Loc, BLOCK_TARGET_DEFAULT, CODEC_STORED, CODEC_ZSTD, CODEC_ZSTD_DICT};
pub use segment::FoldTail;
use crate::readat::{ReadAt, Slice};
use crate::types::PieceHash;
use anyhow::{bail, Context, Result};
use dedup::DedupTable;
use segment::{SegHeader, SEG_HDR_LEN, SEG_MAX_DEFAULT, SEG_MAX_LIMIT};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub const SEGMENT_MAX_DEFAULT: u32 = SEG_MAX_DEFAULT;
pub const SEGMENT_MAX_LIMIT: u64 = SEG_MAX_LIMIT;
pub const BLOCK_TARGET_MAX: u64 = (u32::MAX as u64) / 2;
/// Candidate dictionary bytes admitted during open. Zstd dictionaries are normally measured in
/// KiB; this generous ceiling prevents an unrelated sparse file with a dictionary-shaped name from
/// becoming an unbounded allocation.
pub const MAX_DICTIONARY_BYTES: u64 = 64 << 20;
fn read_bounded_candidate(path: &Path, max: u64) -> Result<Vec<u8>> {
let file = File::open(path)?;
let len = file.metadata()?.len();
if len > max {
bail!("candidate file {} is {len} bytes, exceeding the {max}-byte limit", path.display());
}
let capacity =
usize::try_from(len).context("candidate file length does not fit this platform")?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(capacity).context("reserve candidate file buffer")?;
file.take(max + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > max {
bail!("candidate file {} grew past the {max}-byte limit while reading", path.display());
}
Ok(bytes)
}
/// Another writer currently owns this fold's OS lock.
///
/// This is a typed operational condition rather than prose so bindings can expose stable contention
/// handling without matching an error message. It says nothing about WASI, where the platform lacks
/// an advisory lock and the embedder owns exclusion.
#[derive(Debug)]
pub struct WriterLocked {
pub path: PathBuf,
}
impl std::fmt::Display for WriterLocked {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "fold at {} is already open by another writer", self.path.display())
}
}
impl std::error::Error for WriterLocked {}
#[derive(Clone, Copy, Debug)]
pub struct FoldCfg {
/// Roll threshold. Bounded by [`SEG_MAX_LIMIT`] because `Loc.block_off` is a u32.
pub seg_max: u32,
/// Decompressed-block cache budget in BYTES. Sized in bytes rather than blocks on purpose: a
/// fixed block COUNT would make cache memory scale with the block-size dial, which is backwards.
/// Blocking makes this load-bearing — a record's pieces span a few blocks, so the cache turns the
/// rest of its reads into slices.
pub cache_bytes: usize,
/// Raw bytes gathered before a block seals. THE compression/read dial. Write-side only — a reader
/// never needs to know it. Bigger blocks compress harder (more cross-piece redundancy in reach)
/// and cost more to touch, since a read decompresses a whole block.
pub block_target: usize,
/// zstd level. Also write-side only. Costs ingest throughput, barely affects reads.
pub level: i32,
/// Compression threads. Compression is the expensive half of an append and blocks are
/// independent, so it runs off the write path. 0 = one per core.
pub compress_threads: usize,
}
impl Default for FoldCfg {
fn default() -> Self {
FoldCfg {
seg_max: SEG_MAX_DEFAULT,
cache_bytes: 64 << 20,
block_target: BLOCK_TARGET_DEFAULT,
level: codec::LEVEL_DEFAULT,
compress_threads: 0,
}
}
}
/// Outcome of an append.
#[derive(Clone, Copy, Debug)]
pub struct Put {
pub hash: PieceHash,
pub loc: Loc,
/// True when the content was already present and no bytes were written.
pub deduped: bool,
}
/// LRU of decompressed blocks, keyed by logical `block_id`, bounded by total decompressed bytes.
///
/// Recency lives in a second index (`order`: clock -> id) kept exactly in step with the map, so
/// eviction pops the coldest entry in O(log n). The old shape scanned the whole map per eviction
/// — O(n) per admit once warm, on a lock that every parallel scan partition contends for.
struct BlockCache {
budget: usize,
bytes: usize,
map: HashMap<u32, (u64, Arc<Vec<u8>>)>,
order: std::collections::BTreeMap<u64, u32>,
clock: u64,
hits: u64,
misses: u64,
}
impl BlockCache {
fn new(budget: usize) -> BlockCache {
BlockCache {
budget: budget.max(1),
bytes: 0,
map: HashMap::new(),
order: std::collections::BTreeMap::new(),
clock: 0,
hits: 0,
misses: 0,
}
}
fn touch(&mut self, k: u32, old_clock: u64) -> u64 {
self.clock += 1;
self.order.remove(&old_clock);
self.order.insert(self.clock, k);
self.clock
}
fn get(&mut self, k: u32) -> Option<Arc<Vec<u8>>> {
match self.map.get(&k).map(|e| (e.0, e.1.clone())) {
Some((old, v)) => {
let c = self.touch(k, old);
self.map.get_mut(&k).expect("just found").0 = c;
self.hits += 1;
Some(v)
}
None => {
self.misses += 1;
None
}
}
}
/// Drop an entry outright — for a block whose bytes no longer exist.
fn forget(&mut self, k: u32) {
if let Some((clock, v)) = self.map.remove(&k) {
self.bytes -= v.len();
self.order.remove(&clock);
}
}
fn put(&mut self, k: u32, v: Arc<Vec<u8>>) {
let add = v.len();
// always admit one block, however large, then evict coldest until back inside the budget
while self.bytes + add > self.budget && !self.order.is_empty() {
let (&coldest, &victim) = self.order.iter().next().expect("non-empty");
self.order.remove(&coldest);
if let Some((_, gone)) = self.map.remove(&victim) {
self.bytes -= gone.len();
}
}
self.clock += 1;
let c = self.clock;
self.bytes += add;
self.order.insert(c, k);
// Re-inserting a key DISPLACES a value whose bytes are still counted. Two readers racing the
// same block is ordinary now that scan partitions run in parallel, and each race leaked a
// block's worth of budget — enough repeats and a 64 MiB cache believes it is full while
// holding one entry.
if let Some((old_clock, old)) = self.map.insert(k, (c, v)) {
self.bytes -= old.len();
self.order.remove(&old_clock);
}
}
}
/// Cache effectiveness — the thing to watch if read latency regresses.
#[derive(Clone, Copy, Debug, Default)]
pub struct CacheStats {
pub hits: u64,
pub misses: u64,
pub bytes: usize,
pub budget: usize,
}
/// What [`Fold::scrub`] verified.
#[derive(Clone, Copy, Debug, Default)]
pub struct FoldScrub {
pub segments: u32,
pub blocks: usize,
/// Frame bytes whose checksums verified.
pub bytes: u64,
/// Bytes past the active segment's last valid frame — uncommitted residue a crash left, which
/// the next writer open truncates. Reported so "verified" never silently skips them.
pub trailing_uncommitted: u64,
}
/// One segment as a read source hands it to [`Fold::open_read_from`]: its number, its bytes, and
/// its advisory sidecar if the source has one.
pub struct SegmentInput {
pub seg: u32,
pub reader: Arc<dyn ReadAt>,
pub sidecar: Option<Vec<u8>>,
}
pub struct Fold {
dir: PathBuf,
cfg: FoldCfg,
headers: Vec<SegHeader>,
/// Read handles, one per segment — behind [`ReadAt`] so a sealed fold can later be read out of
/// a pack extent or a remote range exactly as it is read out of a directory.
readers: Vec<Arc<dyn ReadAt>>,
dicts: HashMap<[u8; 32], Arc<Vec<u8>>>,
active: u32,
/// Physical append point in the active segment. No `Loc` refers to it — addressing is logical.
cur_off: u32,
/// block id -> (segment, offset). Rebuilt at open by scanning the frames, which carry their ids.
blockdir: Vec<Option<(u32, u32)>>,
/// The id the next sealed block will take.
next_block: u32,
/// Sealed but not yet written (still compressing, or waiting to be appended). Reads are served
/// from here, so a piece is readable the instant `put` returns.
inflight: HashMap<u32, Arc<Vec<u8>>>,
pool: pipe::Pool,
/// `None` for a read-only fold with no directory behind it (a pack): there is nothing to
/// append to, and `poisoned` refuses every write long before this would matter.
active_f: Option<File>,
/// Pieces gathered but not yet compressed and appended.
open_block: Vec<u8>,
dedup: DedupTable,
cache: Mutex<BlockCache>,
poisoned: bool,
scratch: Vec<u8>,
_lock: Option<File>,
/// Blocks the MANIFEST declares erased, as inclusive `[lo, hi]` ranges — the authority for
/// telling erasure from corruption.
///
/// It has to be declared rather than detected. Punching zeroes a block's PAYLOAD and leaves its
/// header intact so the frame chain stays walkable, so an erased block presents as a valid
/// header over a checksum that will not verify — which is byte-for-byte what a torn write looks
/// like. Nothing in the bytes distinguishes them; only the manifest does.
///
/// Empty for a fold nobody declared anything about, which reads exactly as it did before.
punched: Vec<(u32, u32)>,
read_limits: crate::read_limits::ReadLimits,
}
impl Fold {
pub fn open(dir: &Path, cfg: FoldCfg) -> Result<Fold> {
Fold::open_with_limits(dir, cfg, crate::read_limits::ReadLimits::default())
}
/// Open a writer with explicit frame and persistent object-count admission.
pub fn open_with_limits(
dir: &Path,
cfg: FoldCfg,
read_limits: crate::read_limits::ReadLimits,
) -> Result<Fold> {
// No committed tail means no manifest in hand — and therefore no punched declaration.
Fold::open_at_with_limits(dir, cfg, None, &[], read_limits)
}
/// Open, recovering to `committed`: the tail some higher layer durably recorded.
///
/// Two layers answer two different questions. The self-scan answers *"where does my block chain
/// stop being valid?"*. The committed tail answers *"where did the store promise it stopped?"*. A
/// committed tail **beyond** the last good block means the disk broke an fsync promise, and we
/// refuse rather than serve a fold that silently lost durable bytes.
///
/// `punched` is the same manifest's declared-erased block ranges. The tail scan needs it at
/// open, not merely after: a crash mid-punch can leave a DECLARED block's payload partially
/// zeroed, and only the declaration authorizes stepping over that frame instead of reading the
/// committed tail as beyond the last good block.
pub fn open_at(
dir: &Path,
cfg: FoldCfg,
committed: Option<FoldTail>,
punched: &[(u32, u32)],
) -> Result<Fold> {
Fold::open_at_with_limits(
dir,
cfg,
committed,
punched,
crate::read_limits::ReadLimits::default(),
)
}
/// Open and recover a writer under explicit frame and object-count admission.
pub fn open_at_with_limits(
dir: &Path,
cfg: FoldCfg,
committed: Option<FoldTail>,
punched: &[(u32, u32)],
read_limits: crate::read_limits::ReadLimits,
) -> Result<Fold> {
let read_limits = read_limits.validate()?;
if (cfg.seg_max as u64) > SEG_MAX_LIMIT {
bail!(
"seg_max {} exceeds the {} format bound (Loc.block_off is u32)",
cfg.seg_max,
SEG_MAX_LIMIT
);
}
// A block is admitted into a FRESH segment however large it is — otherwise a block bigger than
// seg_max could never be written at all. That admission is what makes block_target load-bearing
// for overflow: the segment append point and `Loc.in_off` are both u32, so a block target past
// 4 GiB wraps them and writes a block directory pointing at the wrong offset. In release that
// is silent.
if cfg.block_target == 0 {
bail!("block_target must be non-zero");
}
if cfg.block_target as u64 > BLOCK_TARGET_MAX {
bail!(
"block_target {} is too large; the segment append point and Loc.in_off are u32, so a \
block must stay well under 4 GiB",
cfg.block_target
);
}
// A deliberate NARROWING, not a bug fix: zstd itself accepts 0 (meaning "default") and
// negative "fast" levels. Neither belongs in a store whose stated posture is compression-first,
// and an invalid level otherwise surfaces at the first block write rather than at open — long
// after the caller could do anything about it.
if !(1..=22).contains(&cfg.level) {
bail!("zstd level {} is outside the 1..=22 range this fold accepts", cfg.level);
}
crate::vfs::mkdir_all(dir).with_context(|| format!("create fold dir {}", dir.display()))?;
let (entries, has_lock, has_segment) = fold_directory_shape(dir, read_limits)?;
let additions = u64::from(!has_lock) + u64::from(!has_segment);
read_limits.admit_directory_entries(
"fold directory during writer open",
entries.saturating_add(additions),
)?;
let lock = acquire_writer_lock(dir)?;
let rd = std::fs::read_dir(dir)
.with_context(|| format!("read fold directory {} for cleanup", dir.display()))?;
let mut visited = 0u64;
for e in rd {
visited = visited.saturating_add(1);
read_limits.admit_directory_entries("fold directory", visited)?;
let e = e?;
if e.file_name().to_string_lossy().ends_with(".tmp") {
let _ = crate::vfs::unlink(&e.path());
}
}
let mut nums = list_segments_with_limits(dir, read_limits)?;
nums.sort_unstable();
for (i, n) in nums.iter().enumerate() {
if *n != i as u32 {
bail!("fold segments are not dense: expected seg {i}, found {n}");
}
}
let mut headers: Vec<SegHeader> = Vec::with_capacity(nums.len());
'scan: while !nums.is_empty() {
headers.clear();
let last = *nums.last().unwrap();
let mut retry = false;
for &n in &nums {
let path = segment::seg_path(dir, n);
let f = File::open(&path).with_context(|| format!("open {}", path.display()))?;
let len = f.metadata()?.len();
let mut hb = [0u8; SEG_HDR_LEN as usize];
let ok = len >= SEG_HDR_LEN && f.read_exact_at(&mut hb, 0).is_ok();
match ok.then(|| SegHeader::decode(&hb, n)).transpose() {
Ok(Some(h)) => headers.push(h),
_ => {
if n != last {
bail!("segment {n} has an unreadable header — refusing (sealed history is corrupt)");
}
if len > SEG_HDR_LEN {
bail!("active segment {n} has a bad header but holds {len} bytes — refusing");
}
drop(f);
crate::vfs::unlink(&path)?;
segment::fsync_dir(dir)?;
// A torn create is not data — removing the last one may empty the fold
// entirely, which the fresh path below handles. (This used to refuse,
// which stranded a store that crashed during its very first segment's
// creation: found by the DST harness at crash point 3.)
nums.pop();
retry = true;
break;
}
}
}
if !retry {
break 'scan;
}
}
if nums.is_empty() {
// A virgin fold, or one whose only segment was a torn create, just removed. Either way
// no durable fold bytes exist — and a committed tail must AGREE with that: a manifest
// naming bytes an empty fold cannot serve means the fold lost durable data, and
// creating a fresh fold underneath it would bury the loss instead of reporting it.
if let Some(ct) = committed {
if ct > (FoldTail { seg: 0, off: SEG_HDR_LEN as u32 }) {
bail!(
"committed fold tail (seg {}, off {}) but the fold holds no durable bytes \
— the fold lost durable data",
ct.seg,
ct.off
);
}
}
let f = segment::create(dir, 0, [0u8; 32])?;
return Ok(Fold {
dir: dir.to_path_buf(),
cfg,
headers: vec![SegHeader { seg: 0, flags: 0, dict_id: [0u8; 32] }],
readers: vec![Arc::new(segment::open_rw(dir, 0)?)],
dicts: HashMap::new(),
active: 0,
cur_off: SEG_HDR_LEN as u32,
active_f: Some(f),
open_block: Vec::with_capacity(cfg.block_target * 2),
dedup: DedupTable::new(),
cache: Mutex::new(BlockCache::new(cfg.cache_bytes)),
poisoned: false,
scratch: Vec::new(),
blockdir: Vec::new(),
next_block: 0,
inflight: HashMap::new(),
pool: pipe::Pool::new(nthreads(cfg.compress_threads), cfg.level, None),
_lock: Some(lock),
punched: punched.to_vec(),
read_limits,
});
}
let mut dicts: HashMap<[u8; 32], Arc<Vec<u8>>> = HashMap::new();
for h in &headers {
if !h.has_dict() || dicts.contains_key(&h.dict_id) {
continue;
}
let name = format!("zdict-{}.zd", PieceHash(h.dict_id).to_hex());
let bytes = read_bounded_candidate(&dir.join(&name), MAX_DICTIONARY_BYTES)
.with_context(|| {
format!("segment {} names dictionary {name} but it is unreadable", h.seg)
})?;
let got: [u8; 32] = blake3::hash(&bytes).into();
if got != h.dict_id {
bail!("dictionary {name} content hash does not match the id naming it");
}
dicts.insert(h.dict_id, Arc::new(bytes));
}
let mut active = *nums.last().unwrap();
let mut active_f = segment::open_rw(dir, active)?;
let flen = active_f.metadata()?.len();
let has_dict = headers[active as usize].has_dict();
let (good_tail, _) =
segment::scan_tail_with_limits(&active_f, flen, has_dict, punched, read_limits)?;
let target = match committed {
None => good_tail,
Some(ct) => {
if (ct.seg, ct.off as u64) > (active, good_tail) {
bail!(
"committed fold tail (seg {}, off {}) is beyond the last good block (seg {}, off {}) \
— the fold lost durable bytes",
ct.seg, ct.off, active, good_tail
);
}
while active > ct.seg {
let p = segment::seg_path(dir, active);
drop(active_f);
crate::vfs::unlink(&p)?;
headers.pop();
active -= 1;
active_f = segment::open_rw(dir, active)?;
}
segment::fsync_dir(dir)?;
ct.off as u64
}
};
let active_path = segment::seg_path(dir, active);
crate::vfs::set_len(&active_f, &active_path, target)?;
crate::vfs::sync_file(&active_f, &active_path)?;
segment::fsync_dir(dir)?;
let mut readers: Vec<Arc<dyn ReadAt>> = Vec::with_capacity(headers.len());
for h in &headers {
readers.push(Arc::new(segment::open_rw(dir, h.seg)?));
}
// Rebuild the block directory across every segment. Frames carry their ids, so this works
// even though blocks were written in completion order rather than id order. Sealed
// segments answer from their directory sidecars when they can — that is what keeps open
// O(active segment) instead of O(store) — and are rescanned (and their sidecar
// regenerated) when they cannot.
let mut blockdir: Vec<Option<(u32, u32)>> = Vec::new();
let mut next_block = 0u32;
let mut seen_blocks = 0u64;
for (i, h) in headers.iter().enumerate() {
let len = readers[i].len()?;
let entries = if h.seg != active {
match segment::read_dir_sidecar_with_limits(dir, h.seg, len, read_limits)? {
Some((_, e)) => e,
None => {
let (tail, e) = segment::scan_tail_with_limits(
&readers[i],
len,
h.has_dict(),
punched,
read_limits,
)?;
// Regenerate so the next open finds it. Best-effort: advisory data must
// never fail an open, only slow one down.
let _ = segment::write_dir_sidecar(dir, h.seg, tail as u32, &e);
e
}
}
} else {
segment::scan_tail_with_limits(
&readers[i],
len,
h.has_dict(),
punched,
read_limits,
)?
.1
};
for (id, off) in entries {
install_block_location(
&mut blockdir,
&mut next_block,
&mut seen_blocks,
id,
(h.seg, off),
read_limits,
)?;
}
}
Ok(Fold {
dir: dir.to_path_buf(),
cfg,
headers,
readers,
dicts,
active,
cur_off: target as u32,
active_f: Some(active_f),
open_block: Vec::with_capacity(cfg.block_target * 2),
dedup: DedupTable::new(),
cache: Mutex::new(BlockCache::new(cfg.cache_bytes)),
poisoned: false,
scratch: Vec::new(),
blockdir,
next_block,
inflight: HashMap::new(),
pool: pipe::Pool::new(nthreads(cfg.compress_threads), cfg.level, None),
_lock: Some(lock),
punched: punched.to_vec(),
read_limits,
})
}
/// Tell this fold which blocks the manifest declares erased, as inclusive `[lo, hi]` ranges.
///
/// The caller owes the right manifest, and for a RETAINED snapshot that is the LIVE one, not the
/// snapshot's own: punching commits a new manifest, so the retained copy predates the erasure
/// and declares nothing. `punched` is cumulative in the live manifest, which is what makes this
/// answerable at all.
pub fn declare_punched(&mut self, ranges: &[(u32, u32)]) {
self.punched = ranges.to_vec();
}
fn is_punched(&self, block_id: u32) -> bool {
self.punched.iter().any(|&(lo, hi)| block_id >= lo && block_id <= hi)
}
/// Open WITHOUT the writer lock, read-only.
///
/// Takes no lock, truncates nothing, sweeps nothing — a reader must never mutate a store another
/// process is writing. Safe concurrently with a live writer: segments are append-only and blocks
/// are immutable once written, so a reader sees a prefix that only ever grows. No manifest in
/// hand, so no punched declaration reaches the scan.
pub fn open_read(dir: &Path, cfg: FoldCfg) -> Result<Fold> {
Fold::open_read_with_limits(dir, cfg, &[], crate::read_limits::ReadLimits::default())
}
/// Open an unlocked reader with explicit frame and object-count admission, declaring the
/// manifest's punched block ranges so the scan can step over erased frames.
pub fn open_read_with_limits(
dir: &Path,
cfg: FoldCfg,
punched: &[(u32, u32)],
read_limits: crate::read_limits::ReadLimits,
) -> Result<Fold> {
let read_limits = read_limits.validate()?;
let mut nums = list_segments_with_limits(dir, read_limits)?;
if nums.is_empty() {
bail!("no fold segments under {}", dir.display());
}
nums.sort_unstable();
let mut segs = Vec::with_capacity(nums.len());
for &n in &nums {
let reader = Arc::new(segment::open_read(dir, n)?);
let len = reader.metadata()?.len();
segs.push(SegmentInput {
seg: n,
reader: reader as Arc<dyn ReadAt>,
sidecar: segment::read_dir_sidecar_bytes_with_limits(dir, n, len, read_limits)?,
});
}
let mut dict_files = Vec::new();
let rd = std::fs::read_dir(dir)
.with_context(|| format!("read fold directory {} for dictionaries", dir.display()))?;
let mut visited = 0u64;
for e in rd {
visited = visited.saturating_add(1);
read_limits.admit_directory_entries("fold directory", visited)?;
let e = e?;
let n = e.file_name().to_string_lossy().to_string();
if n.starts_with("zdict-") && n.ends_with(".zd") {
dict_files.push(read_bounded_candidate(&e.path(), MAX_DICTIONARY_BYTES)?);
}
}
Fold::open_read_from_with_limits(segs, dict_files, cfg, dir, punched, read_limits)
}
/// Open only the durable prefix named by a manifest, ignoring later append residue. No
/// punched declaration in hand — a caller holding the manifest uses the `_with_limits` form.
pub fn open_read_at(dir: &Path, cfg: FoldCfg, committed: FoldTail) -> Result<Fold> {
Fold::open_read_at_with_limits(
dir,
cfg,
committed,
&[],
crate::read_limits::ReadLimits::default(),
)
}
/// Open a committed read-only prefix with explicit frame and object-count admission, plus the
/// manifest's punched declaration for the scan.
pub fn open_read_at_with_limits(
dir: &Path,
cfg: FoldCfg,
committed: FoldTail,
punched: &[(u32, u32)],
read_limits: crate::read_limits::ReadLimits,
) -> Result<Fold> {
let read_limits = read_limits.validate()?;
let mut nums = list_segments_with_limits(dir, read_limits)?;
nums.retain(|segment| *segment <= committed.seg);
nums.sort_unstable();
if nums.last().copied() != Some(committed.seg) {
bail!(
"committed fold tail names segment {} but it is absent under {}",
committed.seg,
dir.display()
);
}
let mut segs = Vec::with_capacity(nums.len());
for &segment in &nums {
let file = Arc::new(segment::open_read(dir, segment)?);
let physical = file.metadata()?.len();
let len = if segment == committed.seg { committed.off as u64 } else { physical };
if len > physical {
bail!(
"committed fold tail is {} bytes into segment {segment}, which holds only {physical}",
committed.off
);
}
segs.push(SegmentInput {
seg: segment,
reader: Arc::new(Slice::new(file, 0, len)) as Arc<dyn ReadAt>,
// The committed segment may have been sealed before a later generation became
// active, and punched blocks can only be located through its sidecar. The parser
// below accepts it only when its embedded tail equals this bounded reader's length,
// so a sidecar describing a newer suffix remains safely advisory.
sidecar: segment::read_dir_sidecar_bytes_with_limits(
dir,
segment,
len,
read_limits,
)?,
});
}
let mut dict_files = Vec::new();
let entries = std::fs::read_dir(dir)
.with_context(|| format!("read fold directory {} for dictionaries", dir.display()))?;
let mut visited = 0u64;
for entry in entries {
visited = visited.saturating_add(1);
read_limits.admit_directory_entries("fold directory", visited)?;
let entry = entry?;
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("zdict-") && name.ends_with(".zd") {
dict_files.push(read_bounded_candidate(&entry.path(), MAX_DICTIONARY_BYTES)?);
}
}
Fold::open_read_from_with_limits(segs, dict_files, cfg, dir, punched, read_limits)
}
/// Open read-only from prepared inputs — the entry every SOURCE uses. A directory hands in
/// files; a pack hands in extents; a remote store would hand in range readers. Nothing below
/// this knows or cares which.
///
/// `dict_files` are candidate trained dictionaries, identified by content hash — a segment
/// naming a dictionary no candidate hashes to is refused. `label` names the source in errors
/// and [`Fold::dir`], and is never touched as a path.
pub fn open_read_from(
segs: Vec<SegmentInput>,
dict_files: Vec<Vec<u8>>,
cfg: FoldCfg,
label: &Path,
) -> Result<Fold> {
Fold::open_read_from_with_limits(
segs,
dict_files,
cfg,
label,
&[],
crate::read_limits::ReadLimits::default(),
)
}
/// Backend-neutral read open with explicit frame and object-count admission. `punched` is the
/// owning manifest's declared-erased block ranges: a source that has punched blocks may hold a
/// frame whose payload a crash left partially zeroed, and the declaration is what lets the
/// rebuild scan step over it.
pub fn open_read_from_with_limits(
mut segs: Vec<SegmentInput>,
dict_files: Vec<Vec<u8>>,
cfg: FoldCfg,
label: &Path,
punched: &[(u32, u32)],
read_limits: crate::read_limits::ReadLimits,
) -> Result<Fold> {
let read_limits = read_limits.validate()?;
if segs.is_empty() {
bail!("no fold segments under {}", label.display());
}
segs.sort_by_key(|s| s.seg);
// The same density rule the writer applies. A gap means a segment is missing, and reading
// around it would silently serve a fold with a hole in its block space rather than refuse —
// the writer refused and the reader did not, which is the worse half of an asymmetry.
for (i, s) in segs.iter().enumerate() {
if s.seg != i as u32 {
bail!("fold segments are not dense: expected seg {i}, found {}", s.seg);
}
}
let mut headers = Vec::with_capacity(segs.len());
let mut readers: Vec<Arc<dyn ReadAt>> = Vec::with_capacity(segs.len());
for s in &segs {
let mut hb = [0u8; SEG_HDR_LEN as usize];
s.reader.read_exact_at(&mut hb, 0)?;
headers.push(SegHeader::decode(&hb, s.seg)?);
readers.push(s.reader.clone());
}
let mut dicts: HashMap<[u8; 32], Arc<Vec<u8>>> = HashMap::new();
for bytes in dict_files {
let id: [u8; 32] = blake3::hash(&bytes).into();
dicts.insert(id, Arc::new(bytes));
}
for h in &headers {
if h.has_dict() && !dicts.contains_key(&h.dict_id) {
bail!(
"segment {} names dictionary {} but no candidate hashes to it",
h.seg,
PieceHash(h.dict_id).to_hex()
);
}
}
// The directory is rebuilt from the ids the frames carry — the same sidecar-or-scan rule
// the writer applies, except a reader NEVER writes a missing sidecar back: a reader must
// not mutate a store it does not own, and a slower open is the whole cost.
let mut blockdir: Vec<Option<(u32, u32)>> = Vec::new();
let mut next_block = 0u32;
let mut seen_blocks = 0u64;
for (i, h) in headers.iter().enumerate() {
let len = readers[i].len()?;
let entries = match segs[i].sidecar.as_ref() {
Some(bytes) => {
match segment::parse_dir_sidecar_with_limits(bytes, h.seg, len, read_limits)? {
Some((_, entries)) => entries,
None => {
segment::scan_tail_with_limits(
&readers[i],
len,
h.has_dict(),
punched,
read_limits,
)?
.1
}
}
}
None => {
segment::scan_tail_with_limits(
&readers[i],
len,
h.has_dict(),
punched,
read_limits,
)?
.1
}
};
for (id, off) in entries {
install_block_location(
&mut blockdir,
&mut next_block,
&mut seen_blocks,
id,
(h.seg, off),
read_limits,
)?;
}
}
let cur_off = readers.last().unwrap().len()? as u32;
Ok(Fold {
dir: label.to_path_buf(),
cfg,
headers,
readers,
dicts,
active: segs.last().unwrap().seg,
cur_off,
active_f: None,
open_block: Vec::new(),
dedup: DedupTable::with_capacity(16),
cache: Mutex::new(BlockCache::new(cfg.cache_bytes)),
poisoned: true, // a read-only fold must refuse every append
scratch: Vec::new(),
blockdir,
next_block,
inflight: HashMap::new(),
pool: pipe::Pool::new(1, cfg.level, None),
_lock: None,
punched: punched.to_vec(),
read_limits,
})
}
/// Append `raw`, or return the existing location if this content is already folded.
///
/// The returned `Loc` is final even though the block holding it may not be sealed yet: a block's
/// offset is fixed when the block *opens* (it is the segment's append point), so a piece's address
/// is known the moment it enters the buffer. Reads of an unsealed piece are served from the buffer.
pub fn put(&mut self, raw: &[u8]) -> Result<Put> {
let hash = PieceHash::of(raw);
self.put_hashed(raw, hash)
}
/// `put` for a caller that has ALREADY hashed the content.
///
/// Hashing is the parallelizable half of an append and the serialized writer is the scarce
/// resource, so an ingest pipeline hashes on worker threads and hands the digest in. The hash is
/// trusted: it is the caller's assertion about bytes it holds, exactly as `put` trusts its own.
pub fn put_hashed(&mut self, raw: &[u8], hash: PieceHash) -> Result<Put> {
if self.poisoned {
bail!("fold is poisoned by an earlier failed write; reopen to recover by tail scan");
}
if raw.len() as u64 > u32::MAX as u64 {
bail!("piece of {} bytes exceeds the u32 length cap; carve smaller", raw.len());
}
debug_assert_eq!(
hash,
PieceHash::of(raw),
"put_hashed given a digest that is not its content's"
);
if let Some(loc) = self.dedup.get(&hash) {
return Ok(Put { hash, loc, deduped: true });
}
// A limit smaller than the ordinary block target deliberately becomes the effective seal
// target. Seal BEFORE appending when needed, and refuse one indivisible piece before any
// fold mutation. This is the progress rule that lets strict profiles keep accepting small
// records without ever writing a block they cannot reopen.
let atomic =
self.read_limits.max_stored_frame_bytes.min(self.read_limits.max_decoded_frame_bytes);
self.read_limits.admit("new fold block", raw.len() as u64, raw.len() as u64)?;
let starts_new_block = self.open_block.is_empty()
|| self.open_block.len() as u64 > atomic.saturating_sub(raw.len() as u64);
let proposed_block = if self.open_block.is_empty() {
self.next_block
} else if starts_new_block {
self.next_block
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("block id space exhausted"))?
} else {
self.next_block
};
if starts_new_block {
self.read_limits.admit_fold_blocks(u64::from(proposed_block) + 1)?;
}
if !self.open_block.is_empty() && starts_new_block {
self.seal_block()?;
self.write_ready(false)?;
}
let loc = Loc {
block_id: self.next_block,
in_off: self.open_block.len() as u32,
raw: raw.len() as u32,
};
self.open_block.extend_from_slice(raw);
self.dedup.insert(hash, loc);
if self.open_block.len() >= self.cfg.block_target {
self.seal_block()?;
}
// Write anything the pool has finished. Cheap, and it keeps the backlog shallow.
self.write_ready(false)?;
Ok(Put { hash, loc, deduped: false })
}
/// Run `f` over the piece's bytes wherever they live — the open buffer, the compression
/// pipeline, or a (cached) decompressed block — WITHOUT copying them anywhere first. Every
/// read shape is a projection of this one.
fn with_piece<T>(&self, loc: Loc, f: impl FnOnce(&[u8]) -> T) -> Result<T> {
crate::io_trace::fold_block_touched(loc.block_id);
let end = loc.in_off as u64 + loc.raw as u64;
// still gathering — not yet sealed
if loc.block_id == self.next_block {
if end > self.open_block.len() as u64 {
bail!("Loc names bytes past the open block");
}
return Ok(f(&self.open_block[loc.in_off as usize..end as usize]));
}
// sealed but still in the pipeline — already uncompressed, so serve it directly
if let Some(raw) = self.inflight.get(&loc.block_id) {
if end > raw.len() as u64 {
bail!("Loc names bytes past its block");
}
return Ok(f(&raw[loc.in_off as usize..end as usize]));
}
let blk = self.block_bytes(loc)?;
if end > blk.len() as u64 {
bail!(
"Loc (in_off {}, raw {}) exceeds its block of {} bytes",
loc.in_off,
loc.raw,
blk.len()
);
}
Ok(f(&blk[loc.in_off as usize..end as usize]))
}
/// Read one piece back, exactly as it was written.
pub fn read(&self, loc: Loc) -> Result<Vec<u8>> {
self.with_piece(loc, |s| s.to_vec())
}
/// Read and confirm full content identity — the caller knows what hash it expects.
pub fn read_verified(&self, loc: Loc, expect: PieceHash) -> Result<Vec<u8>> {
self.with_piece(loc, |s| -> Result<Vec<u8>> {
let got = PieceHash::of(s);
if got != expect {
bail!(
"content hash mismatch in block {} at +{}: got {got}, expected {expect}",
loc.block_id,
loc.in_off
);
}
Ok(s.to_vec())
})?
}
/// [`Fold::read_verified`], appending straight into `out` — reconstruction's read. A body is
/// many pieces concatenated, and the intermediate Vec per piece was pure overhead: verify the
/// bytes where they sit in the block, then copy ONCE, into their final place.
pub fn read_verified_into(&self, loc: Loc, expect: PieceHash, out: &mut Vec<u8>) -> Result<()> {
self.with_piece(loc, |s| -> Result<()> {
let got = PieceHash::of(s);
if got != expect {
bail!(
"content hash mismatch in block {} at +{}: got {got}, expected {expect}",
loc.block_id,
loc.in_off
);
}
out.extend_from_slice(s);
Ok(())
})?
}
/// The decompressed bytes of the block holding `loc`, through the cache.
fn block_bytes(&self, loc: Loc) -> Result<Arc<Vec<u8>>> {
if let Some(v) = self.cache.lock().unwrap().get(loc.block_id) {
crate::io_trace::fold_block_cache_hit();
return Ok(v);
}
let (seg, off) =
*self.blockdir.get(loc.block_id as usize).and_then(|e| e.as_ref()).ok_or_else(
|| anyhow::anyhow!("block {} is not in the fold's directory", loc.block_id),
)?;
let f = self.readers.get(seg as usize).ok_or_else(|| {
anyhow::anyhow!("block {} names segment {seg} which does not exist", loc.block_id)
})?;
if (off as u64) < SEG_HDR_LEN {
bail!("block {} offset {off} is inside the segment header", loc.block_id);
}
let has_dict = self.headers[seg as usize].has_dict();
let mut hb = [0u8; block::BLOCK_HDR_LEN];
f.read_exact_at(&mut hb, off as u64)
.with_context(|| format!("read block header at seg {seg} off {off}"))?;
// Naming an erasure is the difference between "your disk is failing" and "this content was
// erased on purpose", and only one of those is true.
//
// The DECLARATION is checked first because it is the only thing that can be right. Punching
// zeroes a block's payload and deliberately leaves its 16-byte header intact so the frame
// chain stays walkable, so an erased block presents as a valid header over a payload whose
// checksum will not verify — which is byte-for-byte indistinguishable from a torn write.
// The zero-header test below cannot see that case, which is every block turndb itself
// punches; it survives for a frame zeroed by something other than `punch_blocks`.
if self.is_punched(loc.block_id) {
bail!(
"block {} was ERASED (its bytes were punched out of the fold); \
the manifest's punched list is authoritative for which",
loc.block_id
);
}
if hb.iter().all(|&b| b == 0) {
bail!(
"block {} was ERASED (its bytes were punched out of the fold); \
the manifest's punched list is authoritative for which",
loc.block_id
);
}
let hdr = block::parse_hdr(&hb, has_dict)?;
if hdr.block_id != loc.block_id {
bail!("directory sent block {} to a frame carrying id {}", loc.block_id, hdr.block_id);
}
self.read_limits.admit(
format!("fold block {}", hdr.block_id),
u64::from(hdr.stored),
u64::from(hdr.raw),
)?;
let span = hdr.frame_len() as usize;
let mut buf = vec![0u8; span];
buf[..block::BLOCK_HDR_LEN].copy_from_slice(&hb);
f.read_exact_at(&mut buf[block::BLOCK_HDR_LEN..], off as u64 + block::BLOCK_HDR_LEN as u64)
.with_context(|| format!("read block at seg {seg} off {off}"))?;
block::verify_frame_bytes(&buf, has_dict)?;
let dict = self.dicts.get(&self.headers[seg as usize].dict_id).cloned();
let payload = &buf[block::BLOCK_HDR_LEN..block::BLOCK_HDR_LEN + hdr.stored as usize];
let raw = codec::decode(hdr.codec, payload, hdr.raw, dict.as_deref().map(|v| &v[..]))?;
// A free check that a decode produced the bytes this block was written for. It filters; it
// never concludes identity. Unconditional — every block in this build carries r16. (The
// ENCRYPTED segment flag is reserved and refused at open, so nothing reaching here was
// ever ciphertext.)
if blake3::hash(&raw).as_bytes()[0..2] != hdr.r16 {
bail!("decoded block does not match its content prefix (block {})", loc.block_id);
}
let arc = Arc::new(raw);
self.cache.lock().unwrap().put(loc.block_id, arc.clone());
crate::io_trace::fold_block_cache_miss(span as u64, hdr.raw);
Ok(arc)
}
/// Seal the open block: assign its id and hand it to the compression pool. Does no compression
/// and no I/O — that is the whole point. Idempotent when the buffer is empty.
fn seal_block(&mut self) -> Result<()> {
if self.open_block.is_empty() {
return Ok(());
}
let id = self.next_block;
self.next_block = self
.next_block
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("block id space exhausted"))?;
let raw = Arc::new(std::mem::replace(
&mut self.open_block,
Vec::with_capacity(self.cfg.block_target * 2),
));
self.inflight.insert(id, raw.clone());
self.pool.submit(id, raw)?;
Ok(())
}
/// Append every block the pool has finished. With `wait`, blocks until the pool is empty.
fn write_ready(&mut self, wait: bool) -> Result<()> {
let done = if wait { self.pool.take_all()? } else { self.pool.try_take() };
for d in done {
self.write_block(d)?;
}
Ok(())
}
fn write_block(&mut self, d: pipe::Done) -> Result<()> {
let n = block::encode(&mut self.scratch, d.block_id, d.codec, &d.raw, &d.payload);
// Roll if this block would not fit. Blocks are self-contained, so one never straddles.
if self.cur_off as u64 > SEG_HDR_LEN
&& self.cur_off as u64 + n as u64 > self.cfg.seg_max as u64
{
self.roll()?;
}
let path = segment::seg_path(&self.dir, self.active);
let f = self
.active_f
.as_ref()
.ok_or_else(|| anyhow::anyhow!("read-only fold cannot append"))?;
if let Err(e) = crate::vfs::write_all_at(f, &path, &self.scratch[..n], self.cur_off as u64)
{
self.poisoned = true;
return Err(anyhow::Error::new(e).context("fold block append failed; fold poisoned"));
}
self.read_limits.admit_fold_blocks(u64::from(d.block_id) + 1)?;
if self.blockdir.len() <= d.block_id as usize {
self.blockdir.resize(d.block_id as usize + 1, None);
}
if self.blockdir[d.block_id as usize].replace((self.active, self.cur_off)).is_some() {
bail!("fold block id {} was written more than once", d.block_id);
}
self.cur_off += n as u32;
match self.inflight.entry(d.block_id) {
Entry::Occupied(e) => {
e.remove();
}
Entry::Vacant(_) => {}
}
Ok(())
}
/// Seal the open block, make everything durable, and return the tail. Data before pointers: no part
/// may name a `Loc` at or beyond a tail this has not returned.
///
/// Call this at flush boundaries, not per record — every call seals the open block early, and short
/// blocks compress worse.
pub fn sync(&mut self) -> Result<FoldTail> {
self.seal_block()?;
// Every block must be compressed AND written before a tail can be reported durable.
self.write_ready(true)?;
let f =
self.active_f.as_ref().ok_or_else(|| anyhow::anyhow!("read-only fold cannot sync"))?;
crate::vfs::sync_file(f, &segment::seg_path(&self.dir, self.active))
.context("fsync active fold segment")?;
Ok(self.tail())
}
/// The current append point. Pieces in the open buffer live AT this offset and are not yet durable.
pub fn tail(&self) -> FoldTail {
FoldTail { seg: self.active, off: self.cur_off }
}
/// Resolve content to a location through the unsealed dedup window.
///
/// Only covers pieces not yet sealed into a part — sealed pieces are found through the parts' own
/// dictionaries, which is why this index needs no on-disk form. A miss is never wrong, only slower.
pub fn lookup(&self, hash: PieceHash) -> Option<Loc> {
self.dedup.get(&hash)
}
/// Record a location the caller resolved elsewhere (a Tier-1 part lookup), so that further
/// references to the same content in this flush window are answered from memory.
///
/// This only ever populates a cache with a mapping that is already true on disk. It cannot create
/// content, and a wrong entry here would be indistinguishable from a wrong entry made by `put`.
pub fn note(&mut self, hash: PieceHash, loc: Loc) {
self.dedup.insert(hash, loc);
}
pub fn window_len(&self) -> usize {
self.dedup.len()
}
/// Release the dedup window — the pieces it covers are sealed into a part, so resident memory
/// tracks the flush interval rather than the store.
pub fn seal_window(&mut self) {
self.dedup.clear();
}
/// Physically destroy the bytes of blocks whose every piece is dead, WITHOUT moving anything.
///
/// `FALLOC_FL_PUNCH_HOLE` deallocates a file's extents and reads them back as zeros: the file
/// length, and therefore every offset in it, is unchanged — so no `Loc` above the fold is
/// invalidated and no part needs rebuilding. That is what makes this the sub-refold erasure
/// primitive: a refold rewrites the world to reclaim space, and this reclaims the same space
/// in place, at the cost of leaving the block's frame header behind unpunched.
///
/// `dead` names BLOCK IDS, and the caller owes the truth of that: a block is punchable only
/// when no live record references any piece in it. The store computes that from the parts and
/// records the result in the manifest before calling here — because a punched block read as
/// merely corrupt is an ops fire drill, and only an authoritative record prevents it.
///
/// Returns the ids actually punched. A block already punched, or whose frame will not parse,
/// is skipped rather than errored — this is reclamation, and a block it cannot account for is
/// a block it leaves alone.
pub fn punch_blocks(&mut self, dead: &[u32]) -> Result<Vec<u32>> {
self.punch_blocks_with_control(dead, &crate::control::OperationControl::default())
}
/// [`Fold::punch_blocks`] with a safe checkpoint before each independently reclaimable block.
pub fn punch_blocks_with_control(
&mut self,
dead: &[u32],
control: &crate::control::OperationControl,
) -> Result<Vec<u32>> {
let mut done = Vec::new();
for &id in dead {
control.check("fold punch")?;
let Some(Some((seg, off))) = self.blockdir.get(id as usize).copied() else { continue };
let mut hb = [0u8; block::BLOCK_HDR_LEN];
if self.readers[seg as usize].read_exact_at(&mut hb, off as u64).is_err() {
continue;
}
let has_dict = self.headers[seg as usize].has_dict();
let Ok(hdr) = block::parse_hdr(&hb, has_dict) else { continue };
if hdr.block_id != id {
bail!("directory sent block {id} to a frame carrying id {}", hdr.block_id);
}
let f = segment::open_rw(&self.dir, seg)?;
// The PAYLOAD only — the header stays so the frame chain remains walkable. See
// `segment::punch`.
let path = segment::seg_path(&self.dir, seg);
segment::punch(&f, &path, off as u64 + block::BLOCK_HDR_LEN as u64, hdr.stored as u64)?;
// The block is gone as content: drop it from the directory so no Loc can resolve
// into erased bytes, exactly as a reopened store's scan would.
self.blockdir[id as usize] = None;
done.push(id);
}
// Punched blocks are no longer readable content: drop their cache entries so a warm
// reader cannot keep serving what the disk no longer holds.
{
let mut c = self.cache.lock().unwrap();
for id in &done {
c.forget(*id);
}
}
Ok(done)
}
/// Verify every block frame in every segment — the fold's half of a scrub.
///
/// This is the whole-file read that sidecars removed from OPEN, done deliberately where it
/// belongs: a scrub's cost is the point of a scrub. Covers what reconstruction-based deep
/// verification cannot — blocks holding only retained or unreferenced pieces — and works
/// identically over a directory or a pack, because it reads through [`ReadAt`].
///
/// A frame that fails its checksum ends a segment's valid span; a sealed segment whose span
/// ends before its file does is corruption and errors. The ACTIVE segment is allowed a
/// trailing invalid region (uncommitted writes a crash abandoned), which is reported, not
/// condemned.
pub fn scrub(&self) -> Result<FoldScrub> {
self.scrub_with_control(&crate::control::OperationControl::default())
}
/// [`Fold::scrub`] with cooperative checks between segments and complete frames.
pub fn scrub_with_control(
&self,
control: &crate::control::OperationControl,
) -> Result<FoldScrub> {
let mut report = FoldScrub::default();
for (i, h) in self.headers.iter().enumerate() {
control.check("fold verification")?;
let len = self.readers[i].len()?;
// With this fold's punched declaration: verification runs against crash residue too,
// and a declared block mid-punch (payload part-zeroed, retry pending) is accounted
// for, not corrupt.
let (end, entries) = segment::scan_tail_controlled_with_limits(
&self.readers[i],
len,
h.has_dict(),
&self.punched,
control,
"fold verification",
self.read_limits,
)?;
report.segments += 1;
report.blocks += entries.len();
report.bytes += end.saturating_sub(segment::SEG_HDR_LEN);
if end < len {
if h.seg == self.active {
report.trailing_uncommitted = len - end;
} else {
bail!(
"sealed segment {} holds valid frames only to byte {end} of {len} — corruption",
h.seg
);
}
}
}
Ok(report)
}
pub fn cache_stats(&self) -> CacheStats {
let c = self.cache.lock().unwrap();
CacheStats { hits: c.hits, misses: c.misses, bytes: c.bytes, budget: c.budget }
}
/// Every block id the directory knows — the universe a reachability sweep works against.
pub fn block_ids(&self) -> Vec<u32> {
self.blockdir.iter().enumerate().filter_map(|(id, e)| e.map(|_| id as u32)).collect()
}
/// Read the framing facts for every block the current directory can address.
///
/// This deliberately reads headers only: callers can classify compressed storage without
/// decompressing content or warming the block cache. Blocks declared punched may still appear
/// here after reopen because sealed-segment sidecars preserve their framing locations; the
/// store layer owns that manifest-level classification.
pub(crate) fn block_inventory_with_control(
&self,
control: &crate::control::OperationControl,
) -> Result<Vec<BlockStorage>> {
let mut inventory = Vec::new();
for (id, entry) in self.blockdir.iter().enumerate() {
control.check("fold block inventory")?;
let Some((seg, off)) = *entry else { continue };
let id = u32::try_from(id).map_err(|_| anyhow::anyhow!("block id exceeds u32"))?;
let reader = self.readers.get(seg as usize).ok_or_else(|| {
anyhow::anyhow!("block {id} names segment {seg} which does not exist")
})?;
let mut bytes = [0u8; block::BLOCK_HDR_LEN];
reader
.read_exact_at(&mut bytes, u64::from(off))
.with_context(|| format!("read block {id} header at seg {seg} off {off}"))?;
let header = block::parse_hdr(&bytes, self.headers[seg as usize].has_dict())?;
if header.block_id != id {
bail!("directory sent block {id} to a frame carrying id {}", header.block_id);
}
inventory.push(BlockStorage {
block_id: id,
raw_bytes: header.raw,
stored_bytes: header.stored,
});
}
Ok(inventory)
}
pub fn segment_count(&self) -> u32 {
self.headers.len() as u32
}
pub fn dir(&self) -> &Path {
&self.dir
}
/// Total bytes across all segment files. Excludes anything still in the open buffer.
pub fn disk_bytes(&self) -> u64 {
// Measured through the readers rather than the filesystem. `dir` is a real directory only
// for a directory-backed fold; for one served out of a pack or a container it is a LABEL,
// so building segment paths from it yields paths that do not exist, `metadata` fails, and
// `.ok()` turns the whole sum into a silent zero. A reader knows its own length whatever
// is behind it, which is the only form of this question that has an answer everywhere.
self.readers.iter().filter_map(|r| crate::readat::ReadAt::len(r).ok()).sum()
}
/// The active segment's dictionary. Currently unused because the compression pool is handed its
/// dictionary at construction; when trained dictionaries land, the pool must be rebuilt on roll.
#[allow(dead_code)]
fn active_dict(&self) -> Option<Arc<Vec<u8>>> {
let id = self.headers[self.active as usize].dict_id;
if id == [0u8; 32] {
None
} else {
self.dicts.get(&id).cloned()
}
}
/// Roll to a new segment. Every physical step happens before any logical state moves, so a failure
/// leaves nothing changed and the caller's retry re-enters cleanly. (An earlier generation of this
/// engine advanced the offset first; a roll-time ENOSPC then left a zero offset over the *old*
/// segment handle and the next write silently corrupted the fold.)
fn roll(&mut self) -> Result<()> {
let entries = count_fold_directory_entries(&self.dir, self.read_limits)?;
self.read_limits.admit_directory_entries(
"fold directory during segment roll",
entries.saturating_add(2),
)?;
let flags = self.headers[self.active as usize].flags;
let f =
self.active_f.as_ref().ok_or_else(|| anyhow::anyhow!("read-only fold cannot roll"))?;
crate::vfs::sync_file(f, &segment::seg_path(&self.dir, self.active))
.context("fsync before roll")?;
// The segment being sealed gets its directory sidecar now — the write that turns the next
// open's full scan of it into a 2 KB read. Best-effort, AFTER the fsync above: advisory
// data must never fail a roll, and a sidecar must never describe bytes less durable than
// itself.
let mut entries: Vec<(u32, u32)> = self
.blockdir
.iter()
.enumerate()
.filter_map(|(id, e)| match e {
Some((s, o)) if *s == self.active => Some((id as u32, *o)),
_ => None,
})
.collect();
entries.sort_by_key(|&(_, off)| off);
let _ = segment::write_dir_sidecar(&self.dir, self.active, self.cur_off, &entries);
let next = self
.active
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("segment number space exhausted"))?;
let f = segment::create_flagged(&self.dir, next, [0u8; 32], flags)?;
let reader = Arc::new(segment::open_rw(&self.dir, next)?);
self.active_f = Some(f);
self.headers.push(SegHeader { seg: next, flags, dict_id: [0u8; 32] });
self.readers.push(reader);
self.active = next;
self.cur_off = SEG_HDR_LEN as u32;
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct BlockStorage {
pub block_id: u32,
pub raw_bytes: u32,
pub stored_bytes: u32,
}
/// Compression threads: 0 means one per core.
fn nthreads(cfg: usize) -> usize {
if cfg > 0 {
cfg
} else {
// wasm32 has no threads; the pool compresses inline there, so asking for more than one
// worker would be meaningless.
#[cfg(target_arch = "wasm32")]
{
1
}
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
}
}
}
fn list_segments_with_limits(
dir: &Path,
read_limits: crate::read_limits::ReadLimits,
) -> Result<Vec<u32>> {
let mut out = Vec::new();
let mut visited = 0u64;
for e in std::fs::read_dir(dir)? {
visited = visited.saturating_add(1);
read_limits.admit_directory_entries("fold directory", visited)?;
let e = e?;
if let Some(n) = segment::parse_seg_name(&e.file_name().to_string_lossy()) {
out.push(n);
}
}
Ok(out)
}
fn count_fold_directory_entries(
dir: &Path,
read_limits: crate::read_limits::ReadLimits,
) -> Result<u64> {
Ok(fold_directory_shape(dir, read_limits)?.0)
}
fn fold_directory_shape(
dir: &Path,
read_limits: crate::read_limits::ReadLimits,
) -> Result<(u64, bool, bool)> {
let mut visited = 0u64;
let mut has_lock = false;
let mut has_segment = false;
for entry in std::fs::read_dir(dir)? {
visited = visited.saturating_add(1);
read_limits.admit_directory_entries("fold directory", visited)?;
let entry = entry?;
let name = entry.file_name();
let name = name.to_string_lossy();
has_lock |= name == "WRITER.lock";
has_segment |= segment::parse_seg_name(&name).is_some();
}
Ok((visited, has_lock, has_segment))
}
fn install_block_location(
blockdir: &mut Vec<Option<(u32, u32)>>,
next_block: &mut u32,
seen_blocks: &mut u64,
id: u32,
location: (u32, u32),
read_limits: crate::read_limits::ReadLimits,
) -> Result<()> {
let required_ids = u64::from(id) + 1;
let required_entries = seen_blocks.saturating_add(1);
read_limits.admit_fold_blocks(required_ids)?;
read_limits.admit_fold_blocks(required_entries)?;
if blockdir.len() <= id as usize {
blockdir.resize(id as usize + 1, None);
}
if blockdir[id as usize].replace(location).is_some() {
bail!("fold block id {id} appears more than once in one generation");
}
*seen_blocks = required_entries;
*next_block = (*next_block)
.max(id.checked_add(1).ok_or_else(|| anyhow::anyhow!("fold block id space exhausted"))?);
Ok(())
}
/// Exclusive writer lock held for the fold's whole lifetime — the single-writer invariant.
///
/// Enforced by the OS *on Unix*. On `wasm32-wasip1` `sys::lock_exclusive` succeeds unconditionally,
/// so this creates the file and gates nothing: there the invariant IS convention, and it is the
/// embedder's to keep.
pub(crate) fn acquire_writer_lock(dir: &Path) -> Result<File> {
let path = dir.join("WRITER.lock");
let f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&path)
.with_context(|| format!("open {}", path.display()))?;
if !crate::sys::lock_exclusive(&f).with_context(|| format!("locking {}", path.display()))? {
return Err(WriterLocked { path: dir.to_path_buf() }.into());
}
Ok(f)
}