1use std::cell::RefCell;
20use std::fs::{File, OpenOptions};
21use std::io::{BufWriter, Read, Write};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
25
26use xxhash_rust::xxh3::xxh3_64;
27
28use crate::sort::block::{BlockDecoder, BlockEncoder};
29use crate::sort::entry::SortEntry;
30use crate::sort::error::SortRunError;
31use crate::sort::reclaim;
32use crate::tiles_error::{Result, TilesError};
33
34const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
36
37const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
41
42pub const RUN_EXTENSION: &str = "run";
44
45const MAGIC: [u8; 4] = *b"GLRN";
47const LAYOUT: u8 = 1;
49const HEADER_LEN: usize = 8;
51const KIND_BLOCK: u8 = 1;
53const KIND_END: u8 = 0xFF;
55const BLOCK_HEADER_LEN: usize = 20;
58const END_LEN: usize = 24;
60const MAX_RAW_BLOCK: usize = 256 * 1024 * 1024;
62
63const BLOCK_RAW_TARGET: usize = 512 * 1024;
65const ZSTD_LEVEL: i32 = 3;
67
68thread_local! {
69 static DECOMPRESSOR: RefCell<Option<zstd::bulk::Decompressor<'static>>> =
73 const { RefCell::new(None) };
74
75 static PACKED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
78}
79
80fn io_error(op: &'static str, path: &Path) -> impl FnOnce(std::io::Error) -> TilesError {
81 let path = path.to_path_buf();
82 move |source| SortRunError::Io { op, path, source }.into()
83}
84
85pub struct ChunkSink {
90 dir: PathBuf,
92 chunk_paths: Vec<PathBuf>,
94 counter: Arc<AtomicU32>,
96}
97
98impl ChunkSink {
99 pub fn new(dir: PathBuf) -> Result<Self> {
108 std::fs::create_dir_all(&dir).map_err(|source| TilesError::CreateChunkDir {
109 path: dir.clone(),
110 source,
111 })?;
112 Ok(Self {
113 dir,
114 chunk_paths: Vec::new(),
115 counter: Arc::new(AtomicU32::new(0)),
116 })
117 }
118
119 pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
125 Self {
126 dir,
127 chunk_paths: Vec::new(),
128 counter,
129 }
130 }
131
132 pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
142 let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
143 let path = self.dir.join(format!("chunk_{id:06}.{RUN_EXTENSION}"));
144 write_run(&path, entries)?;
145 self.chunk_paths.push(path.clone());
146 Ok(path)
147 }
148
149 #[must_use]
151 pub fn chunk_paths(&self) -> &[PathBuf] {
152 &self.chunk_paths
153 }
154
155 #[must_use]
157 pub const fn chunk_count(&self) -> usize {
158 self.chunk_paths.len()
159 }
160
161 #[must_use]
163 pub fn into_chunk_paths(self) -> Vec<PathBuf> {
164 self.chunk_paths
165 }
166
167 pub fn cleanup(&self) -> Result<()> {
173 for path in &self.chunk_paths {
174 if path.exists() {
175 std::fs::remove_file(path).map_err(io_error("remove", path))?;
176 }
177 }
178 Ok(())
179 }
180}
181
182pub(crate) trait RunFile: Write {
186 fn make_durable(&mut self) -> std::io::Result<()>;
189}
190
191impl RunFile for BufWriter<File> {
192 fn make_durable(&mut self) -> std::io::Result<()> {
193 self.flush()?;
194 self.get_ref().sync_all()
195 }
196}
197
198fn write_run(path: &Path, entries: &[SortEntry]) -> Result<()> {
204 let file = File::create(path).map_err(io_error("create", path))?;
205 let mut out = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
206 let result = write_run_to(&mut out, path, entries);
207 if result.is_err() {
208 drop(out);
213 let _ = std::fs::remove_file(path);
214 return result;
215 }
216 geolith::output::sync_parent_dir(path).map_err(io_error("sync the folder of", path))
220}
221
222pub(crate) fn write_run_to<W: RunFile>(
224 out: &mut W,
225 path: &Path,
226 entries: &[SortEntry],
227) -> Result<()> {
228 let write = |out: &mut W, bytes: &[u8]| out.write_all(bytes).map_err(io_error("write", path));
229
230 let mut header = [0u8; HEADER_LEN];
231 header[..4].copy_from_slice(&MAGIC);
232 header[4] = LAYOUT;
233 write(out, &header)?;
234
235 let mut compressor =
236 zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
237 let mut encoder = BlockEncoder::new();
238 let mut raw = Vec::new();
239 let mut packed = Vec::new();
240 let (mut blocks, mut total) = (0u64, 0u64);
241
242 let mut close_block = |encoder: &mut BlockEncoder,
243 out: &mut W,
244 blocks: &mut u64,
245 total: &mut u64|
246 -> Result<()> {
247 raw.clear();
248 let count = encoder.finish_into(&mut raw);
249 if raw.len() > MAX_RAW_BLOCK {
250 return Err(SortRunError::BadHeader {
251 path: path.to_path_buf(),
252 at: *blocks,
253 what: "an entry is too large for a block",
254 }
255 .into());
256 }
257 packed.clear();
258 packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
259 compressor
260 .compress_to_buffer(&raw, &mut packed)
261 .map_err(io_error("compress", path))?;
262 let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
263 head[0] = KIND_BLOCK;
264 head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
265 head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
266 head[9..13].copy_from_slice(&count.to_le_bytes());
267 head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
268 write(out, &head)?;
269 write(out, &packed)?;
270 *blocks += 1;
271 *total += u64::from(count);
272 Ok(())
273 };
274
275 for entry in entries {
276 encoder
277 .push(entry)
278 .map_err(|source| SortRunError::BadBlock {
279 path: path.to_path_buf(),
280 block: blocks,
281 source,
282 })?;
283 if encoder.raw_len() >= BLOCK_RAW_TARGET {
284 close_block(&mut encoder, out, &mut blocks, &mut total)?;
285 }
286 }
287 if !encoder.is_empty() {
288 close_block(&mut encoder, out, &mut blocks, &mut total)?;
289 }
290
291 let mut end = [0u8; 1 + END_LEN];
292 end[0] = KIND_END;
293 end[1..9].copy_from_slice(&total.to_le_bytes());
294 end[9..17].copy_from_slice(&blocks.to_le_bytes());
295 let checksum = xxh3_64(&end[..17]);
296 end[17..25].copy_from_slice(&checksum.to_le_bytes());
297 write(out, &end)?;
298 out.make_durable().map_err(io_error("sync", path))?;
299 Ok(())
300}
301
302pub struct SortBuffer {
305 entries: Vec<SortEntry>,
306 approx_bytes: usize,
308 max_bytes: usize,
310}
311
312impl SortBuffer {
313 #[must_use]
315 pub fn new() -> Self {
316 Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
317 }
318
319 #[must_use]
321 pub fn with_max_bytes(max_bytes: usize) -> Self {
322 Self {
323 entries: Vec::with_capacity(1024),
324 approx_bytes: 0,
325 max_bytes,
326 }
327 }
328
329 #[inline]
333 pub fn push(&mut self, entry: SortEntry) -> bool {
334 self.approx_bytes +=
336 58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
337 self.entries.push(entry);
338 self.approx_bytes >= self.max_bytes
339 }
340
341 pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
349 if self.entries.is_empty() {
350 return Ok(());
351 }
352 self.entries.sort_unstable();
353 sink.write_chunk(&self.entries)?;
354 self.entries.clear();
355 self.approx_bytes = 0;
356 Ok(())
357 }
358
359 #[must_use]
361 pub const fn is_empty(&self) -> bool {
362 self.entries.is_empty()
363 }
364
365 #[must_use]
367 pub const fn len(&self) -> usize {
368 self.entries.len()
369 }
370}
371
372impl Default for SortBuffer {
373 fn default() -> Self {
374 Self::new()
375 }
376}
377
378pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
388 let mut reader = ChunkReader::open(path)?;
389 let mut entries = Vec::new();
390 while let Some(entry) = reader.take()? {
391 entries.push(entry);
392 }
393 Ok(entries)
394}
395
396pub struct ChunkReader {
401 path: PathBuf,
402 file: File,
403 decoder: BlockDecoder,
404 peeked: Option<SortEntry>,
406 exhausted: bool,
408 position: u64,
410 blocks: u64,
411 entries: u64,
412 reclaim: bool,
415 reclaimed: u64,
417}
418
419impl ChunkReader {
420 pub fn open(path: &Path) -> Result<Self> {
427 Self::open_with(path, false)
428 }
429
430 pub fn open_reclaiming(path: &Path) -> Result<Self> {
441 Self::open_with(path, true)
442 }
443
444 fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
445 let file = OpenOptions::new()
446 .read(true)
447 .write(reclaim)
448 .open(path)
449 .map_err(io_error("open", path))?;
450 let mut reader = Self {
451 path: path.to_path_buf(),
452 file,
453 decoder: BlockDecoder::empty(),
454 peeked: None,
455 exhausted: false,
456 position: 0,
457 blocks: 0,
458 entries: 0,
459 reclaim,
460 reclaimed: 0,
461 };
462 reader.read_header()?;
463 reader.advance()?;
464 Ok(reader)
465 }
466
467 #[inline]
469 #[must_use]
470 pub const fn peek(&self) -> Option<&SortEntry> {
471 self.peeked.as_ref()
472 }
473
474 pub fn take(&mut self) -> Result<Option<SortEntry>> {
480 let entry = self.peeked.take();
481 if entry.is_some() {
482 self.advance()?;
483 }
484 Ok(entry)
485 }
486
487 #[inline]
489 #[must_use]
490 pub const fn is_exhausted(&self) -> bool {
491 self.exhausted
492 }
493
494 fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
495 let mut done = 0;
496 while done < buf.len() {
497 match self.file.read(&mut buf[done..]) {
498 Ok(0) => break,
499 Ok(n) => done += n,
500 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
501 Err(source) => return Err(io_error("read", &self.path)(source)),
502 }
503 }
504 self.position += done as u64;
505 if done == buf.len() {
506 Ok(true)
507 } else if done == 0 {
508 Ok(false)
509 } else {
510 Err(self.truncated())
511 }
512 }
513
514 fn truncated(&self) -> TilesError {
515 SortRunError::Truncated {
516 path: self.path.clone(),
517 at: self.position,
518 }
519 .into()
520 }
521
522 fn read_header(&mut self) -> Result<()> {
523 let mut header = [0u8; HEADER_LEN];
524 if !self.fill(&mut header)? {
525 return Err(SortRunError::NotARun {
526 path: self.path.clone(),
527 }
528 .into());
529 }
530 if header[..4] != MAGIC {
531 return Err(SortRunError::NotARun {
532 path: self.path.clone(),
533 }
534 .into());
535 }
536 if header[4] != LAYOUT {
537 return Err(SortRunError::UnsupportedLayout {
538 path: self.path.clone(),
539 found: header[4],
540 expected: LAYOUT,
541 }
542 .into());
543 }
544 Ok(())
545 }
546
547 fn advance(&mut self) -> Result<()> {
550 if self.exhausted {
551 return Ok(());
552 }
553 if self.decoder.remaining() == 0 && !self.load_block()? {
554 return Ok(());
555 }
556 let entry = self
557 .decoder
558 .next_entry()
559 .map_err(|source| SortRunError::BadBlock {
560 path: self.path.clone(),
561 block: self.blocks.saturating_sub(1),
562 source,
563 })?;
564 if self.decoder.remaining() == 0 {
565 self.decoder
566 .check_complete()
567 .map_err(|source| SortRunError::BadBlock {
568 path: self.path.clone(),
569 block: self.blocks.saturating_sub(1),
570 source,
571 })?;
572 }
573 self.peeked = Some(entry);
574 Ok(())
575 }
576
577 fn load_block(&mut self) -> Result<bool> {
579 loop {
580 let at = self.position;
581 let mut kind = [0u8; 1];
582 if !self.fill(&mut kind)? {
583 return Err(self.truncated());
584 }
585 match kind[0] {
586 KIND_END => {
587 self.read_end(at)?;
588 return Ok(false);
589 }
590 KIND_BLOCK => {}
591 _ => {
592 return Err(SortRunError::BadHeader {
593 path: self.path.clone(),
594 at,
595 what: "unknown record kind",
596 }
597 .into());
598 }
599 }
600 let mut head = [0u8; BLOCK_HEADER_LEN];
601 if !self.fill(&mut head)? {
602 return Err(self.truncated());
603 }
604 let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
605 let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
606 let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
607 let checksum = u64::from_le_bytes([
608 head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
609 ]);
610 if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
611 return Err(SortRunError::BadHeader {
612 path: self.path.clone(),
613 at,
614 what: "block size out of range",
615 }
616 .into());
617 }
618 let path = self.path.clone();
619 let block = self.blocks;
620 let produced = PACKED.with(|packed_cell| -> Result<usize> {
621 let mut packed = packed_cell.borrow_mut();
622 packed.resize(packed_len, 0);
623 if !self.fill(&mut packed)? && packed_len != 0 {
624 return Err(self.truncated());
625 }
626 if xxh3_64(&packed) != checksum {
627 return Err(SortRunError::BadChecksum {
628 path: path.clone(),
629 block,
630 at,
631 }
632 .into());
633 }
634 let buffer = self.decoder.buffer();
635 buffer.clear();
636 buffer.reserve(raw_len);
637 DECOMPRESSOR
638 .with(|cell| -> std::io::Result<usize> {
639 let mut slot = cell.borrow_mut();
640 if slot.is_none() {
641 *slot = Some(zstd::bulk::Decompressor::new()?);
642 }
643 let decompressor = slot
644 .as_mut()
645 .ok_or_else(|| std::io::Error::other("no decompressor"))?;
646 decompressor.decompress_to_buffer(&packed[..], buffer)
647 })
648 .map_err(|source| SortRunError::Io {
649 op: "decompress",
650 path: path.clone(),
651 source,
652 })
653 .map_err(TilesError::from)
654 })?;
655 if produced != raw_len {
656 return Err(SortRunError::BadHeader {
657 path: self.path.clone(),
658 at,
659 what: "block decompresses to another size",
660 }
661 .into());
662 }
663 self.decoder
664 .load(count)
665 .map_err(|source| SortRunError::BadBlock {
666 path: self.path.clone(),
667 block,
668 source,
669 })?;
670 self.blocks += 1;
671 self.entries += u64::from(count);
672 self.release_read_bytes();
673 if count == 0 {
674 continue;
675 }
676 return Ok(true);
677 }
678 }
679
680 fn release_read_bytes(&mut self) {
683 if !self.reclaim {
684 return;
685 }
686 if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
687 self.reclaimed = upto;
688 }
689 }
690
691 fn read_end(&mut self, at: u64) -> Result<()> {
692 let mut end = [0u8; END_LEN];
693 if !self.fill(&mut end)? {
694 return Err(self.truncated());
695 }
696 let mut signed = [0u8; 17];
697 signed[0] = KIND_END;
698 signed[1..].copy_from_slice(&end[..16]);
699 let checksum = u64::from_le_bytes([
700 end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
701 ]);
702 if xxh3_64(&signed) != checksum {
703 return Err(SortRunError::BadHeader {
704 path: self.path.clone(),
705 at,
706 what: "end marker fails its checksum",
707 }
708 .into());
709 }
710 let entries = u64::from_le_bytes([
711 end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
712 ]);
713 let blocks = u64::from_le_bytes([
714 end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
715 ]);
716 if entries != self.entries || blocks != self.blocks {
717 return Err(SortRunError::CountMismatch {
718 path: self.path.clone(),
719 expected: entries,
720 found: self.entries,
721 }
722 .into());
723 }
724 let mut extra = [0u8; 1];
725 if self.fill(&mut extra)? {
726 return Err(SortRunError::TrailingBytes {
727 path: self.path.clone(),
728 }
729 .into());
730 }
731 self.exhausted = true;
732 if self.reclaim
733 && let Err(e) = std::fs::remove_file(&self.path)
734 {
735 tracing::warn!(
741 "could not delete the consumed run {}: {e}",
742 self.path.display()
743 );
744 }
745 Ok(())
746 }
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752
753 use std::sync::Arc;
754
755 use geolith::layer::Layer;
756 use geolith::tile::feature::{GeomType, TileFeature};
757
758 fn make_entry(key: u64) -> SortEntry {
759 SortEntry::new(
760 key,
761 TileFeature {
762 layer: Layer::Buildings,
763 id: key,
764 geom_type: GeomType::Polygon,
765 geometry: vec![9, 0, 0],
766 properties: Arc::new(vec![]),
767 sort_key: 0,
768 },
769 )
770 }
771
772 #[test]
773 fn roundtrip_chunk_write_read() {
774 let dir = tempfile::tempdir().expect("tmpdir");
775 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
776
777 let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
778 entries.sort_unstable();
779 sink.write_chunk(&entries).expect("write");
780
781 let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
782 assert_eq!(read_back.len(), 100);
783 for window in read_back.windows(2) {
785 assert!(window[0].key <= window[1].key);
786 }
787 }
788
789 #[test]
790 fn sort_buffer_flush_threshold() {
791 let mut buf = SortBuffer::with_max_bytes(100);
792 let mut full = false;
793 for i in 0..1000 {
794 if buf.push(make_entry(i)) {
795 full = true;
796 break;
797 }
798 }
799 assert!(full, "buffer should fill up");
800 assert!(!buf.is_empty());
801 }
802
803 #[test]
804 fn chunk_reader_streaming() {
805 let dir = tempfile::tempdir().expect("tmpdir");
806 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
807
808 let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
809 sink.write_chunk(&entries).expect("write");
810
811 let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
812 let mut count = 0;
813 while !reader.is_exhausted() {
814 let entry = reader.take().expect("take");
815 if entry.is_some() {
816 count += 1;
817 }
818 }
819 assert_eq!(count, 50);
820 }
821
822 struct FailAfter {
825 limit: usize,
826 taken: usize,
827 sync_fails: bool,
828 }
829
830 impl Write for FailAfter {
831 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
832 let room = self.limit - self.taken;
833 if room == 0 && !buf.is_empty() {
834 return Err(std::io::Error::from_raw_os_error(28));
836 }
837 let n = room.min(buf.len());
838 self.taken += n;
839 Ok(n)
840 }
841
842 fn flush(&mut self) -> std::io::Result<()> {
843 Ok(())
844 }
845 }
846
847 impl RunFile for FailAfter {
848 fn make_durable(&mut self) -> std::io::Result<()> {
849 if self.sync_fails {
850 Err(std::io::Error::from_raw_os_error(5))
852 } else {
853 Ok(())
854 }
855 }
856 }
857
858 fn noisy_entries(count: u64) -> Vec<SortEntry> {
859 (0..count)
860 .map(|i| {
861 let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
862 x ^= x >> 29;
863 make_entry_with(
864 i,
865 (0..16).map(|j| (x.rotate_left(j) & 0xFFF) as u32).collect(),
866 )
867 })
868 .collect()
869 }
870
871 fn make_entry_with(key: u64, geometry: Vec<u32>) -> SortEntry {
872 SortEntry::new(
873 key,
874 TileFeature {
875 layer: Layer::Buildings,
876 id: key.wrapping_mul(0xBF58_476D_1CE4_E5B9),
877 geom_type: GeomType::Polygon,
878 geometry,
879 properties: Arc::new(vec![]),
880 sort_key: 0,
881 },
882 )
883 }
884
885 #[test]
886 fn a_run_whose_write_fails_at_any_byte_is_an_error_that_names_the_file() {
887 let entries = noisy_entries(30_000);
888 let path = Path::new("/sort/chunk_000007.run");
889 let mut whole = FailAfter {
890 limit: usize::MAX,
891 taken: 0,
892 sync_fails: false,
893 };
894 write_run_to(&mut whole, path, &entries).expect("room enough");
895 let size = whole.taken;
896 assert!(
897 size > BLOCK_RAW_TARGET,
898 "the run has several blocks: {size}"
899 );
900
901 let mut limits: Vec<usize> = vec![0, 1, 7, 8, 9, 28, 29, size / 3, size / 2, size - 26];
902 limits.extend((1..=24).map(|k| size - k));
903 limits.extend((1..60).map(|k| k * size / 61));
904 for limit in limits {
905 let mut sink = FailAfter {
906 limit,
907 taken: 0,
908 sync_fails: false,
909 };
910 let err = write_run_to(&mut sink, path, &entries).expect_err(&format!(
911 "a disk full after {limit} of {size} bytes must fail"
912 ));
913 let text = geolith::error::report(&err);
914 assert!(text.contains("chunk_000007.run"), "{text}");
915 assert!(text.contains("os error 28"), "{text}");
916 assert!(
917 matches!(
918 err,
919 TilesError::SortRun(SortRunError::Io { op: "write", .. })
920 ),
921 "{text}"
922 );
923 }
924 let mut exact = FailAfter {
925 limit: size,
926 taken: 0,
927 sync_fails: false,
928 };
929 write_run_to(&mut exact, path, &entries).expect("exactly enough room");
930 }
931
932 #[test]
933 fn a_failed_sync_fails_the_run() {
934 let entries = noisy_entries(100);
935 let path = Path::new("/sort/chunk_000001.run");
936 let mut sink = FailAfter {
937 limit: usize::MAX,
938 taken: 0,
939 sync_fails: true,
940 };
941 let err = write_run_to(&mut sink, path, &entries).expect_err("sync fails");
942 let text = geolith::error::report(&err);
943 assert!(text.contains("sync /sort/chunk_000001.run"), "{text}");
944 assert!(text.contains("os error 5"), "{text}");
945 }
946
947 #[test]
948 fn a_run_that_fails_on_disk_leaves_no_file_behind() {
949 let dir = tempfile::tempdir().expect("tmpdir");
950 let entries = vec![make_entry_with(9, vec![1]), make_entry_with(3, vec![1])];
952 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
953 assert!(sink.write_chunk(&entries).is_err());
954 let left: Vec<_> = std::fs::read_dir(dir.path())
955 .expect("read")
956 .map(|e| e.expect("entry").path())
957 .collect();
958 assert!(left.is_empty(), "a failed run was left behind: {left:?}");
959 assert_eq!(sink.chunk_count(), 0, "a failed run is not listed");
960 }
961}