Skip to main content

geolith_tiles_builder/sort/
chunk.rs

1//! Sorted runs on disk: the spill files of the external sort.
2//!
3//! During Phase 1 (read + process), each rayon thread accumulates
4//! `SortEntry` items in a local buffer. When the buffer exceeds a size
5//! threshold, it is sorted by key and written as one run.
6//!
7//! A run is a header, a sequence of blocks and an end marker. A block holds a
8//! few thousand entries in the columnar layout of [`crate::sort::block`],
9//! compressed with zstd, with the xxh3 checksum of the compressed bytes in
10//! its header. The end marker holds the number of blocks and entries and its
11//! own checksum, so a run that was cut short, damaged or written by another
12//! version stops the reader with a [`SortRunError`] and never yields a wrong
13//! entry.
14//!
15//! The reader keeps one block in memory, so the k-way merge over thousands of
16//! runs stays small, and it can give the disk space of every block back to the
17//! file system as soon as the block is read (see [`ChunkReader::open_reclaiming`]).
18
19use 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
34/// Maximum uncompressed bytes per chunk before flushing (default 256 MB).
35const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
36
37/// Write buffer size for chunk files (8 MB).
38///
39/// Larger buffers reduce syscall overhead during Phase 1 writes.
40const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
41
42/// File extension of a run.
43pub const RUN_EXTENSION: &str = "run";
44
45/// The first four bytes of a run.
46const MAGIC: [u8; 4] = *b"GLRN";
47/// The layout of the blocks: columnar entries, zstd.
48const LAYOUT: u8 = 1;
49/// Bytes of the run header: magic, layout, three reserved.
50const HEADER_LEN: usize = 8;
51/// Record kind byte of a block.
52const KIND_BLOCK: u8 = 1;
53/// Record kind byte of the end marker.
54const KIND_END: u8 = 0xFF;
55/// Bytes of a block header after the kind byte: raw length, compressed
56/// length, entry count (`u32` each) and checksum (`u64`).
57const BLOCK_HEADER_LEN: usize = 20;
58/// Bytes of the end marker after the kind byte: entries, blocks and checksum.
59const END_LEN: usize = 24;
60/// The most bytes a block may take once decompressed; larger is a bad header.
61const MAX_RAW_BLOCK: usize = 256 * 1024 * 1024;
62
63/// A block closes once its columns hold this many bytes.
64const BLOCK_RAW_TARGET: usize = 512 * 1024;
65/// The zstd level of the blocks.
66const ZSTD_LEVEL: i32 = 3;
67
68thread_local! {
69    /// One decompression context per thread: the merge reads thousands of
70    /// runs from one thread, and a context per run would cost more memory
71    /// than the run's block.
72    static DECOMPRESSOR: RefCell<Option<zstd::bulk::Decompressor<'static>>> =
73        const { RefCell::new(None) };
74
75    /// The compressed bytes of the block being loaded, shared the same way:
76    /// they are needed only until the block is decompressed.
77    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
85/// Manages writing sorted chunk files to a temporary directory.
86///
87/// Each instance tracks its own chunk paths. Multiple sinks can share
88/// a single atomic counter to produce unique filenames across threads.
89pub struct ChunkSink {
90    /// Directory to store chunk files.
91    dir: PathBuf,
92    /// Paths of all chunk files written so far.
93    chunk_paths: Vec<PathBuf>,
94    /// Shared counter for generating unique chunk file names.
95    counter: Arc<AtomicU32>,
96}
97
98impl ChunkSink {
99    /// Create a new chunk sink writing to the given directory.
100    ///
101    /// Creates the directory if it doesn't exist. Uses a private counter
102    /// starting at 0 for chunk file naming.
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if creating the directory fails.
107    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    /// Create a per-thread chunk sink sharing a global chunk ID counter.
120    ///
121    /// The directory must already exist (caller creates it once).
122    /// The shared counter ensures chunk files have unique names across
123    /// all threads, eliminating the need for a global `Mutex`.
124    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    /// Write a sorted slice of entries to a new chunk file.
133    ///
134    /// The entries MUST already be sorted by key before calling this.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error if file creation or a write fails, if the entries
139    /// are not sorted by key, or if an entry holds a value the run layout
140    /// cannot store.
141    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    /// All chunk file paths written so far, in creation order.
150    #[must_use]
151    pub fn chunk_paths(&self) -> &[PathBuf] {
152        &self.chunk_paths
153    }
154
155    /// Number of chunk files written.
156    #[must_use]
157    pub const fn chunk_count(&self) -> usize {
158        self.chunk_paths.len()
159    }
160
161    /// Consume this sink and return all chunk file paths written.
162    #[must_use]
163    pub fn into_chunk_paths(self) -> Vec<PathBuf> {
164        self.chunk_paths
165    }
166
167    /// Clean up all chunk files.
168    ///
169    /// # Errors
170    ///
171    /// Returns an error if removing any chunk file fails.
172    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
182/// Where a run is written: a byte sink that can be made durable.
183///
184/// The seam is here so a test can fail a write, or the final sync, at any byte.
185pub(crate) trait RunFile: Write {
186    /// Push every byte written so far to the disk and report any error the
187    /// file system kept back until now (a full disk, for one).
188    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
198/// Write `entries` as a run at `path`.
199///
200/// Every write, the flush and the sync is checked. A run that fails is
201/// deleted again, so a half-written file is never left where `--resume`
202/// looks for runs.
203fn 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        // Close the file before removing it. The write error is the one that
209        // matters and is returned; a failure to remove the leftover cannot
210        // add to it, and a leftover run is refused loudly by the reader
211        // (no end marker), never read as a shorter run.
212        drop(out);
213        let _ = std::fs::remove_file(path);
214        return result;
215    }
216    // The run's data is synced; its name in the folder is made durable too, so
217    // a power loss cannot leave `--resume` without a run whose data was kept
218    // (the next step may delete the source file it came from).
219    geolith::output::sync_parent_dir(path).map_err(io_error("sync the folder of", path))
220}
221
222/// Write `entries` as a run to `out`; `path` names it in errors.
223pub(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
302/// A thread-local buffer that accumulates sort entries and flushes
303/// to a `ChunkSink` when the buffer exceeds the size threshold.
304pub struct SortBuffer {
305    entries: Vec<SortEntry>,
306    /// Approximate total serialized size in bytes.
307    approx_bytes: usize,
308    /// Flush threshold in bytes.
309    max_bytes: usize,
310}
311
312impl SortBuffer {
313    /// Create a new sort buffer with the default size threshold.
314    #[must_use]
315    pub fn new() -> Self {
316        Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
317    }
318
319    /// Create a new sort buffer with a custom size threshold.
320    #[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    /// Push an entry into the buffer.
330    ///
331    /// Returns `true` if the buffer is now full and should be flushed.
332    #[inline]
333    pub fn push(&mut self, entry: SortEntry) -> bool {
334        // Approximate size: 8 bytes key + ~50 bytes avg feature
335        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    /// Sort entries by key and flush to a chunk file via the sink.
342    ///
343    /// Clears the buffer after writing.
344    ///
345    /// # Errors
346    ///
347    /// Returns an error if sorting or chunk write fails.
348    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    /// Whether the buffer has pending entries.
360    #[must_use]
361    pub const fn is_empty(&self) -> bool {
362        self.entries.is_empty()
363    }
364
365    /// Number of entries in the buffer.
366    #[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
378/// Read all sort entries from a chunk file, in order.
379///
380/// This is a convenience for testing; the merge module uses
381/// `ChunkReader` for streaming reads.
382///
383/// # Errors
384///
385/// Returns an error if the run cannot be opened, is cut, damaged or of
386/// another layout.
387pub 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
396/// Streaming reader for a single chunk file.
397///
398/// Used by the k-way merge to read entries one at a time without
399/// loading the entire chunk into memory: one block is in memory at a time.
400pub struct ChunkReader {
401    path: PathBuf,
402    file: File,
403    decoder: BlockDecoder,
404    /// The next entry, pre-read for the merge heap.
405    peeked: Option<SortEntry>,
406    /// Whether we've reached the end of the chunk.
407    exhausted: bool,
408    /// Bytes read from the file so far.
409    position: u64,
410    blocks: u64,
411    entries: u64,
412    /// Give the disk space of blocks back as they are read, and delete the
413    /// file at its end.
414    reclaim: bool,
415    /// The file offset below which the space is already given back.
416    reclaimed: u64,
417}
418
419impl ChunkReader {
420    /// Open a chunk file for streaming reads.
421    ///
422    /// # Errors
423    ///
424    /// Returns an error if the file cannot be opened, is not a run of this
425    /// layout, or its first block is cut or damaged.
426    pub fn open(path: &Path) -> Result<Self> {
427        Self::open_with(path, false)
428    }
429
430    /// Open a chunk file for streaming reads that consume it: the disk space
431    /// of each block goes back to the file system once the block is read, and
432    /// the file is deleted when its last entry is taken.
433    ///
434    /// The run cannot be read again afterwards, so a build that is stopped
435    /// during the merge cannot resume from its chunks.
436    ///
437    /// # Errors
438    ///
439    /// As [`Self::open`].
440    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    /// The next entry, if any, without consuming it.
468    #[inline]
469    #[must_use]
470    pub const fn peek(&self) -> Option<&SortEntry> {
471        self.peeked.as_ref()
472    }
473
474    /// Take the next entry and advance the reader.
475    ///
476    /// # Errors
477    ///
478    /// Returns an error if reading or decoding the next entry fails.
479    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    /// Whether this reader has been fully consumed.
488    #[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    /// Read the next entry from the current block, loading the next block
548    /// or the end marker when the block is used up.
549    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    /// Load the next block. Returns `false` at the end marker.
578    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    /// The bytes before `position` are in memory now: give their disk space
681    /// back, in steps, never the bytes of a block that is still to be read.
682    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            // Every entry of the run was read and checked by now, so the
736            // archive does not depend on the file any more. The build removes
737            // the whole sort folder at its end; a file that stays until then
738            // only costs disk, and failing a build of many hours over it would
739            // cost more.
740            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        // Verify sorted order
784        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    /// A sink that takes `limit` bytes and then fails like a full disk, and
823    /// whose sync can fail too.
824    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                // ENOSPC
835                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                // EIO
851                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        // The entries are not sorted: the write fails after the file exists.
951        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}