znippy-common 0.14.1

Core logic and data structures for Znippy, a parallel chunked compression system.
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
//! **A body file**: one body a stack owns in a file of its own, written beside the stack's
//! writer, and named by a commit where it lies (the plan's "segment"; the word is not used,
//! because a hot layer's journal files are its segments).
//!
//! ```text
//!   <S>.b<n>.stage   a body being staged: written by a [`BodyStage`], locked by the kernel
//!                      (flock) while its writer lives
//!   <S>.b<n>         a body file a commit named: the stage's file under its body name (a hard
//!                      link); never written again, never copied, and removed only by an
//!                      ordered GC (StackWriter::gc), once no live row names it
//! ```
//!
//! * **Written once.** The body is written as it comes, beside the stack's writer, holding none
//!   of its locks: a slow body (a download) holds no writer of the stack. The commit that names
//!   it writes a row and moves no byte. The stage and the commit may be two processes: the one
//!   that staged the body hands its [`BodyFile`] to the one that commits it
//!   ([`StackOp::PutBody`](crate::StackOp::PutBody)) and holds its stage until the answer.
//! * **The commit's order**: the stage's file gets its body name (synced), then the row is
//!   written (durable), then the stage's name goes. A cut after the body name leaves a body file
//!   no row names ([`BodyFiles::unnamed`]): it lies there until an ordered GC. A cut after the
//!   row leaves a stage a row names: the next open finishes its body name.
//! * **Debris.** A stage dropped before its end (a failed or refused body) removes its file at
//!   once: no row can name a body that was never sealed. A stage dropped after its end leaves its
//!   name, unless its body name is made, since its writer cannot know whether another process
//!   named it. The next `StackWriter::open` judges every stage nobody holds: one a row names gets
//!   its body name, every other goes. No clock is read.
//! * **One hasher.** Each piece of [`STREAM_PIECE`](crate::STREAM_PIECE) bytes is hashed once,
//!   as it passes, into its BLAKE3 *chaining value* (a piece that starts at a multiple of its
//!   size is a whole subtree of BLAKE3's tree; lblake3's `hazmat`, pure Rust). Its row keeps
//!   each piece's chaining value as that chunk's checksum, and the whole body's BLAKE3, merged
//!   from them with no second read: the ordinary BLAKE3 of the body.
//! * **Checked a piece at a time.** A reader checks each piece against its chaining value at its
//!   offset, and a bad piece ends the body before it goes out.
//! * **A body within its first piece** never becomes a file: it stays in memory, and the commit
//!   that names it lays it into the hot layer (one write, compressed when that is smaller), its
//!   BLAKE3 the chunk's: it is not hashed again.
//! * **A body file is a sealed znippy file**: its pieces (raw, or each compressed when that is
//!   smaller, as the hot layer lays a body), then its tail: its row (the links codec) and its
//!   stack section (`kind=body`). Its seal is the BLAKE3 of the tail, as every sealed file's
//!   ([`seal_id`](crate::seal_id)). A row names it by number and seal ([`BodyFile`]); a commit
//!   and a read check the seal first.

use std::fs::File;
use std::io::Write;
use std::os::unix::fs::{FileExt, MetadataExt};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use anyhow::{Result, anyhow, bail, ensure};
use blake3::hazmat::{
    HasherExt, Mode, left_subtree_len, merge_subtrees_non_root, merge_subtrees_root,
};

use crate::codec::CompressCtx;
use crate::hot::{Expect, Staged};
use crate::index::ChunkLoc;
use crate::rows::{BlobRef, Group, Pack, RowEntry, sync_dir_of};
use crate::stack::{StackPaths, StackSection, id_of};

/// **A body file of a stack, as a row names it**: `<S>.b<number>`, sealed `seal` (the BLAKE3 of
/// its tail). What a process that staged a body hands to the process that commits it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BodyFile {
    pub number: u64,
    pub seal: [u8; 32],
}

/// **The body files of a stack, as its rows name them**
/// ([`StackWriter::body_files`](crate::StackWriter::body_files)). A body file no row names is
/// one a commit was cut after naming (its row never written): it lies there until an ordered
/// GC removes it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct BodyFiles {
    /// Body files a row of the stack names.
    pub named: usize,
    /// Body files no row names, and their bytes.
    pub unnamed: usize,
    pub unnamed_bytes: u64,
}

/// **A body being staged beside a stack's writer** (see the module docs): a [`Write`] that
/// takes the body's bytes as they come, writes each where it stays and hashes it once, with no
/// buffer of its own past the body's first piece (a compressible body: the piece being
/// compressed). [`finish`](Self::finish) makes it a [`Staged`], which
/// [`StackWriter::commit`](crate::StackWriter::commit) names.
pub struct BodyStage {
    paths: StackPaths,
    name: String,
    level: i32,
    policy: crate::SkipPolicy,
    piece: u64,
    /// The body's first piece while the body is within it; then, for a compressible body, the
    /// piece being filled.
    held: Vec<u8>,
    /// The stage's file, once the body passed its first piece.
    stage: Option<Arc<StageFile>>,
    raw: bool,
    /// The piece being hashed, from its offset.
    hasher: blake3::Hasher,
    /// Each whole piece's chaining value, and its chunk.
    cvs: Vec<[u8; 32]>,
    chunks: Vec<ChunkLoc>,
    size: u64,
    /// Where the next stored byte goes in the stage's file.
    cursor: u64,
    written: u64,
    hashed: u64,
    ctx: Option<CompressCtx>,
    frame: Vec<u8>,
}

impl BodyStage {
    /// A stage of a body called `name` (its name tells whether it is stored raw, as for every
    /// body: [`SkipPolicy`](crate::SkipPolicy)) for the stack at `root`, compressed at `level`
    /// when it is not. Nothing is made on disk until the body passes its first piece.
    pub fn new(root: &Path, name: &str, level: i32, policy: crate::SkipPolicy) -> Result<Self> {
        let paths = StackPaths::new(root)?;
        ensure!(
            paths.dir().is_dir(),
            "stack: no directory {} to stage a body in",
            paths.dir().display()
        );
        Ok(Self {
            paths,
            name: name.to_string(),
            level,
            policy,
            piece: crate::STREAM_PIECE as u64,
            held: Vec::new(),
            stage: None,
            raw: true,
            hasher: blake3::Hasher::new(),
            cvs: Vec::new(),
            chunks: Vec::new(),
            size: 0,
            cursor: 0,
            written: 0,
            hashed: 0,
            ctx: None,
            frame: Vec::new(),
        })
    }

    /// A test's own piece (a power of two, at least BLAKE3's chunk).
    #[cfg(test)]
    pub(crate) fn with_piece(mut self, piece: u64) -> Self {
        assert!(piece.is_power_of_two() && piece >= blake3::CHUNK_LEN as u64);
        self.piece = piece;
        self
    }

    /// The bytes taken so far.
    pub fn size(&self) -> u64 {
        self.size
    }

    /// `bytes`, the body's next: hashed, and written where they stay (or held while the body is
    /// within its first piece).
    fn take(&mut self, mut bytes: &[u8]) -> Result<()> {
        while !bytes.is_empty() {
            let Some(stage) = self.stage.clone() else {
                let room = self.piece as usize - self.held.len();
                if room == 0 {
                    // A byte past the first piece: the body becomes a file.
                    self.spill()?;
                    continue;
                }
                let n = room.min(bytes.len());
                self.hash(&bytes[..n]);
                self.held.extend_from_slice(&bytes[..n]);
                bytes = &bytes[n..];
                continue;
            };
            let into = self.size % self.piece;
            let n = usize::try_from(self.piece - into).map_or(bytes.len(), |r| r.min(bytes.len()));
            let part = &bytes[..n];
            self.hash(part);
            if self.raw {
                stage.file.write_all_at(part, self.cursor)?;
                self.cursor += n as u64;
                self.written += n as u64;
            } else {
                self.held.extend_from_slice(part);
            }
            if self.size.is_multiple_of(self.piece) {
                self.close_piece()?;
            }
            bytes = &bytes[n..];
        }
        Ok(())
    }

    fn hash(&mut self, bytes: &[u8]) {
        self.hasher.update(bytes);
        self.hashed += bytes.len() as u64;
        self.size += bytes.len() as u64;
    }

    /// **The body passed its first piece**: its stage's file is made (and locked), raw or not is
    /// told by its name and first bytes, and the first piece is laid there.
    fn spill(&mut self) -> Result<()> {
        let listing = self.paths.list()?;
        let top = (listing.bodies.keys().chain(listing.stages.keys())).max();
        let (number, file) = create_stage(&self.paths, top.map_or(1, |n| n + 1))?;
        self.stage = Some(Arc::new(StageFile {
            file: Arc::new(file),
            number,
            path: self.paths.body_stage(number),
            body: self.paths.body(number),
            sealed: AtomicBool::new(false),
        }));
        let first = &self.held[..self.held.len().min(crate::SNIFF_PREFIX_LEN)];
        self.raw =
            self.policy.skip_by_path(Path::new(&self.name)) || self.policy.skip_by_bytes(first);
        if self.raw {
            let stage = self.stage.as_ref().expect("just made");
            stage.file.write_all_at(&self.held, 0)?;
            self.cursor = self.held.len() as u64;
            self.written = self.cursor;
            // Raw, the pieces after the first are written as they come: no buffer is kept.
            self.held = Vec::new();
        } else {
            self.ctx = Some(CompressCtx::new(self.level)?);
        }
        self.close_piece()
    }

    /// **The piece being taken is whole** (or the body ended in it): its chaining value, and its
    /// chunk; a compressible body's piece is compressed and written now, kept compressed when
    /// that is smaller. The next piece's hasher starts at its offset.
    fn close_piece(&mut self) -> Result<()> {
        let stage = Arc::clone(self.stage.as_ref().expect("a body in a file"));
        let start = self.cvs.len() as u64 * self.piece;
        let len = self.size - start;
        let cv = self.hasher.finalize_non_root();
        let (blob_offset, blob_size, compressed) = if self.raw {
            (self.cursor - len, len, false)
        } else {
            let ctx = self.ctx.as_mut().expect("made at the spill");
            ctx.compress_into(&self.held, &mut self.frame)?;
            let (on_disk, compressed): (&[u8], bool) = match self.frame.len() < self.held.len() {
                true => (&self.frame, true),
                false => (&self.held, false),
            };
            stage.file.write_all_at(on_disk, self.cursor)?;
            let at = self.cursor;
            let n = on_disk.len() as u64;
            self.cursor += n;
            self.written += n;
            self.held.clear();
            (at, n, compressed)
        };
        self.chunks.push(ChunkLoc {
            chunk_seq: u32::try_from(self.cvs.len())?,
            fdata_offset: start,
            blob_offset,
            blob_size,
            uncompressed_size: len,
            compressed,
            checksum: cv,
        });
        self.cvs.push(cv);
        if self.size.is_multiple_of(self.piece) {
            // A whole piece: the body may go on, at the next piece's offset.
            self.hasher = blake3::Hasher::new();
            self.hasher.set_input_offset(self.size);
        }
        Ok(())
    }

    /// **The body staged**, as `expect` says it must be: its last piece hashed, the whole BLAKE3
    /// merged with no second read, its tail written and synced. A body refused leaves no file. A
    /// body within its first piece stays in memory, staged to be laid by the commit that names
    /// it.
    pub fn finish(mut self, expect: &Expect) -> Result<Staged> {
        let Some(stage) = self.stage.clone() else {
            let blake3 = *self.hasher.finalize().as_bytes();
            check(expect, self.size, blake3)?;
            let bytes = Arc::new(std::mem::take(&mut self.held));
            return Ok(Staged::in_memory(
                std::mem::take(&mut self.name),
                bytes,
                blake3,
                self.hashed,
            ));
        };
        if !self.size.is_multiple_of(self.piece) {
            self.close_piece()?;
        }
        let whole = root_of(&self.cvs, self.piece, self.size);
        check(expect, self.size, whole)?;
        let own = BlobRef::new(None, self.chunks.clone(), Some(whole));
        let row = RowEntry {
            group: Group::default(),
            name: std::mem::take(&mut self.name),
            slot: Some(own),
        };
        crate::stack::write_base(
            Arc::clone(&stage.file),
            self.cursor,
            &StackSection::body(stage.number),
            &[],
            std::slice::from_ref(&row),
            None,
        )?;
        let seal = seal_of(&stage.file)?;
        sync_dir_of(&stage.path);
        let f = BodyFile {
            number: stage.number,
            seal,
        };
        let at = BlobRef::new(
            Some(Pack::Body(f)),
            std::mem::take(&mut self.chunks),
            Some(whole),
        );
        // Sealed, a row may name it from now on: its drop leaves its name to the next open.
        stage.sealed.store(true, Ordering::Release);
        Ok(Staged::in_file(
            stage,
            at,
            self.size,
            whole,
            self.written,
            self.hashed,
        ))
    }
}

impl Write for BodyStage {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.take(bytes).map_err(std::io::Error::other)?;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// The body as `expect` says it must be, else why not.
fn check(expect: &Expect, size: u64, blake3: [u8; 32]) -> Result<()> {
    if let Some(want) = expect.size {
        ensure!(
            want == size,
            "the body is {size} bytes, {want} were expected"
        );
    }
    if let Some(want) = expect.blake3 {
        ensure!(want == blake3, "the body's BLAKE3 is not the one expected");
    }
    Ok(())
}

/// The chaining value of `bytes`, a piece that starts `offset` bytes into its body.
#[cfg(test)]
pub(crate) fn chaining_value(bytes: &[u8], offset: u64) -> [u8; 32] {
    let mut h = blake3::Hasher::new();
    h.set_input_offset(offset);
    h.update(bytes);
    h.finalize_non_root()
}

/// **The BLAKE3 of a body of `len` bytes, more than one `piece`**, merged from its pieces'
/// chaining values `cvs` (one per piece, in order) the way BLAKE3's tree joins them: each left
/// subtree is the largest power of two of chunks below the whole, so it is whole pieces.
pub(crate) fn root_of(cvs: &[[u8; 32]], piece: u64, len: u64) -> [u8; 32] {
    debug_assert!(cvs.len() >= 2 && len > piece);
    let left = left_subtree_len(len);
    let k = usize::try_from(left / piece).expect("pieces fit");
    let l = subtree(&cvs[..k], piece, left);
    let r = subtree(&cvs[k..], piece, len - left);
    *merge_subtrees_root(&l, &r, Mode::Hash).as_bytes()
}

/// The chaining value of the subtree of `len` bytes whose pieces are `cvs`.
fn subtree(cvs: &[[u8; 32]], piece: u64, len: u64) -> [u8; 32] {
    if let [one] = cvs {
        return *one;
    }
    let left = left_subtree_len(len);
    let k = usize::try_from(left / piece).expect("pieces fit");
    let l = subtree(&cvs[..k], piece, left);
    let r = subtree(&cvs[k..], piece, len - left);
    merge_subtrees_non_root(&l, &r, Mode::Hash)
}

/// The seal of a sealed file open as `file`: the BLAKE3 of its tail.
fn seal_of(file: &File) -> Result<[u8; 32]> {
    let tail = crate::stack::read_tail(file)?;
    Ok(*blake3::hash(&tail.bytes).as_bytes())
}

/// **The row of the body file `f`, open as `file`**, as the stack names it: its seal checked
/// first, then that it is body file `f.number` and holds one body in pieces.
fn body_row(file: &File, f: BodyFile) -> Result<BlobRef> {
    let rows = crate::stack::load_sealed(file)
        .map_err(|e| anyhow!("stack: body file {}: {e:#}", f.number))?;
    ensure!(
        rows.seal == f.seal,
        "stack: body file {} is sealed {}, the row names {}: another body",
        f.number,
        hex::encode(rows.seal),
        hex::encode(f.seal)
    );
    ensure!(
        rows.section == Some(StackSection::body(f.number)),
        "stack: body file {} says it is {:?}",
        f.number,
        rows.section
    );
    let g = Group::default();
    let names: Vec<_> = rows.index.slots(&g).collect();
    let [(_, Some(own))] = names.as_slice() else {
        bail!(
            "stack: body file {} holds no body, or more than one",
            f.number
        );
    };
    ensure!(
        own.pack.is_none() && own.chunks.len() >= 2 && own.body_checksum.is_some(),
        "stack: body file {} holds no body in pieces",
        f.number
    );
    Ok(BlobRef::new(
        Some(Pack::Body(f)),
        own.chunks.clone(),
        own.body_checksum,
    ))
}

/// **The body file `f` named for a commit**: its row (the seal checked), its body name made from
/// its stage when it has none yet (the caller syncs the directory before any row names it), and
/// the stage's name, which goes once the row is durable.
pub(crate) fn name_body(paths: &StackPaths, f: BodyFile) -> Result<(BlobRef, Option<PathBuf>)> {
    let body = paths.body(f.number);
    let stage = paths.body_stage(f.number);
    match File::open(&body) {
        Ok(file) => {
            // Named before (a second name, or a cut commit's): the same body, by its seal.
            let at = body_row(&file, f)?;
            let both = id_of(&stage).is_some() && id_of(&stage) == id_of(&body);
            return Ok((at, both.then_some(stage)));
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => bail!("stack: body file {}: {}: {e}", f.number, body.display()),
    }
    let file = File::open(&stage).map_err(|e| {
        anyhow!(
            "stack: body file {}: no body file and no stage ({e}): its writer ended before the \
             commit, and it was removed as debris",
            f.number
        )
    })?;
    let at = body_row(&file, f)?;
    std::fs::hard_link(&stage, &body).map_err(|e| {
        anyhow!(
            "stack: body file {}: name {}: {e}",
            f.number,
            body.display()
        )
    })?;
    let m = file.metadata()?;
    ensure!(
        id_of(&body) == Some((m.dev(), m.ino())),
        "stack: body file {}: its stage changed while it was named",
        f.number
    );
    Ok((at, Some(stage)))
}

/// **A named stage's name goes** (its row durable): only when the file under it is the body
/// file's, under its body name.
pub(crate) fn let_stage_go(paths: &StackPaths, stage: &Path) {
    let Some(n) = number_of_stage(stage) else {
        return;
    };
    if id_of(stage).is_some() && id_of(stage) == id_of(&paths.body(n)) {
        let _ = std::fs::remove_file(stage);
    }
}

fn number_of_stage(stage: &Path) -> Option<u64> {
    let name = stage.file_name()?.to_str()?.strip_suffix(".stage")?;
    name.rsplit_once(".b")?.1.parse().ok()
}

/// **A stage at a writer's open** (`<S>.b<n>.stage`): held, it stays (its writer lives). Nobody
/// holds it: when a row names the body it holds (`named`: the seal a row names number `n` by)
/// and its body name is not there, the name is finished; then the stage's name goes.
pub(crate) fn settle_stage(paths: &StackPaths, n: u64, named: Option<[u8; 32]>) -> Result<()> {
    let stage = paths.body_stage(n);
    let file = match File::open(&stage) {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => bail!("stack: {}: {e}", stage.display()),
    };
    match file.try_lock() {
        Ok(()) => {}
        Err(std::fs::TryLockError::WouldBlock) => return Ok(()),
        Err(std::fs::TryLockError::Error(e)) => bail!("stack: lock {}: {e}", stage.display()),
    }
    let body = paths.body(n);
    if let Some(seal) = named
        && id_of(&body).is_none()
        && seal_of(&file).ok() == Some(seal)
    {
        std::fs::hard_link(&stage, &body)
            .map_err(|e| anyhow!("stack: body file {n}: name {}: {e}", body.display()))?;
        sync_dir_of(&body);
    }
    match std::fs::remove_file(&stage) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
            bail!("stack: remove {}: {e}", stage.display())
        }
        _ => Ok(()),
    }
}

/// **A body file gone** from where a row names it, or another under its name: a GC removed it
/// since the reader read the row.
#[derive(Debug)]
pub(crate) struct BodyGone {
    pub number: u64,
    pub why: String,
}

impl std::fmt::Display for BodyGone {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "stack: body file {}: {}", self.number, self.why)
    }
}

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

/// **The bytes of the body file `f`** that the row `b` names, for a reader: open at its body
/// name (or at its stage, when a row is durable and its body name is not yet), its seal
/// checked, the row's chunks inside its blob region.
pub(crate) fn body_blob(paths: &StackPaths, b: BlobRef, f: BodyFile) -> Result<crate::Blob> {
    let gone = |why: String| {
        anyhow::Error::new(BodyGone {
            number: f.number,
            why,
        })
    };
    let path = paths.body(f.number);
    let file = match File::open(&path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            File::open(paths.body_stage(f.number))
                .map_err(|_| gone(format!("{}: {e}", path.display())))?
        }
        Err(e) => bail!("stack: {}: {e}", path.display()),
    };
    let tail = crate::stack::read_tail(&file).map_err(|e| gone(format!("{e:#}")))?;
    let seal = *blake3::hash(&tail.bytes).as_bytes();
    if seal != f.seal {
        return Err(gone(format!(
            "sealed {}, the row names {}",
            hex::encode(seal),
            hex::encode(f.seal)
        )));
    }
    ensure!(
        b.end() <= tail.start,
        "stack: a row names bytes past body file {}'s pieces",
        f.number
    );
    Ok(crate::Blob::new(Arc::new(file), b))
}

/// **A new stage's file** `<S>.b<n>.stage`, made and locked at the first number from `from` up
/// that no other stage took first and no named body file has ([`BodyStage`] starts one above
/// every body file and stage it lists).
pub(crate) fn create_stage(paths: &StackPaths, from: u64) -> Result<(u64, File)> {
    let mut n = from.max(1);
    loop {
        let path = paths.body_stage(n);
        let file = match std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(&path)
        {
            Ok(f) => f,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                n += 1;
                continue;
            }
            Err(e) => bail!("stack: create {}: {e}", path.display()),
        };
        match file.try_lock() {
            Ok(()) => {}
            // A writer's open took it for debris before this stage locked it: it goes.
            Err(std::fs::TryLockError::WouldBlock) => {
                n += 1;
                continue;
            }
            Err(std::fs::TryLockError::Error(e)) => bail!("stack: lock {}: {e}", path.display()),
        }
        let m = file.metadata()?;
        if id_of(&path) != Some((m.dev(), m.ino())) {
            // Removed as debris between its making and its lock.
            n += 1;
            continue;
        }
        if id_of(&paths.body(n)).is_some() {
            // A body file of that number is named: its number is not staged again.
            let _ = std::fs::remove_file(&path);
            n += 1;
            continue;
        }
        sync_dir_of(&path);
        return Ok((n, file));
    }
}

/// **A body file nobody holds** at `path` is removed (an ordered GC, which found no live row
/// naming it). One a stage's writer holds stays. Whether it was removed.
pub(crate) fn remove_unheld(path: &Path) -> Result<bool> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => bail!("stack: {}: {e}", path.display()),
    };
    match file.try_lock() {
        Ok(()) => {
            std::fs::remove_file(path)
                .map_err(|e| anyhow!("stack: remove {}: {e}", path.display()))?;
            Ok(true)
        }
        Err(std::fs::TryLockError::WouldBlock) => Ok(false),
        Err(std::fs::TryLockError::Error(e)) => bail!("stack: lock {}: {e}", path.display()),
    }
}

/// **The file of a stage**, shared by the [`Staged`]s made of it, locked while any lives. When
/// the last goes: a stage never sealed takes its name with it (no row can name it); a sealed one
/// does only when its body name is made (the same file under both names), and otherwise leaves
/// its name for the next open to judge.
#[derive(Debug)]
pub(crate) struct StageFile {
    pub(crate) file: Arc<File>,
    pub(crate) number: u64,
    /// `<S>.b<number>.stage`.
    pub(crate) path: PathBuf,
    /// Its body name, `<S>.b<number>`.
    body: PathBuf,
    sealed: AtomicBool,
}

impl Drop for StageFile {
    fn drop(&mut self) {
        let Ok(m) = self.file.metadata() else { return };
        let me = Some((m.dev(), m.ino()));
        if id_of(&self.path) != me {
            return;
        }
        if !self.sealed.load(Ordering::Acquire) || id_of(&self.body) == me {
            let _ = std::fs::remove_file(&self.path);
            sync_dir_of(&self.path);
        }
    }
}

#[cfg(all(test, feature = "openzl"))]
mod tests {
    use super::*;
    use crate::hot::stream_tests::{noise, text};
    use crate::stack::{StackPaths, StopAt};
    use crate::{
        GcPolicy, Group, HotCommitReport, Lookup, SkipPolicy, StackOp, StackView, StackWriter,
    };
    use std::io::{BufRead, BufReader};
    use std::os::unix::fs::FileExt;
    use std::process::{Child, ChildStdin, Command, Stdio};

    /// A test's piece: small, so a body of many pieces is quick. The real one is STREAM_PIECE.
    const P: u64 = 64 << 10;

    fn raw() -> SkipPolicy {
        SkipPolicy::already_compressed()
    }

    fn files_of(dir: &Path) -> Vec<String> {
        let mut v: Vec<String> = std::fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .collect();
        v.sort();
        v
    }

    fn bodies_of(dir: &Path) -> Vec<String> {
        files_of(dir)
            .into_iter()
            .filter(|f| f.contains(".znippy.b"))
            .collect()
    }

    /// `body` staged for the stack at `root`, written in uneven parts as a socket hands them.
    fn stage(root: &Path, name: &str, body: &[u8], policy: SkipPolicy) -> Staged {
        let mut s = BodyStage::new(root, name, 3, policy).unwrap().with_piece(P);
        for part in body.chunks(7001) {
            s.write_all(part).unwrap();
        }
        s.finish(&Expect::default()).unwrap()
    }

    fn put(w: &mut StackWriter, g: &Group, name: &str, staged: Staged) -> HotCommitReport {
        let op = StackOp::Put {
            group: g.clone(),
            name: name.to_string(),
            staged,
        };
        w.commit(vec![op]).unwrap()
    }

    fn read_w(w: &StackWriter, g: &Group, name: &str) -> Option<Vec<u8>> {
        w.get(g, name).unwrap().map(|b| b.read_verified().unwrap())
    }

    fn read_v(v: &StackView, g: &Group, name: &str) -> Option<Vec<u8>> {
        v.get(g, name).unwrap().map(|b| b.read_verified().unwrap())
    }

    fn read_fresh(root: &Path, g: &Group, name: &str) -> Option<Vec<u8>> {
        read_v(&StackView::open(root).unwrap(), g, name)
    }

    fn hash(bytes: &[u8]) -> [u8; 32] {
        *blake3::hash(bytes).as_bytes()
    }

    /// **The whole BLAKE3 merged from the pieces' chaining values is the ordinary BLAKE3**, at
    /// every length around the pieces' edges, for pieces of several sizes, and through a stage
    /// of the real piece.
    #[test]
    fn the_whole_blake3_merged_from_the_pieces_is_the_ordinary_one() {
        for piece in [1024u64, 2048, 8192] {
            let lens = [
                piece + 1,
                2 * piece,
                2 * piece + 1,
                3 * piece,
                3 * piece + 5,
                4 * piece,
                5 * piece + 1023,
                7 * piece,
                8 * piece + 1,
                13 * piece + 17,
                16 * piece,
                17 * piece + 1,
            ];
            for len in lens {
                let data = noise(len, len);
                let cvs: Vec<[u8; 32]> = (data.chunks(piece as usize).enumerate())
                    .map(|(i, p)| chaining_value(p, i as u64 * piece))
                    .collect();
                assert_eq!(
                    root_of(&cvs, piece, len),
                    hash(&data),
                    "pieces of {piece}, {len} bytes"
                );
            }
        }
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let body = noise(3, 2 * crate::STREAM_PIECE as u64 + 3);
        let mut s = BodyStage::new(&root, "real.whl", 3, raw()).unwrap();
        s.write_all(&body).unwrap();
        let staged = s.finish(&Expect::default()).unwrap();
        assert_eq!(staged.blake3(), hash(&body), "the real piece");
        assert_eq!(staged.hashed(), body.len() as u64, "hashed once");
    }

    /// **A body staged beside the writer is written once, and named where it lies**: its bytes
    /// are written to its body file as they come and hashed once; the commit that names it moves
    /// no byte (the hot layer's file does not grow) and makes three fsyncs (its body name, its
    /// row, its stage's name gone), and its row keeps the ordinary BLAKE3. It
    /// reads back through the writer, a view and a new open, after a seal and after a fold, which
    /// copies none of it.
    #[test]
    fn a_body_staged_beside_the_writer_is_written_once_and_named_where_it_lies() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::new(2, "pypi");
        let body = noise(7, 5 * P + 1000);
        let len = body.len() as u64;
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        w.append_from(&g, "small", &mut &b"small"[..], &Expect::default())
            .unwrap();
        let hot = dir.path().join("acct.znippy.g1.open");
        let hot_len = std::fs::metadata(&hot).unwrap().len();
        let staged = stage(&root, "big.whl", &body, raw());
        assert_eq!(
            (staged.size(), staged.written(), staged.hashed()),
            (len, len, len),
            "every byte written once and hashed once"
        );
        assert_eq!(staged.blake3(), hash(&body));
        let f = staged
            .body_file()
            .expect("a body past its first piece lies in a body file");
        assert_eq!(f.number, 1);
        assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1.stage"]);
        let read: Vec<u8> = (staged.pieces(P as usize).unwrap())
            .flat_map(|p| p.unwrap())
            .collect();
        assert_eq!(read, body, "the stage reads before any row names it");
        let synced = w.fsyncs();
        let r = put(&mut w, &g, "big.whl", staged);
        assert_eq!(r.bytes_laid, 0, "the commit moves no byte: {r:?}");
        assert_eq!(
            w.fsyncs() - synced,
            3,
            "its body name, its row, its stage's name gone"
        );
        assert_eq!(
            std::fs::metadata(&hot).unwrap().len(),
            hot_len,
            "the hot layer's file did not grow"
        );
        assert_eq!(
            bodies_of(dir.path()),
            ["acct.znippy.b1"],
            "named where it lies"
        );
        let Lookup::Live(b) = w.lookup(&g, "big.whl") else {
            panic!("live")
        };
        assert_eq!(b.body_file(), Some(f));
        assert_eq!(b.chunks.len(), 6, "one chunk per piece");
        assert_eq!(w.checksum(&g, "big.whl"), Some(hash(&body)), "row 98");
        assert_eq!(read_w(&w, &g, "big.whl"), Some(body.clone()), "the writer");
        let v = StackView::open(&root).unwrap();
        assert_eq!(read_v(&v, &g, "big.whl"), Some(body.clone()), "a view");
        assert_eq!(v.checksum_in(&g, "big.whl"), Some(hash(&body)));
        w.seal_layer(None).unwrap();
        assert_eq!(
            read_fresh(&root, &g, "big.whl"),
            Some(body.clone()),
            "sealed"
        );
        let r = w.compact(None).unwrap();
        assert_eq!((r.bytes_copied, r.body_files_kept), (0, 1), "{r:?}");
        assert_eq!(read_w(&w, &g, "big.whl"), Some(body.clone()), "folded");
        assert_eq!(read_fresh(&root, &g, "big.whl"), Some(body.clone()));
        drop((w, v));
        let w = StackWriter::open(&root, 3, raw()).unwrap();
        assert_eq!(read_w(&w, &g, "big.whl"), Some(body), "opened again");
        assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1"]);
    }

    /// **A bad piece ends the body before it goes out**: each piece is checked against its
    /// chaining value at its offset, so the pieces before it are read and it is not.
    #[test]
    fn a_bad_piece_ends_the_body_before_it_goes_out() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::default();
        let body = noise(8, 4 * P + 10);
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        let staged = stage(&root, "x.whl", &body, raw());
        put(&mut w, &g, "x.whl", staged);
        let f = std::fs::OpenOptions::new()
            .write(true)
            .open(dir.path().join("acct.znippy.b1"))
            .unwrap();
        f.write_all_at(&[!body[(2 * P + 100) as usize]], 2 * P + 100)
            .unwrap();
        drop(f);
        let v = StackView::open(&root).unwrap();
        let blob = v.get(&g, "x.whl").unwrap().unwrap();
        let got: Vec<Result<Vec<u8>>> = blob.pieces(P as usize, true).unwrap().collect();
        assert_eq!(got.len(), 3, "two good pieces, then the bad one's error");
        assert_eq!(got[0].as_ref().unwrap()[..], body[..P as usize]);
        assert_eq!(
            got[1].as_ref().unwrap()[..],
            body[P as usize..2 * P as usize]
        );
        let err = got[2].as_ref().unwrap_err();
        assert!(format!("{err:#}").contains("chunk 2"), "{err:#}");
    }

    /// **A body within its first piece stays in memory**: no file is made, nothing is written
    /// until the commit lays it into the hot layer, once (compressed when that is smaller), with
    /// two fsyncs (the body, then its row), and it is hashed once. The staged body says what the
    /// commit wrote of it.
    #[test]
    fn a_body_within_its_first_piece_stays_in_memory_and_is_laid_at_the_commit() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::default();
        let mut w = StackWriter::open(&root, 3, SkipPolicy::resolve()).unwrap();
        let cases: [(&str, Vec<u8>, bool); 4] = [
            ("whole.whl", noise(1, P), false),
            ("short.whl", noise(2, P - 1), false),
            ("empty.whl", Vec::new(), false),
            ("data.txt", text(P), true),
        ];
        for (name, body, compressed) in cases {
            let len = body.len() as u64;
            let staged = stage(&root, name, &body, SkipPolicy::resolve());
            assert!(staged.body_file().is_none(), "{name}");
            assert_eq!((staged.written(), staged.hashed()), (0, len), "{name}");
            assert!(bodies_of(dir.path()).is_empty(), "{name}: no file is made");
            let synced = w.fsyncs();
            let r = put(&mut w, &g, name, staged.clone());
            match compressed {
                false => assert_eq!(r.bytes_laid, len, "{name}: laid once"),
                true => assert!(0 < r.bytes_laid && r.bytes_laid < len, "{name}: {r:?}"),
            }
            assert_eq!(staged.written(), r.bytes_laid, "{name}: what the commit wrote");
            let fsyncs = w.fsyncs() - synced;
            match len {
                0 => assert_eq!(fsyncs, 1, "{name}: no bytes, its row"),
                _ => assert_eq!(fsyncs, 2, "{name}: the body, then its row"),
            }
            assert_eq!(w.checksum(&g, name), Some(hash(&body)), "{name}");
            assert_eq!(read_fresh(&root, &g, name), Some(body), "{name}");
        }
    }

    /// **A compressible body file is compressed a piece at a time**, each piece kept compressed
    /// when that is smaller; it is still hashed once, and reads back checked.
    #[test]
    fn a_compressible_body_file_is_compressed_piece_by_piece() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::new(1, "raw");
        let body = text(3 * P + 1);
        let mut w = StackWriter::open(&root, 3, SkipPolicy::resolve()).unwrap();
        let staged = stage(&root, "data.txt", &body, SkipPolicy::resolve());
        assert!(staged.body_file().is_some());
        assert!(
            staged.written() < staged.size(),
            "compressed: {}",
            staged.written()
        );
        assert_eq!(staged.hashed(), staged.size());
        put(&mut w, &g, "data.txt", staged);
        assert_eq!(w.checksum(&g, "data.txt"), Some(hash(&body)));
        assert_eq!(read_fresh(&root, &g, "data.txt"), Some(body));
    }

    /// **A stage that no one holds and no row names is debris, and one that is held is not**: a
    /// stage dropped while it was written leaves no file, nor does one refused at its end (no row
    /// can name a body that was never sealed). A stage dropped after its end leaves its name for
    /// the next open of a writer to judge (its writer cannot know that no other process named
    /// it): no row names it, so the open removes it. A stage's file that its writer left without
    /// its drop (as a process that died) is removed by the next open too, while one a live stage
    /// holds stays and is named after.
    #[test]
    fn a_stage_that_no_one_holds_is_debris_and_one_that_is_held_is_not() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::default();
        drop(StackWriter::open(&root, 3, raw()).unwrap());
        {
            let mut s = BodyStage::new(&root, "a.whl", 3, raw())
                .unwrap()
                .with_piece(P);
            s.write_all(&noise(1, 2 * P)).unwrap();
            assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1.stage"]);
        }
        assert!(
            bodies_of(dir.path()).is_empty(),
            "dropped while it was written"
        );
        drop(stage(&root, "b.whl", &noise(2, 2 * P), raw()));
        assert_eq!(
            bodies_of(dir.path()),
            ["acct.znippy.b1.stage"],
            "staged: its drop leaves the stage to the open"
        );
        drop(StackWriter::open(&root, 3, raw()).unwrap());
        assert!(
            bodies_of(dir.path()).is_empty(),
            "staged and never named: debris"
        );
        let mut s = BodyStage::new(&root, "c.whl", 3, raw())
            .unwrap()
            .with_piece(P);
        s.write_all(&noise(3, 2 * P)).unwrap();
        let refused = s.finish(&Expect {
            size: Some(1),
            blake3: None,
        });
        assert!(refused.is_err());
        assert!(bodies_of(dir.path()).is_empty(), "refused at its end");

        let mut held = BodyStage::new(&root, "d.whl", 3, raw())
            .unwrap()
            .with_piece(P);
        held.write_all(&noise(4, 2 * P)).unwrap();
        std::fs::write(dir.path().join("acct.znippy.b9.stage"), b"cut").unwrap();
        drop(StackWriter::open(&root, 3, raw()).unwrap());
        assert_eq!(
            bodies_of(dir.path()),
            ["acct.znippy.b1.stage"],
            "the held stage stays, the cut one goes"
        );
        let staged = held.finish(&Expect::default()).unwrap();
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        put(&mut w, &g, "d.whl", staged);
        drop(w);
        drop(StackWriter::open(&root, 3, raw()).unwrap());
        assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1"], "named, it stays");
        assert_eq!(read_fresh(&root, &g, "d.whl"), Some(noise(4, 2 * P)));
    }

    /// The writer process of the two-process test (`ZNIPPY_TEST_BODY_WRITER` names the stack):
    /// it stages a body, says which body file holds it, and waits for one line; then it ends with
    /// no drop of its stage, as a process that died.
    const WRITER: &str = "ZNIPPY_TEST_BODY_WRITER";

    fn writer_process(root: &Path) {
        let staged = stage(root, "w.whl", &noise(77, 3 * P + 5), raw());
        let f = staged.body_file().expect("a body file");
        println!("BODY {} {}", f.number, hex::encode(f.seal));
        std::io::stdout().flush().unwrap();
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        std::process::exit(0);
    }

    /// This test binary again, running only the test `test`, in the role the variable `role`
    /// gives it (`spec`).
    fn second_process(test: &str, role: &str, spec: &str) -> Command {
        let mut c = Command::new(std::env::current_exe().unwrap());
        c.args(["--exact", test, "--nocapture", "--test-threads", "1"])
            .env(role, spec);
        c
    }

    /// The writer process of `test` started for the stack at `root`, its body staged and held:
    /// the process, its stdin (a line ends it, as a death would), and the body file it names.
    fn spawn_writer(test: &str, root: &Path) -> (Child, ChildStdin, BodyFile) {
        let mut child = second_process(test, WRITER, root.to_str().unwrap())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        let mut out = BufReader::new(child.stdout.take().unwrap());
        let f = loop {
            let mut line = String::new();
            assert!(
                out.read_line(&mut line).unwrap() > 0,
                "the writer said nothing"
            );
            // libtest's own "test <name> ... " may lead the line.
            if let Some((_, rest)) = line.trim().split_once("BODY ") {
                let (n, seal) = rest.split_once(' ').unwrap();
                let seal: [u8; 32] = hex::decode(seal).unwrap().try_into().unwrap();
                break BodyFile {
                    number: n.parse().unwrap(),
                    seal,
                };
            }
        };
        let stdin = child.stdin.take().unwrap();
        (child, stdin, f)
    }

    /// **A body file written by one process is named by another** (Holger: the server's fetch
    /// job writes it, the account's process commits its row): while the writer lives its stage
    /// stays, whoever opens the stack; a writer that dies before the commit leaves debris, which
    /// the next open removes and no commit can name; one that dies after the commit leaves the
    /// body named, and it stays.
    #[test]
    fn a_body_file_written_by_one_process_is_named_by_another() {
        const ME: &str = "body::tests::a_body_file_written_by_one_process_is_named_by_another";
        if let Ok(root) = std::env::var(WRITER) {
            writer_process(Path::new(&root));
            return;
        }
        for dies_before in [true, false] {
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().join("acct.znippy");
            let g = Group::new(2, "pypi");
            let mut w = StackWriter::open(&root, 3, raw()).unwrap();
            let (mut child, mut stdin, f) = spawn_writer(ME, &root);
            drop(StackWriter::open(&root, 3, raw()).unwrap());
            assert_eq!(
                bodies_of(dir.path()),
                ["acct.znippy.b1.stage"],
                "held by its living writer"
            );
            let name_it = |w: &mut StackWriter| {
                w.commit(vec![StackOp::PutBody {
                    group: g.clone(),
                    name: "w.whl".into(),
                    body: f,
                }])
            };
            if dies_before {
                writeln!(stdin, "die").unwrap();
                child.wait().unwrap();
                drop(w);
                let mut w = StackWriter::open(&root, 3, raw()).unwrap();
                assert!(bodies_of(dir.path()).is_empty(), "debris, removed");
                let err = name_it(&mut w).expect_err("no commit names debris");
                assert!(format!("{err:#}").contains("body file 1"), "{err:#}");
            } else {
                name_it(&mut w).unwrap();
                writeln!(stdin, "die").unwrap();
                child.wait().unwrap();
                drop(w);
                drop(StackWriter::open(&root, 3, raw()).unwrap());
                assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1"], "named, kept");
                assert_eq!(read_fresh(&root, &g, "w.whl"), Some(noise(77, 3 * P + 5)));
            }
        }
    }

    /// The committer process of the cut test (`ZNIPPY_TEST_BODY_CUT`: the cut, the body file's
    /// number and seal, and the stack): it names the body file a writer process staged, and dies
    /// at the cut with nothing dropped, as a crash would.
    const CUT: &str = "ZNIPPY_TEST_BODY_CUT";

    fn committer_process(spec: &str) {
        let parts: Vec<&str> = spec.splitn(4, ' ').collect();
        let [cut, number, seal, root] = parts[..] else {
            panic!("{spec}")
        };
        let f = BodyFile {
            number: number.parse().unwrap(),
            seal: hex::decode(seal).unwrap().try_into().unwrap(),
        };
        let mut w = StackWriter::open(Path::new(root), 3, raw()).unwrap();
        w.stop = Some(match cut {
            "linked" => StopAt::BodyLinked,
            "row" => StopAt::BodyRowWritten,
            c => panic!("no cut {c}"),
        });
        let r = w.commit(vec![StackOp::PutBody {
            group: Group::new(2, "pypi"),
            name: "w.whl".into(),
            body: f,
        }]);
        eprintln!("the committer was not cut at {cut}: {r:?}");
        std::process::exit(3);
    }

    /// **A commit cut between naming a body file and its row loses no body** (main's two cuts, in
    /// two processes as in Holger, each dying with nothing dropped). The commit gives the stage its
    /// body name first (synced), then writes its row, then lets the stage's name go. Cut after
    /// the body name: no row names the body file; the next open lets its stage's name go and
    /// keeps the body file, which the status counts unnamed; an open never removes it, only an
    /// ordered GC does. Cut after the row: the open lets the stage's name go and the body reads.
    /// Cut after the row with the body name lost (a row durable, its body name not): a view reads
    /// the body at its stage, and the next open finishes the body name, never removing a stage a
    /// row names.
    #[test]
    fn a_commit_cut_between_its_body_name_and_its_row_loses_no_body() {
        const ME: &str =
            "body::tests::a_commit_cut_between_its_body_name_and_its_row_loses_no_body";
        if let Ok(root) = std::env::var(WRITER) {
            writer_process(Path::new(&root));
            return;
        }
        if let Ok(spec) = std::env::var(CUT) {
            committer_process(&spec);
            return;
        }
        let body = noise(77, 3 * P + 5);
        for (cut, name_lost) in [("linked", false), ("row", false), ("row", true)] {
            let case = format!(
                "{cut}{}",
                if name_lost {
                    ", its body name lost"
                } else {
                    ""
                }
            );
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().join("acct.znippy");
            let g = Group::new(2, "pypi");
            drop(StackWriter::open(&root, 3, raw()).unwrap());
            let (mut writer, mut stdin, f) = spawn_writer(ME, &root);
            let spec = format!(
                "{cut} {} {} {}",
                f.number,
                hex::encode(f.seal),
                root.display()
            );
            let status = (second_process(ME, CUT, &spec).stdout(Stdio::null()))
                .status()
                .unwrap();
            assert!(
                status.success(),
                "{case}: the committer died at its cut: {status}"
            );
            writeln!(stdin, "die").unwrap();
            writer.wait().unwrap();
            assert_eq!(
                bodies_of(dir.path()),
                ["acct.znippy.b1", "acct.znippy.b1.stage"],
                "{case}: its body name made, its stage's name not gone"
            );
            if name_lost {
                std::fs::remove_file(dir.path().join("acct.znippy.b1")).unwrap();
                assert_eq!(
                    read_fresh(&root, &g, "w.whl"),
                    Some(body.clone()),
                    "{case}: a view reads it at its stage"
                );
            }
            let w = StackWriter::open(&root, 3, raw()).unwrap();
            assert_eq!(
                bodies_of(dir.path()),
                ["acct.znippy.b1"],
                "{case}: one body file, its stage's name gone"
            );
            let counted = w.body_files().unwrap();
            if cut == "linked" {
                assert!(
                    matches!(w.lookup(&g, "w.whl"), Lookup::Absent),
                    "{case}: no row"
                );
                let len = std::fs::metadata(dir.path().join("acct.znippy.b1"))
                    .unwrap()
                    .len();
                assert_eq!(
                    (counted.named, counted.unnamed, counted.unnamed_bytes),
                    (0, 1, len),
                    "{case}: counted unnamed"
                );
                drop(w);
                let mut w = StackWriter::open(&root, 3, raw()).unwrap();
                assert_eq!(
                    bodies_of(dir.path()),
                    ["acct.znippy.b1"],
                    "{case}: an open keeps it"
                );
                let r = w.gc(GcPolicy { small: 64 << 10 }, None).unwrap();
                assert_eq!(r.body_files_removed, 1, "{case}: {r:?}");
                assert!(
                    bodies_of(dir.path()).is_empty(),
                    "{case}: the ordered GC removed it"
                );
            } else {
                assert_eq!(
                    (counted.named, counted.unnamed),
                    (1, 0),
                    "{case}: counted named"
                );
                assert_eq!(read_w(&w, &g, "w.whl"), Some(body.clone()), "{case}");
                assert_eq!(read_fresh(&root, &g, "w.whl"), Some(body.clone()), "{case}");
            }
        }
    }

    /// **Stages at once get files of their own**: a stage that finds its number taken takes the
    /// next; a named body file's number is never staged again while it lies there; and stages
    /// made at once from many threads each get a file, all named in one commit.
    #[test]
    fn stages_at_once_get_files_of_their_own() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let g = Group::default();
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        let paths = StackPaths::new(&root).unwrap();
        let (n1, f1) = create_stage(&paths, 1).unwrap();
        let (n2, f2) = create_stage(&paths, 1).unwrap();
        assert_eq!((n1, n2), (1, 2), "the number taken, the next");
        drop((f1, f2));
        for p in bodies_of(dir.path()) {
            std::fs::remove_file(dir.path().join(p)).unwrap();
        }
        put(
            &mut w,
            &g,
            "one",
            stage(&root, "one.whl", &noise(1, 2 * P), raw()),
        );
        let (n, f) = create_stage(&paths, 1).unwrap();
        assert_eq!(n, 2, "a named body file's number is not staged again");
        drop(f);
        std::fs::remove_file(dir.path().join("acct.znippy.b2.stage")).unwrap();

        let at_once = std::sync::Barrier::new(6);
        let staged: Vec<Staged> = std::thread::scope(|s| {
            let runs: Vec<_> = (0..6u64)
                .map(|i| {
                    let (root, at_once) = (&root, &at_once);
                    s.spawn(move || {
                        let mut b = BodyStage::new(root, "t.whl", 3, raw())
                            .unwrap()
                            .with_piece(P);
                        b.write_all(&noise(100 + i, P)).unwrap();
                        at_once.wait();
                        b.write_all(&noise(200 + i, P)).unwrap();
                        b.finish(&Expect::default()).unwrap()
                    })
                })
                .collect();
            runs.into_iter().map(|r| r.join().unwrap()).collect()
        });
        let mut numbers: Vec<u64> = staged
            .iter()
            .map(|s| s.body_file().unwrap().number)
            .collect();
        numbers.sort();
        numbers.dedup();
        assert_eq!(numbers.len(), 6, "six files: {numbers:?}");
        let ops = (staged.into_iter().enumerate())
            .map(|(i, staged)| StackOp::Put {
                group: g.clone(),
                name: format!("t{i}"),
                staged,
            })
            .collect();
        w.commit(ops).unwrap();
        for i in 0..6u64 {
            let mut want = noise(100 + i, P);
            want.extend(noise(200 + i, P));
            assert_eq!(read_w(&w, &g, &format!("t{i}")), Some(want), "t{i}");
        }
    }

    /// **Only an ordered GC removes a body file, and only when no live row names it** (the
    /// owner: a package is never deleted, only an ordered GC removes bytes; the caller decides
    /// what is live, by the rows it keeps). A GC keeps a body file a live row names, and never
    /// copies one, however small its policy's "small"; a fold and an open keep one no row names;
    /// the GC after removes it, and a view that read it before finds it gone without an error.
    #[test]
    fn only_an_ordered_gc_removes_a_body_file_and_only_when_no_live_row_names_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("acct.znippy");
        let (g, h) = (Group::new(2, "pypi"), Group::new(2, "virtual"));
        let body = noise(9, 3 * P + 7);
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        put(&mut w, &g, "a", stage(&root, "a.whl", &body, raw()));
        w.link(&h, "a-too", &g, "a").unwrap();
        w.end(&g, "a").unwrap();
        let v = StackView::open(&root).unwrap();
        assert_eq!(read_v(&v, &h, "a-too"), Some(body.clone()));
        let r = w.gc(GcPolicy { small: u64::MAX }, None).unwrap();
        assert_eq!(
            (r.body_files_kept, r.body_files_removed, r.bytes_copied),
            (1, 0, 0),
            "a live row names it, and no GC copies a body file: {r:?}"
        );
        assert_eq!(bodies_of(dir.path()), ["acct.znippy.b1"]);
        assert_eq!(read_w(&w, &h, "a-too"), Some(body.clone()));
        w.end(&h, "a-too").unwrap();
        w.compact(None).unwrap();
        assert_eq!(
            bodies_of(dir.path()),
            ["acct.znippy.b1"],
            "a fold removes no byte"
        );
        drop(w);
        let mut w = StackWriter::open(&root, 3, raw()).unwrap();
        assert_eq!(
            bodies_of(dir.path()),
            ["acct.znippy.b1"],
            "nor does an open"
        );
        let r = w.gc(GcPolicy { small: 64 << 10 }, None).unwrap();
        assert_eq!((r.body_files_kept, r.body_files_removed), (0, 1), "{r:?}");
        assert!(
            bodies_of(dir.path()).is_empty(),
            "the ordered GC removed it"
        );
        assert_eq!(
            v.get(&h, "a-too").unwrap().map(|_| ()),
            None,
            "a view finds it gone"
        );
    }
}