geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
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
//! Sorted runs on disk: the spill files of the external sort.
//!
//! During Phase 1 (read + process), each rayon thread accumulates
//! `SortEntry` items in a local buffer. When the buffer exceeds a size
//! threshold, it is sorted by key and written as one run.
//!
//! A run is a header, a sequence of blocks and an end marker. A block holds a
//! few thousand entries in the columnar layout of [`crate::sort::block`],
//! compressed with zstd, with the xxh3 checksum of the compressed bytes in
//! its header. The end marker holds the number of blocks and entries and its
//! own checksum, so a run that was cut short, damaged or written by another
//! version stops the reader with a [`SortRunError`] and never yields a wrong
//! entry.
//!
//! The reader keeps one block in memory, so the k-way merge over thousands of
//! runs stays small, and it can give the disk space of every block back to the
//! file system as soon as the block is read (see [`ChunkReader::open_reclaiming`]).

use std::cell::RefCell;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};

use xxhash_rust::xxh3::xxh3_64;

use crate::sort::block::{BlockDecoder, BlockEncoder};
use crate::sort::entry::SortEntry;
use crate::sort::error::SortRunError;
use crate::sort::reclaim;
use crate::tiles_error::{Result, TilesError};

/// Maximum uncompressed bytes per chunk before flushing (default 256 MB).
const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;

/// Write buffer size for chunk files (8 MB).
///
/// Larger buffers reduce syscall overhead during Phase 1 writes.
const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;

/// File extension of a run.
pub const RUN_EXTENSION: &str = "run";

/// The first four bytes of a run.
const MAGIC: [u8; 4] = *b"GLRN";
/// The layout of the blocks: columnar entries, zstd.
const LAYOUT: u8 = 1;
/// Bytes of the run header: magic, layout, three reserved.
const HEADER_LEN: usize = 8;
/// Record kind byte of a block.
const KIND_BLOCK: u8 = 1;
/// Record kind byte of the end marker.
const KIND_END: u8 = 0xFF;
/// Bytes of a block header after the kind byte: raw length, compressed
/// length, entry count (`u32` each) and checksum (`u64`).
const BLOCK_HEADER_LEN: usize = 20;
/// Bytes of the end marker after the kind byte: entries, blocks and checksum.
const END_LEN: usize = 24;
/// The most bytes a block may take once decompressed; larger is a bad header.
const MAX_RAW_BLOCK: usize = 256 * 1024 * 1024;

/// A block closes once its columns hold this many bytes.
const BLOCK_RAW_TARGET: usize = 512 * 1024;
/// The zstd level of the blocks.
const ZSTD_LEVEL: i32 = 3;

thread_local! {
    /// One decompression context per thread: the merge reads thousands of
    /// runs from one thread, and a context per run would cost more memory
    /// than the run's block.
    static DECOMPRESSOR: RefCell<Option<zstd::bulk::Decompressor<'static>>> =
        const { RefCell::new(None) };

    /// The compressed bytes of the block being loaded, shared the same way:
    /// they are needed only until the block is decompressed.
    static PACKED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}

fn io_error(op: &'static str, path: &Path) -> impl FnOnce(std::io::Error) -> TilesError {
    let path = path.to_path_buf();
    move |source| SortRunError::Io { op, path, source }.into()
}

/// Manages writing sorted chunk files to a temporary directory.
///
/// Each instance tracks its own chunk paths. Multiple sinks can share
/// a single atomic counter to produce unique filenames across threads.
pub struct ChunkSink {
    /// Directory to store chunk files.
    dir: PathBuf,
    /// Paths of all chunk files written so far.
    chunk_paths: Vec<PathBuf>,
    /// Shared counter for generating unique chunk file names.
    counter: Arc<AtomicU32>,
}

impl ChunkSink {
    /// Create a new chunk sink writing to the given directory.
    ///
    /// Creates the directory if it doesn't exist. Uses a private counter
    /// starting at 0 for chunk file naming.
    ///
    /// # Errors
    ///
    /// Returns an error if creating the directory fails.
    pub fn new(dir: PathBuf) -> Result<Self> {
        std::fs::create_dir_all(&dir).map_err(|source| TilesError::CreateChunkDir {
            path: dir.clone(),
            source,
        })?;
        Ok(Self {
            dir,
            chunk_paths: Vec::new(),
            counter: Arc::new(AtomicU32::new(0)),
        })
    }

    /// Create a per-thread chunk sink sharing a global chunk ID counter.
    ///
    /// The directory must already exist (caller creates it once).
    /// The shared counter ensures chunk files have unique names across
    /// all threads, eliminating the need for a global `Mutex`.
    pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
        Self {
            dir,
            chunk_paths: Vec::new(),
            counter,
        }
    }

    /// Write a sorted slice of entries to a new chunk file.
    ///
    /// The entries MUST already be sorted by key before calling this.
    ///
    /// # Errors
    ///
    /// Returns an error if file creation or a write fails, if the entries
    /// are not sorted by key, or if an entry holds a value the run layout
    /// cannot store.
    pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
        let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
        let path = self.dir.join(format!("chunk_{id:06}.{RUN_EXTENSION}"));
        write_run(&path, entries)?;
        self.chunk_paths.push(path.clone());
        Ok(path)
    }

    /// All chunk file paths written so far, in creation order.
    #[must_use]
    pub fn chunk_paths(&self) -> &[PathBuf] {
        &self.chunk_paths
    }

    /// Number of chunk files written.
    #[must_use]
    pub const fn chunk_count(&self) -> usize {
        self.chunk_paths.len()
    }

    /// Consume this sink and return all chunk file paths written.
    #[must_use]
    pub fn into_chunk_paths(self) -> Vec<PathBuf> {
        self.chunk_paths
    }

    /// Clean up all chunk files.
    ///
    /// # Errors
    ///
    /// Returns an error if removing any chunk file fails.
    pub fn cleanup(&self) -> Result<()> {
        for path in &self.chunk_paths {
            if path.exists() {
                std::fs::remove_file(path).map_err(io_error("remove", path))?;
            }
        }
        Ok(())
    }
}

/// Where a run is written: a byte sink that can be made durable.
///
/// The seam is here so a test can fail a write, or the final sync, at any byte.
pub(crate) trait RunFile: Write {
    /// Push every byte written so far to the disk and report any error the
    /// file system kept back until now (a full disk, for one).
    fn make_durable(&mut self) -> std::io::Result<()>;
}

impl RunFile for BufWriter<File> {
    fn make_durable(&mut self) -> std::io::Result<()> {
        self.flush()?;
        self.get_ref().sync_all()
    }
}

/// Write `entries` as a run at `path`.
///
/// Every write, the flush and the sync is checked. A run that fails is
/// deleted again, so a half-written file is never left where `--resume`
/// looks for runs.
fn write_run(path: &Path, entries: &[SortEntry]) -> Result<()> {
    let file = File::create(path).map_err(io_error("create", path))?;
    let mut out = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
    let result = write_run_to(&mut out, path, entries);
    if result.is_err() {
        // Close the file before removing it. The write error is the one that
        // matters and is returned; a failure to remove the leftover cannot
        // add to it, and a leftover run is refused loudly by the reader
        // (no end marker), never read as a shorter run.
        drop(out);
        let _ = std::fs::remove_file(path);
        return result;
    }
    // The run's data is synced; its name in the folder is made durable too, so
    // a power loss cannot leave `--resume` without a run whose data was kept
    // (the next step may delete the source file it came from).
    geolith::output::sync_parent_dir(path).map_err(io_error("sync the folder of", path))
}

/// Write `entries` as a run to `out`; `path` names it in errors.
pub(crate) fn write_run_to<W: RunFile>(
    out: &mut W,
    path: &Path,
    entries: &[SortEntry],
) -> Result<()> {
    let write = |out: &mut W, bytes: &[u8]| out.write_all(bytes).map_err(io_error("write", path));

    let mut header = [0u8; HEADER_LEN];
    header[..4].copy_from_slice(&MAGIC);
    header[4] = LAYOUT;
    write(out, &header)?;

    let mut compressor =
        zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
    let mut encoder = BlockEncoder::new();
    let mut raw = Vec::new();
    let mut packed = Vec::new();
    let (mut blocks, mut total) = (0u64, 0u64);

    let mut close_block = |encoder: &mut BlockEncoder,
                           out: &mut W,
                           blocks: &mut u64,
                           total: &mut u64|
     -> Result<()> {
        raw.clear();
        let count = encoder.finish_into(&mut raw);
        if raw.len() > MAX_RAW_BLOCK {
            return Err(SortRunError::BadHeader {
                path: path.to_path_buf(),
                at: *blocks,
                what: "an entry is too large for a block",
            }
            .into());
        }
        packed.clear();
        packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
        compressor
            .compress_to_buffer(&raw, &mut packed)
            .map_err(io_error("compress", path))?;
        let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
        head[0] = KIND_BLOCK;
        head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
        head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
        head[9..13].copy_from_slice(&count.to_le_bytes());
        head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
        write(out, &head)?;
        write(out, &packed)?;
        *blocks += 1;
        *total += u64::from(count);
        Ok(())
    };

    for entry in entries {
        encoder
            .push(entry)
            .map_err(|source| SortRunError::BadBlock {
                path: path.to_path_buf(),
                block: blocks,
                source,
            })?;
        if encoder.raw_len() >= BLOCK_RAW_TARGET {
            close_block(&mut encoder, out, &mut blocks, &mut total)?;
        }
    }
    if !encoder.is_empty() {
        close_block(&mut encoder, out, &mut blocks, &mut total)?;
    }

    let mut end = [0u8; 1 + END_LEN];
    end[0] = KIND_END;
    end[1..9].copy_from_slice(&total.to_le_bytes());
    end[9..17].copy_from_slice(&blocks.to_le_bytes());
    let checksum = xxh3_64(&end[..17]);
    end[17..25].copy_from_slice(&checksum.to_le_bytes());
    write(out, &end)?;
    out.make_durable().map_err(io_error("sync", path))?;
    Ok(())
}

/// A thread-local buffer that accumulates sort entries and flushes
/// to a `ChunkSink` when the buffer exceeds the size threshold.
pub struct SortBuffer {
    entries: Vec<SortEntry>,
    /// Approximate total serialized size in bytes.
    approx_bytes: usize,
    /// Flush threshold in bytes.
    max_bytes: usize,
}

impl SortBuffer {
    /// Create a new sort buffer with the default size threshold.
    #[must_use]
    pub fn new() -> Self {
        Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
    }

    /// Create a new sort buffer with a custom size threshold.
    #[must_use]
    pub fn with_max_bytes(max_bytes: usize) -> Self {
        Self {
            entries: Vec::with_capacity(1024),
            approx_bytes: 0,
            max_bytes,
        }
    }

    /// Push an entry into the buffer.
    ///
    /// Returns `true` if the buffer is now full and should be flushed.
    #[inline]
    pub fn push(&mut self, entry: SortEntry) -> bool {
        // Approximate size: 8 bytes key + ~50 bytes avg feature
        self.approx_bytes +=
            58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
        self.entries.push(entry);
        self.approx_bytes >= self.max_bytes
    }

    /// Sort entries by key and flush to a chunk file via the sink.
    ///
    /// Clears the buffer after writing.
    ///
    /// # Errors
    ///
    /// Returns an error if sorting or chunk write fails.
    pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
        if self.entries.is_empty() {
            return Ok(());
        }
        self.entries.sort_unstable();
        sink.write_chunk(&self.entries)?;
        self.entries.clear();
        self.approx_bytes = 0;
        Ok(())
    }

    /// Whether the buffer has pending entries.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Number of entries in the buffer.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.entries.len()
    }
}

impl Default for SortBuffer {
    fn default() -> Self {
        Self::new()
    }
}

/// Read all sort entries from a chunk file, in order.
///
/// This is a convenience for testing; the merge module uses
/// `ChunkReader` for streaming reads.
///
/// # Errors
///
/// Returns an error if the run cannot be opened, is cut, damaged or of
/// another layout.
pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
    let mut reader = ChunkReader::open(path)?;
    let mut entries = Vec::new();
    while let Some(entry) = reader.take()? {
        entries.push(entry);
    }
    Ok(entries)
}

/// Streaming reader for a single chunk file.
///
/// Used by the k-way merge to read entries one at a time without
/// loading the entire chunk into memory: one block is in memory at a time.
pub struct ChunkReader {
    path: PathBuf,
    file: File,
    decoder: BlockDecoder,
    /// The next entry, pre-read for the merge heap.
    peeked: Option<SortEntry>,
    /// Whether we've reached the end of the chunk.
    exhausted: bool,
    /// Bytes read from the file so far.
    position: u64,
    blocks: u64,
    entries: u64,
    /// Give the disk space of blocks back as they are read, and delete the
    /// file at its end.
    reclaim: bool,
    /// The file offset below which the space is already given back.
    reclaimed: u64,
}

impl ChunkReader {
    /// Open a chunk file for streaming reads.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened, is not a run of this
    /// layout, or its first block is cut or damaged.
    pub fn open(path: &Path) -> Result<Self> {
        Self::open_with(path, false)
    }

    /// Open a chunk file for streaming reads that consume it: the disk space
    /// of each block goes back to the file system once the block is read, and
    /// the file is deleted when its last entry is taken.
    ///
    /// The run cannot be read again afterwards, so a build that is stopped
    /// during the merge cannot resume from its chunks.
    ///
    /// # Errors
    ///
    /// As [`Self::open`].
    pub fn open_reclaiming(path: &Path) -> Result<Self> {
        Self::open_with(path, true)
    }

    fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
        let file = OpenOptions::new()
            .read(true)
            .write(reclaim)
            .open(path)
            .map_err(io_error("open", path))?;
        let mut reader = Self {
            path: path.to_path_buf(),
            file,
            decoder: BlockDecoder::empty(),
            peeked: None,
            exhausted: false,
            position: 0,
            blocks: 0,
            entries: 0,
            reclaim,
            reclaimed: 0,
        };
        reader.read_header()?;
        reader.advance()?;
        Ok(reader)
    }

    /// The next entry, if any, without consuming it.
    #[inline]
    #[must_use]
    pub const fn peek(&self) -> Option<&SortEntry> {
        self.peeked.as_ref()
    }

    /// Take the next entry and advance the reader.
    ///
    /// # Errors
    ///
    /// Returns an error if reading or decoding the next entry fails.
    pub fn take(&mut self) -> Result<Option<SortEntry>> {
        let entry = self.peeked.take();
        if entry.is_some() {
            self.advance()?;
        }
        Ok(entry)
    }

    /// Whether this reader has been fully consumed.
    #[inline]
    #[must_use]
    pub const fn is_exhausted(&self) -> bool {
        self.exhausted
    }

    fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
        let mut done = 0;
        while done < buf.len() {
            match self.file.read(&mut buf[done..]) {
                Ok(0) => break,
                Ok(n) => done += n,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(source) => return Err(io_error("read", &self.path)(source)),
            }
        }
        self.position += done as u64;
        if done == buf.len() {
            Ok(true)
        } else if done == 0 {
            Ok(false)
        } else {
            Err(self.truncated())
        }
    }

    fn truncated(&self) -> TilesError {
        SortRunError::Truncated {
            path: self.path.clone(),
            at: self.position,
        }
        .into()
    }

    fn read_header(&mut self) -> Result<()> {
        let mut header = [0u8; HEADER_LEN];
        if !self.fill(&mut header)? {
            return Err(SortRunError::NotARun {
                path: self.path.clone(),
            }
            .into());
        }
        if header[..4] != MAGIC {
            return Err(SortRunError::NotARun {
                path: self.path.clone(),
            }
            .into());
        }
        if header[4] != LAYOUT {
            return Err(SortRunError::UnsupportedLayout {
                path: self.path.clone(),
                found: header[4],
                expected: LAYOUT,
            }
            .into());
        }
        Ok(())
    }

    /// Read the next entry from the current block, loading the next block
    /// or the end marker when the block is used up.
    fn advance(&mut self) -> Result<()> {
        if self.exhausted {
            return Ok(());
        }
        if self.decoder.remaining() == 0 && !self.load_block()? {
            return Ok(());
        }
        let entry = self
            .decoder
            .next_entry()
            .map_err(|source| SortRunError::BadBlock {
                path: self.path.clone(),
                block: self.blocks.saturating_sub(1),
                source,
            })?;
        if self.decoder.remaining() == 0 {
            self.decoder
                .check_complete()
                .map_err(|source| SortRunError::BadBlock {
                    path: self.path.clone(),
                    block: self.blocks.saturating_sub(1),
                    source,
                })?;
        }
        self.peeked = Some(entry);
        Ok(())
    }

    /// Load the next block. Returns `false` at the end marker.
    fn load_block(&mut self) -> Result<bool> {
        loop {
            let at = self.position;
            let mut kind = [0u8; 1];
            if !self.fill(&mut kind)? {
                return Err(self.truncated());
            }
            match kind[0] {
                KIND_END => {
                    self.read_end(at)?;
                    return Ok(false);
                }
                KIND_BLOCK => {}
                _ => {
                    return Err(SortRunError::BadHeader {
                        path: self.path.clone(),
                        at,
                        what: "unknown record kind",
                    }
                    .into());
                }
            }
            let mut head = [0u8; BLOCK_HEADER_LEN];
            if !self.fill(&mut head)? {
                return Err(self.truncated());
            }
            let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
            let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
            let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
            let checksum = u64::from_le_bytes([
                head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
            ]);
            if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
                return Err(SortRunError::BadHeader {
                    path: self.path.clone(),
                    at,
                    what: "block size out of range",
                }
                .into());
            }
            let path = self.path.clone();
            let block = self.blocks;
            let produced = PACKED.with(|packed_cell| -> Result<usize> {
                let mut packed = packed_cell.borrow_mut();
                packed.resize(packed_len, 0);
                if !self.fill(&mut packed)? && packed_len != 0 {
                    return Err(self.truncated());
                }
                if xxh3_64(&packed) != checksum {
                    return Err(SortRunError::BadChecksum {
                        path: path.clone(),
                        block,
                        at,
                    }
                    .into());
                }
                let buffer = self.decoder.buffer();
                buffer.clear();
                buffer.reserve(raw_len);
                DECOMPRESSOR
                    .with(|cell| -> std::io::Result<usize> {
                        let mut slot = cell.borrow_mut();
                        if slot.is_none() {
                            *slot = Some(zstd::bulk::Decompressor::new()?);
                        }
                        let decompressor = slot
                            .as_mut()
                            .ok_or_else(|| std::io::Error::other("no decompressor"))?;
                        decompressor.decompress_to_buffer(&packed[..], buffer)
                    })
                    .map_err(|source| SortRunError::Io {
                        op: "decompress",
                        path: path.clone(),
                        source,
                    })
                    .map_err(TilesError::from)
            })?;
            if produced != raw_len {
                return Err(SortRunError::BadHeader {
                    path: self.path.clone(),
                    at,
                    what: "block decompresses to another size",
                }
                .into());
            }
            self.decoder
                .load(count)
                .map_err(|source| SortRunError::BadBlock {
                    path: self.path.clone(),
                    block,
                    source,
                })?;
            self.blocks += 1;
            self.entries += u64::from(count);
            self.release_read_bytes();
            if count == 0 {
                continue;
            }
            return Ok(true);
        }
    }

    /// The bytes before `position` are in memory now: give their disk space
    /// back, in steps, never the bytes of a block that is still to be read.
    fn release_read_bytes(&mut self) {
        if !self.reclaim {
            return;
        }
        if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
            self.reclaimed = upto;
        }
    }

    fn read_end(&mut self, at: u64) -> Result<()> {
        let mut end = [0u8; END_LEN];
        if !self.fill(&mut end)? {
            return Err(self.truncated());
        }
        let mut signed = [0u8; 17];
        signed[0] = KIND_END;
        signed[1..].copy_from_slice(&end[..16]);
        let checksum = u64::from_le_bytes([
            end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
        ]);
        if xxh3_64(&signed) != checksum {
            return Err(SortRunError::BadHeader {
                path: self.path.clone(),
                at,
                what: "end marker fails its checksum",
            }
            .into());
        }
        let entries = u64::from_le_bytes([
            end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
        ]);
        let blocks = u64::from_le_bytes([
            end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
        ]);
        if entries != self.entries || blocks != self.blocks {
            return Err(SortRunError::CountMismatch {
                path: self.path.clone(),
                expected: entries,
                found: self.entries,
            }
            .into());
        }
        let mut extra = [0u8; 1];
        if self.fill(&mut extra)? {
            return Err(SortRunError::TrailingBytes {
                path: self.path.clone(),
            }
            .into());
        }
        self.exhausted = true;
        if self.reclaim
            && let Err(e) = std::fs::remove_file(&self.path)
        {
            // Every entry of the run was read and checked by now, so the
            // archive does not depend on the file any more. The build removes
            // the whole sort folder at its end; a file that stays until then
            // only costs disk, and failing a build of many hours over it would
            // cost more.
            tracing::warn!(
                "could not delete the consumed run {}: {e}",
                self.path.display()
            );
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::sync::Arc;

    use geolith::layer::Layer;
    use geolith::tile::feature::{GeomType, TileFeature};

    fn make_entry(key: u64) -> SortEntry {
        SortEntry::new(
            key,
            TileFeature {
                layer: Layer::Buildings,
                id: key,
                geom_type: GeomType::Polygon,
                geometry: vec![9, 0, 0],
                properties: Arc::new(vec![]),
                sort_key: 0,
            },
        )
    }

    #[test]
    fn roundtrip_chunk_write_read() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");

        let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
        entries.sort_unstable();
        sink.write_chunk(&entries).expect("write");

        let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
        assert_eq!(read_back.len(), 100);
        // Verify sorted order
        for window in read_back.windows(2) {
            assert!(window[0].key <= window[1].key);
        }
    }

    #[test]
    fn sort_buffer_flush_threshold() {
        let mut buf = SortBuffer::with_max_bytes(100);
        let mut full = false;
        for i in 0..1000 {
            if buf.push(make_entry(i)) {
                full = true;
                break;
            }
        }
        assert!(full, "buffer should fill up");
        assert!(!buf.is_empty());
    }

    #[test]
    fn chunk_reader_streaming() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");

        let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
        sink.write_chunk(&entries).expect("write");

        let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
        let mut count = 0;
        while !reader.is_exhausted() {
            let entry = reader.take().expect("take");
            if entry.is_some() {
                count += 1;
            }
        }
        assert_eq!(count, 50);
    }

    /// A sink that takes `limit` bytes and then fails like a full disk, and
    /// whose sync can fail too.
    struct FailAfter {
        limit: usize,
        taken: usize,
        sync_fails: bool,
    }

    impl Write for FailAfter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let room = self.limit - self.taken;
            if room == 0 && !buf.is_empty() {
                // ENOSPC
                return Err(std::io::Error::from_raw_os_error(28));
            }
            let n = room.min(buf.len());
            self.taken += n;
            Ok(n)
        }

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

    impl RunFile for FailAfter {
        fn make_durable(&mut self) -> std::io::Result<()> {
            if self.sync_fails {
                // EIO
                Err(std::io::Error::from_raw_os_error(5))
            } else {
                Ok(())
            }
        }
    }

    fn noisy_entries(count: u64) -> Vec<SortEntry> {
        (0..count)
            .map(|i| {
                let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
                x ^= x >> 29;
                make_entry_with(
                    i,
                    (0..16).map(|j| (x.rotate_left(j) & 0xFFF) as u32).collect(),
                )
            })
            .collect()
    }

    fn make_entry_with(key: u64, geometry: Vec<u32>) -> SortEntry {
        SortEntry::new(
            key,
            TileFeature {
                layer: Layer::Buildings,
                id: key.wrapping_mul(0xBF58_476D_1CE4_E5B9),
                geom_type: GeomType::Polygon,
                geometry,
                properties: Arc::new(vec![]),
                sort_key: 0,
            },
        )
    }

    #[test]
    fn a_run_whose_write_fails_at_any_byte_is_an_error_that_names_the_file() {
        let entries = noisy_entries(30_000);
        let path = Path::new("/sort/chunk_000007.run");
        let mut whole = FailAfter {
            limit: usize::MAX,
            taken: 0,
            sync_fails: false,
        };
        write_run_to(&mut whole, path, &entries).expect("room enough");
        let size = whole.taken;
        assert!(
            size > BLOCK_RAW_TARGET,
            "the run has several blocks: {size}"
        );

        let mut limits: Vec<usize> = vec![0, 1, 7, 8, 9, 28, 29, size / 3, size / 2, size - 26];
        limits.extend((1..=24).map(|k| size - k));
        limits.extend((1..60).map(|k| k * size / 61));
        for limit in limits {
            let mut sink = FailAfter {
                limit,
                taken: 0,
                sync_fails: false,
            };
            let err = write_run_to(&mut sink, path, &entries).expect_err(&format!(
                "a disk full after {limit} of {size} bytes must fail"
            ));
            let text = geolith::error::report(&err);
            assert!(text.contains("chunk_000007.run"), "{text}");
            assert!(text.contains("os error 28"), "{text}");
            assert!(
                matches!(
                    err,
                    TilesError::SortRun(SortRunError::Io { op: "write", .. })
                ),
                "{text}"
            );
        }
        let mut exact = FailAfter {
            limit: size,
            taken: 0,
            sync_fails: false,
        };
        write_run_to(&mut exact, path, &entries).expect("exactly enough room");
    }

    #[test]
    fn a_failed_sync_fails_the_run() {
        let entries = noisy_entries(100);
        let path = Path::new("/sort/chunk_000001.run");
        let mut sink = FailAfter {
            limit: usize::MAX,
            taken: 0,
            sync_fails: true,
        };
        let err = write_run_to(&mut sink, path, &entries).expect_err("sync fails");
        let text = geolith::error::report(&err);
        assert!(text.contains("sync /sort/chunk_000001.run"), "{text}");
        assert!(text.contains("os error 5"), "{text}");
    }

    #[test]
    fn a_run_that_fails_on_disk_leaves_no_file_behind() {
        let dir = tempfile::tempdir().expect("tmpdir");
        // The entries are not sorted: the write fails after the file exists.
        let entries = vec![make_entry_with(9, vec![1]), make_entry_with(3, vec![1])];
        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
        assert!(sink.write_chunk(&entries).is_err());
        let left: Vec<_> = std::fs::read_dir(dir.path())
            .expect("read")
            .map(|e| e.expect("entry").path())
            .collect();
        assert!(left.is_empty(), "a failed run was left behind: {left:?}");
        assert_eq!(sink.chunk_count(), 0, "a failed run is not listed");
    }
}