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    }
215    result
216}
217
218/// Write `entries` as a run to `out`; `path` names it in errors.
219pub(crate) fn write_run_to<W: RunFile>(
220    out: &mut W,
221    path: &Path,
222    entries: &[SortEntry],
223) -> Result<()> {
224    let write = |out: &mut W, bytes: &[u8]| out.write_all(bytes).map_err(io_error("write", path));
225
226    let mut header = [0u8; HEADER_LEN];
227    header[..4].copy_from_slice(&MAGIC);
228    header[4] = LAYOUT;
229    write(out, &header)?;
230
231    let mut compressor =
232        zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
233    let mut encoder = BlockEncoder::new();
234    let mut raw = Vec::new();
235    let mut packed = Vec::new();
236    let (mut blocks, mut total) = (0u64, 0u64);
237
238    let mut close_block = |encoder: &mut BlockEncoder,
239                           out: &mut W,
240                           blocks: &mut u64,
241                           total: &mut u64|
242     -> Result<()> {
243        raw.clear();
244        let count = encoder.finish_into(&mut raw);
245        if raw.len() > MAX_RAW_BLOCK {
246            return Err(SortRunError::BadHeader {
247                path: path.to_path_buf(),
248                at: *blocks,
249                what: "an entry is too large for a block",
250            }
251            .into());
252        }
253        packed.clear();
254        packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
255        compressor
256            .compress_to_buffer(&raw, &mut packed)
257            .map_err(io_error("compress", path))?;
258        let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
259        head[0] = KIND_BLOCK;
260        head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
261        head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
262        head[9..13].copy_from_slice(&count.to_le_bytes());
263        head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
264        write(out, &head)?;
265        write(out, &packed)?;
266        *blocks += 1;
267        *total += u64::from(count);
268        Ok(())
269    };
270
271    for entry in entries {
272        encoder
273            .push(entry)
274            .map_err(|source| SortRunError::BadBlock {
275                path: path.to_path_buf(),
276                block: blocks,
277                source,
278            })?;
279        if encoder.raw_len() >= BLOCK_RAW_TARGET {
280            close_block(&mut encoder, out, &mut blocks, &mut total)?;
281        }
282    }
283    if !encoder.is_empty() {
284        close_block(&mut encoder, out, &mut blocks, &mut total)?;
285    }
286
287    let mut end = [0u8; 1 + END_LEN];
288    end[0] = KIND_END;
289    end[1..9].copy_from_slice(&total.to_le_bytes());
290    end[9..17].copy_from_slice(&blocks.to_le_bytes());
291    let checksum = xxh3_64(&end[..17]);
292    end[17..25].copy_from_slice(&checksum.to_le_bytes());
293    write(out, &end)?;
294    out.make_durable().map_err(io_error("sync", path))?;
295    Ok(())
296}
297
298/// A thread-local buffer that accumulates sort entries and flushes
299/// to a `ChunkSink` when the buffer exceeds the size threshold.
300pub struct SortBuffer {
301    entries: Vec<SortEntry>,
302    /// Approximate total serialized size in bytes.
303    approx_bytes: usize,
304    /// Flush threshold in bytes.
305    max_bytes: usize,
306}
307
308impl SortBuffer {
309    /// Create a new sort buffer with the default size threshold.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
313    }
314
315    /// Create a new sort buffer with a custom size threshold.
316    #[must_use]
317    pub fn with_max_bytes(max_bytes: usize) -> Self {
318        Self {
319            entries: Vec::with_capacity(1024),
320            approx_bytes: 0,
321            max_bytes,
322        }
323    }
324
325    /// Push an entry into the buffer.
326    ///
327    /// Returns `true` if the buffer is now full and should be flushed.
328    #[inline]
329    pub fn push(&mut self, entry: SortEntry) -> bool {
330        // Approximate size: 8 bytes key + ~50 bytes avg feature
331        self.approx_bytes +=
332            58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
333        self.entries.push(entry);
334        self.approx_bytes >= self.max_bytes
335    }
336
337    /// Sort entries by key and flush to a chunk file via the sink.
338    ///
339    /// Clears the buffer after writing.
340    ///
341    /// # Errors
342    ///
343    /// Returns an error if sorting or chunk write fails.
344    pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
345        if self.entries.is_empty() {
346            return Ok(());
347        }
348        self.entries.sort_unstable();
349        sink.write_chunk(&self.entries)?;
350        self.entries.clear();
351        self.approx_bytes = 0;
352        Ok(())
353    }
354
355    /// Whether the buffer has pending entries.
356    #[must_use]
357    pub const fn is_empty(&self) -> bool {
358        self.entries.is_empty()
359    }
360
361    /// Number of entries in the buffer.
362    #[must_use]
363    pub const fn len(&self) -> usize {
364        self.entries.len()
365    }
366}
367
368impl Default for SortBuffer {
369    fn default() -> Self {
370        Self::new()
371    }
372}
373
374/// Read all sort entries from a chunk file, in order.
375///
376/// This is a convenience for testing; the merge module uses
377/// `ChunkReader` for streaming reads.
378///
379/// # Errors
380///
381/// Returns an error if the run cannot be opened, is cut, damaged or of
382/// another layout.
383pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
384    let mut reader = ChunkReader::open(path)?;
385    let mut entries = Vec::new();
386    while let Some(entry) = reader.take()? {
387        entries.push(entry);
388    }
389    Ok(entries)
390}
391
392/// Streaming reader for a single chunk file.
393///
394/// Used by the k-way merge to read entries one at a time without
395/// loading the entire chunk into memory: one block is in memory at a time.
396pub struct ChunkReader {
397    path: PathBuf,
398    file: File,
399    decoder: BlockDecoder,
400    /// The next entry, pre-read for the merge heap.
401    peeked: Option<SortEntry>,
402    /// Whether we've reached the end of the chunk.
403    exhausted: bool,
404    /// Bytes read from the file so far.
405    position: u64,
406    blocks: u64,
407    entries: u64,
408    /// Give the disk space of blocks back as they are read, and delete the
409    /// file at its end.
410    reclaim: bool,
411    /// The file offset below which the space is already given back.
412    reclaimed: u64,
413}
414
415impl ChunkReader {
416    /// Open a chunk file for streaming reads.
417    ///
418    /// # Errors
419    ///
420    /// Returns an error if the file cannot be opened, is not a run of this
421    /// layout, or its first block is cut or damaged.
422    pub fn open(path: &Path) -> Result<Self> {
423        Self::open_with(path, false)
424    }
425
426    /// Open a chunk file for streaming reads that consume it: the disk space
427    /// of each block goes back to the file system once the block is read, and
428    /// the file is deleted when its last entry is taken.
429    ///
430    /// The run cannot be read again afterwards, so a build that is stopped
431    /// during the merge cannot resume from its chunks.
432    ///
433    /// # Errors
434    ///
435    /// As [`Self::open`].
436    pub fn open_reclaiming(path: &Path) -> Result<Self> {
437        Self::open_with(path, true)
438    }
439
440    fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
441        let file = OpenOptions::new()
442            .read(true)
443            .write(reclaim)
444            .open(path)
445            .map_err(io_error("open", path))?;
446        let mut reader = Self {
447            path: path.to_path_buf(),
448            file,
449            decoder: BlockDecoder::empty(),
450            peeked: None,
451            exhausted: false,
452            position: 0,
453            blocks: 0,
454            entries: 0,
455            reclaim,
456            reclaimed: 0,
457        };
458        reader.read_header()?;
459        reader.advance()?;
460        Ok(reader)
461    }
462
463    /// The next entry, if any, without consuming it.
464    #[inline]
465    #[must_use]
466    pub const fn peek(&self) -> Option<&SortEntry> {
467        self.peeked.as_ref()
468    }
469
470    /// Take the next entry and advance the reader.
471    ///
472    /// # Errors
473    ///
474    /// Returns an error if reading or decoding the next entry fails.
475    pub fn take(&mut self) -> Result<Option<SortEntry>> {
476        let entry = self.peeked.take();
477        if entry.is_some() {
478            self.advance()?;
479        }
480        Ok(entry)
481    }
482
483    /// Whether this reader has been fully consumed.
484    #[inline]
485    #[must_use]
486    pub const fn is_exhausted(&self) -> bool {
487        self.exhausted
488    }
489
490    fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
491        let mut done = 0;
492        while done < buf.len() {
493            match self.file.read(&mut buf[done..]) {
494                Ok(0) => break,
495                Ok(n) => done += n,
496                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
497                Err(source) => return Err(io_error("read", &self.path)(source)),
498            }
499        }
500        self.position += done as u64;
501        if done == buf.len() {
502            Ok(true)
503        } else if done == 0 {
504            Ok(false)
505        } else {
506            Err(self.truncated())
507        }
508    }
509
510    fn truncated(&self) -> TilesError {
511        SortRunError::Truncated {
512            path: self.path.clone(),
513            at: self.position,
514        }
515        .into()
516    }
517
518    fn read_header(&mut self) -> Result<()> {
519        let mut header = [0u8; HEADER_LEN];
520        if !self.fill(&mut header)? {
521            return Err(SortRunError::NotARun {
522                path: self.path.clone(),
523            }
524            .into());
525        }
526        if header[..4] != MAGIC {
527            return Err(SortRunError::NotARun {
528                path: self.path.clone(),
529            }
530            .into());
531        }
532        if header[4] != LAYOUT {
533            return Err(SortRunError::UnsupportedLayout {
534                path: self.path.clone(),
535                found: header[4],
536                expected: LAYOUT,
537            }
538            .into());
539        }
540        Ok(())
541    }
542
543    /// Read the next entry from the current block, loading the next block
544    /// or the end marker when the block is used up.
545    fn advance(&mut self) -> Result<()> {
546        if self.exhausted {
547            return Ok(());
548        }
549        if self.decoder.remaining() == 0 && !self.load_block()? {
550            return Ok(());
551        }
552        let entry = self
553            .decoder
554            .next_entry()
555            .map_err(|source| SortRunError::BadBlock {
556                path: self.path.clone(),
557                block: self.blocks.saturating_sub(1),
558                source,
559            })?;
560        if self.decoder.remaining() == 0 {
561            self.decoder
562                .check_complete()
563                .map_err(|source| SortRunError::BadBlock {
564                    path: self.path.clone(),
565                    block: self.blocks.saturating_sub(1),
566                    source,
567                })?;
568        }
569        self.peeked = Some(entry);
570        Ok(())
571    }
572
573    /// Load the next block. Returns `false` at the end marker.
574    fn load_block(&mut self) -> Result<bool> {
575        loop {
576            let at = self.position;
577            let mut kind = [0u8; 1];
578            if !self.fill(&mut kind)? {
579                return Err(self.truncated());
580            }
581            match kind[0] {
582                KIND_END => {
583                    self.read_end(at)?;
584                    return Ok(false);
585                }
586                KIND_BLOCK => {}
587                _ => {
588                    return Err(SortRunError::BadHeader {
589                        path: self.path.clone(),
590                        at,
591                        what: "unknown record kind",
592                    }
593                    .into());
594                }
595            }
596            let mut head = [0u8; BLOCK_HEADER_LEN];
597            if !self.fill(&mut head)? {
598                return Err(self.truncated());
599            }
600            let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
601            let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
602            let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
603            let checksum = u64::from_le_bytes([
604                head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
605            ]);
606            if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
607                return Err(SortRunError::BadHeader {
608                    path: self.path.clone(),
609                    at,
610                    what: "block size out of range",
611                }
612                .into());
613            }
614            let path = self.path.clone();
615            let block = self.blocks;
616            let produced = PACKED.with(|packed_cell| -> Result<usize> {
617                let mut packed = packed_cell.borrow_mut();
618                packed.resize(packed_len, 0);
619                if !self.fill(&mut packed)? && packed_len != 0 {
620                    return Err(self.truncated());
621                }
622                if xxh3_64(&packed) != checksum {
623                    return Err(SortRunError::BadChecksum {
624                        path: path.clone(),
625                        block,
626                        at,
627                    }
628                    .into());
629                }
630                let buffer = self.decoder.buffer();
631                buffer.clear();
632                buffer.reserve(raw_len);
633                DECOMPRESSOR
634                    .with(|cell| -> std::io::Result<usize> {
635                        let mut slot = cell.borrow_mut();
636                        if slot.is_none() {
637                            *slot = Some(zstd::bulk::Decompressor::new()?);
638                        }
639                        let decompressor = slot
640                            .as_mut()
641                            .ok_or_else(|| std::io::Error::other("no decompressor"))?;
642                        decompressor.decompress_to_buffer(&packed[..], buffer)
643                    })
644                    .map_err(|source| SortRunError::Io {
645                        op: "decompress",
646                        path: path.clone(),
647                        source,
648                    })
649                    .map_err(TilesError::from)
650            })?;
651            if produced != raw_len {
652                return Err(SortRunError::BadHeader {
653                    path: self.path.clone(),
654                    at,
655                    what: "block decompresses to another size",
656                }
657                .into());
658            }
659            self.decoder
660                .load(count)
661                .map_err(|source| SortRunError::BadBlock {
662                    path: self.path.clone(),
663                    block,
664                    source,
665                })?;
666            self.blocks += 1;
667            self.entries += u64::from(count);
668            self.release_read_bytes();
669            if count == 0 {
670                continue;
671            }
672            return Ok(true);
673        }
674    }
675
676    /// The bytes before `position` are in memory now: give their disk space
677    /// back, in steps, never the bytes of a block that is still to be read.
678    fn release_read_bytes(&mut self) {
679        if !self.reclaim {
680            return;
681        }
682        if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
683            self.reclaimed = upto;
684        }
685    }
686
687    fn read_end(&mut self, at: u64) -> Result<()> {
688        let mut end = [0u8; END_LEN];
689        if !self.fill(&mut end)? {
690            return Err(self.truncated());
691        }
692        let mut signed = [0u8; 17];
693        signed[0] = KIND_END;
694        signed[1..].copy_from_slice(&end[..16]);
695        let checksum = u64::from_le_bytes([
696            end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
697        ]);
698        if xxh3_64(&signed) != checksum {
699            return Err(SortRunError::BadHeader {
700                path: self.path.clone(),
701                at,
702                what: "end marker fails its checksum",
703            }
704            .into());
705        }
706        let entries = u64::from_le_bytes([
707            end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
708        ]);
709        let blocks = u64::from_le_bytes([
710            end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
711        ]);
712        if entries != self.entries || blocks != self.blocks {
713            return Err(SortRunError::CountMismatch {
714                path: self.path.clone(),
715                expected: entries,
716                found: self.entries,
717            }
718            .into());
719        }
720        let mut extra = [0u8; 1];
721        if self.fill(&mut extra)? {
722            return Err(SortRunError::TrailingBytes {
723                path: self.path.clone(),
724            }
725            .into());
726        }
727        self.exhausted = true;
728        if self.reclaim
729            && let Err(e) = std::fs::remove_file(&self.path)
730        {
731            // Every entry of the run was read and checked by now, so the
732            // archive does not depend on the file any more. The build removes
733            // the whole sort folder at its end; a file that stays until then
734            // only costs disk, and failing a build of many hours over it would
735            // cost more.
736            tracing::warn!(
737                "could not delete the consumed run {}: {e}",
738                self.path.display()
739            );
740        }
741        Ok(())
742    }
743}
744
745#[cfg(test)]
746mod tests {
747    use super::*;
748
749    use std::sync::Arc;
750
751    use geolith::layer::Layer;
752    use geolith::tile::feature::{GeomType, TileFeature};
753
754    fn make_entry(key: u64) -> SortEntry {
755        SortEntry::new(
756            key,
757            TileFeature {
758                layer: Layer::Buildings,
759                id: key,
760                geom_type: GeomType::Polygon,
761                geometry: vec![9, 0, 0],
762                properties: Arc::new(vec![]),
763                sort_key: 0,
764            },
765        )
766    }
767
768    #[test]
769    fn roundtrip_chunk_write_read() {
770        let dir = tempfile::tempdir().expect("tmpdir");
771        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
772
773        let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
774        entries.sort_unstable();
775        sink.write_chunk(&entries).expect("write");
776
777        let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
778        assert_eq!(read_back.len(), 100);
779        // Verify sorted order
780        for window in read_back.windows(2) {
781            assert!(window[0].key <= window[1].key);
782        }
783    }
784
785    #[test]
786    fn sort_buffer_flush_threshold() {
787        let mut buf = SortBuffer::with_max_bytes(100);
788        let mut full = false;
789        for i in 0..1000 {
790            if buf.push(make_entry(i)) {
791                full = true;
792                break;
793            }
794        }
795        assert!(full, "buffer should fill up");
796        assert!(!buf.is_empty());
797    }
798
799    #[test]
800    fn chunk_reader_streaming() {
801        let dir = tempfile::tempdir().expect("tmpdir");
802        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
803
804        let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
805        sink.write_chunk(&entries).expect("write");
806
807        let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
808        let mut count = 0;
809        while !reader.is_exhausted() {
810            let entry = reader.take().expect("take");
811            if entry.is_some() {
812                count += 1;
813            }
814        }
815        assert_eq!(count, 50);
816    }
817
818    /// A sink that takes `limit` bytes and then fails like a full disk, and
819    /// whose sync can fail too.
820    struct FailAfter {
821        limit: usize,
822        taken: usize,
823        sync_fails: bool,
824    }
825
826    impl Write for FailAfter {
827        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
828            let room = self.limit - self.taken;
829            if room == 0 && !buf.is_empty() {
830                // ENOSPC
831                return Err(std::io::Error::from_raw_os_error(28));
832            }
833            let n = room.min(buf.len());
834            self.taken += n;
835            Ok(n)
836        }
837
838        fn flush(&mut self) -> std::io::Result<()> {
839            Ok(())
840        }
841    }
842
843    impl RunFile for FailAfter {
844        fn make_durable(&mut self) -> std::io::Result<()> {
845            if self.sync_fails {
846                // EIO
847                Err(std::io::Error::from_raw_os_error(5))
848            } else {
849                Ok(())
850            }
851        }
852    }
853
854    fn noisy_entries(count: u64) -> Vec<SortEntry> {
855        (0..count)
856            .map(|i| {
857                let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
858                x ^= x >> 29;
859                make_entry_with(
860                    i,
861                    (0..16).map(|j| (x.rotate_left(j) & 0xFFF) as u32).collect(),
862                )
863            })
864            .collect()
865    }
866
867    fn make_entry_with(key: u64, geometry: Vec<u32>) -> SortEntry {
868        SortEntry::new(
869            key,
870            TileFeature {
871                layer: Layer::Buildings,
872                id: key.wrapping_mul(0xBF58_476D_1CE4_E5B9),
873                geom_type: GeomType::Polygon,
874                geometry,
875                properties: Arc::new(vec![]),
876                sort_key: 0,
877            },
878        )
879    }
880
881    #[test]
882    fn a_run_whose_write_fails_at_any_byte_is_an_error_that_names_the_file() {
883        let entries = noisy_entries(30_000);
884        let path = Path::new("/sort/chunk_000007.run");
885        let mut whole = FailAfter {
886            limit: usize::MAX,
887            taken: 0,
888            sync_fails: false,
889        };
890        write_run_to(&mut whole, path, &entries).expect("room enough");
891        let size = whole.taken;
892        assert!(
893            size > BLOCK_RAW_TARGET,
894            "the run has several blocks: {size}"
895        );
896
897        let mut limits: Vec<usize> = vec![0, 1, 7, 8, 9, 28, 29, size / 3, size / 2, size - 26];
898        limits.extend((1..=24).map(|k| size - k));
899        limits.extend((1..60).map(|k| k * size / 61));
900        for limit in limits {
901            let mut sink = FailAfter {
902                limit,
903                taken: 0,
904                sync_fails: false,
905            };
906            let err = write_run_to(&mut sink, path, &entries).expect_err(&format!(
907                "a disk full after {limit} of {size} bytes must fail"
908            ));
909            let text = geolith::error::report(&err);
910            assert!(text.contains("chunk_000007.run"), "{text}");
911            assert!(text.contains("os error 28"), "{text}");
912            assert!(
913                matches!(
914                    err,
915                    TilesError::SortRun(SortRunError::Io { op: "write", .. })
916                ),
917                "{text}"
918            );
919        }
920        let mut exact = FailAfter {
921            limit: size,
922            taken: 0,
923            sync_fails: false,
924        };
925        write_run_to(&mut exact, path, &entries).expect("exactly enough room");
926    }
927
928    #[test]
929    fn a_failed_sync_fails_the_run() {
930        let entries = noisy_entries(100);
931        let path = Path::new("/sort/chunk_000001.run");
932        let mut sink = FailAfter {
933            limit: usize::MAX,
934            taken: 0,
935            sync_fails: true,
936        };
937        let err = write_run_to(&mut sink, path, &entries).expect_err("sync fails");
938        let text = geolith::error::report(&err);
939        assert!(text.contains("sync /sort/chunk_000001.run"), "{text}");
940        assert!(text.contains("os error 5"), "{text}");
941    }
942
943    #[test]
944    fn a_run_that_fails_on_disk_leaves_no_file_behind() {
945        let dir = tempfile::tempdir().expect("tmpdir");
946        // The entries are not sorted: the write fails after the file exists.
947        let entries = vec![make_entry_with(9, vec![1]), make_entry_with(3, vec![1])];
948        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
949        assert!(sink.write_chunk(&entries).is_err());
950        let left: Vec<_> = std::fs::read_dir(dir.path())
951            .expect("read")
952            .map(|e| e.expect("entry").path())
953            .collect();
954        assert!(left.is_empty(), "a failed run was left behind: {left:?}");
955        assert_eq!(sink.chunk_count(), 0, "a failed run is not listed");
956    }
957}