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/// Write `entries` as a run at `path`.
183fn write_run(path: &Path, entries: &[SortEntry]) -> Result<()> {
184    let file = File::create(path).map_err(io_error("create", path))?;
185    let mut out = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
186    let write = |out: &mut BufWriter<File>, bytes: &[u8]| {
187        out.write_all(bytes).map_err(io_error("write", path))
188    };
189
190    let mut header = [0u8; HEADER_LEN];
191    header[..4].copy_from_slice(&MAGIC);
192    header[4] = LAYOUT;
193    write(&mut out, &header)?;
194
195    let mut compressor =
196        zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
197    let mut encoder = BlockEncoder::new();
198    let mut raw = Vec::new();
199    let mut packed = Vec::new();
200    let (mut blocks, mut total) = (0u64, 0u64);
201
202    let mut close_block = |encoder: &mut BlockEncoder,
203                           out: &mut BufWriter<File>,
204                           blocks: &mut u64,
205                           total: &mut u64|
206     -> Result<()> {
207        raw.clear();
208        let count = encoder.finish_into(&mut raw);
209        if raw.len() > MAX_RAW_BLOCK {
210            return Err(SortRunError::BadHeader {
211                path: path.to_path_buf(),
212                at: *blocks,
213                what: "an entry is too large for a block",
214            }
215            .into());
216        }
217        packed.clear();
218        packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
219        compressor
220            .compress_to_buffer(&raw, &mut packed)
221            .map_err(io_error("compress", path))?;
222        let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
223        head[0] = KIND_BLOCK;
224        head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
225        head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
226        head[9..13].copy_from_slice(&count.to_le_bytes());
227        head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
228        write(out, &head)?;
229        write(out, &packed)?;
230        *blocks += 1;
231        *total += u64::from(count);
232        Ok(())
233    };
234
235    for entry in entries {
236        encoder
237            .push(entry)
238            .map_err(|source| SortRunError::BadBlock {
239                path: path.to_path_buf(),
240                block: blocks,
241                source,
242            })?;
243        if encoder.raw_len() >= BLOCK_RAW_TARGET {
244            close_block(&mut encoder, &mut out, &mut blocks, &mut total)?;
245        }
246    }
247    if !encoder.is_empty() {
248        close_block(&mut encoder, &mut out, &mut blocks, &mut total)?;
249    }
250
251    let mut end = [0u8; 1 + END_LEN];
252    end[0] = KIND_END;
253    end[1..9].copy_from_slice(&total.to_le_bytes());
254    end[9..17].copy_from_slice(&blocks.to_le_bytes());
255    let checksum = xxh3_64(&end[..17]);
256    end[17..25].copy_from_slice(&checksum.to_le_bytes());
257    write(&mut out, &end)?;
258    out.flush().map_err(io_error("write", path))?;
259    Ok(())
260}
261
262/// A thread-local buffer that accumulates sort entries and flushes
263/// to a `ChunkSink` when the buffer exceeds the size threshold.
264pub struct SortBuffer {
265    entries: Vec<SortEntry>,
266    /// Approximate total serialized size in bytes.
267    approx_bytes: usize,
268    /// Flush threshold in bytes.
269    max_bytes: usize,
270}
271
272impl SortBuffer {
273    /// Create a new sort buffer with the default size threshold.
274    #[must_use]
275    pub fn new() -> Self {
276        Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
277    }
278
279    /// Create a new sort buffer with a custom size threshold.
280    #[must_use]
281    pub fn with_max_bytes(max_bytes: usize) -> Self {
282        Self {
283            entries: Vec::with_capacity(1024),
284            approx_bytes: 0,
285            max_bytes,
286        }
287    }
288
289    /// Push an entry into the buffer.
290    ///
291    /// Returns `true` if the buffer is now full and should be flushed.
292    #[inline]
293    pub fn push(&mut self, entry: SortEntry) -> bool {
294        // Approximate size: 8 bytes key + ~50 bytes avg feature
295        self.approx_bytes +=
296            58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
297        self.entries.push(entry);
298        self.approx_bytes >= self.max_bytes
299    }
300
301    /// Sort entries by key and flush to a chunk file via the sink.
302    ///
303    /// Clears the buffer after writing.
304    ///
305    /// # Errors
306    ///
307    /// Returns an error if sorting or chunk write fails.
308    pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
309        if self.entries.is_empty() {
310            return Ok(());
311        }
312        self.entries.sort_unstable();
313        sink.write_chunk(&self.entries)?;
314        self.entries.clear();
315        self.approx_bytes = 0;
316        Ok(())
317    }
318
319    /// Whether the buffer has pending entries.
320    #[must_use]
321    pub const fn is_empty(&self) -> bool {
322        self.entries.is_empty()
323    }
324
325    /// Number of entries in the buffer.
326    #[must_use]
327    pub const fn len(&self) -> usize {
328        self.entries.len()
329    }
330}
331
332impl Default for SortBuffer {
333    fn default() -> Self {
334        Self::new()
335    }
336}
337
338/// Read all sort entries from a chunk file, in order.
339///
340/// This is a convenience for testing; the merge module uses
341/// `ChunkReader` for streaming reads.
342///
343/// # Errors
344///
345/// Returns an error if the run cannot be opened, is cut, damaged or of
346/// another layout.
347pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
348    let mut reader = ChunkReader::open(path)?;
349    let mut entries = Vec::new();
350    while let Some(entry) = reader.take()? {
351        entries.push(entry);
352    }
353    Ok(entries)
354}
355
356/// Streaming reader for a single chunk file.
357///
358/// Used by the k-way merge to read entries one at a time without
359/// loading the entire chunk into memory: one block is in memory at a time.
360pub struct ChunkReader {
361    path: PathBuf,
362    file: File,
363    decoder: BlockDecoder,
364    /// The next entry, pre-read for the merge heap.
365    peeked: Option<SortEntry>,
366    /// Whether we've reached the end of the chunk.
367    exhausted: bool,
368    /// Bytes read from the file so far.
369    position: u64,
370    blocks: u64,
371    entries: u64,
372    /// Give the disk space of blocks back as they are read, and delete the
373    /// file at its end.
374    reclaim: bool,
375    /// The file offset below which the space is already given back.
376    reclaimed: u64,
377}
378
379impl ChunkReader {
380    /// Open a chunk file for streaming reads.
381    ///
382    /// # Errors
383    ///
384    /// Returns an error if the file cannot be opened, is not a run of this
385    /// layout, or its first block is cut or damaged.
386    pub fn open(path: &Path) -> Result<Self> {
387        Self::open_with(path, false)
388    }
389
390    /// Open a chunk file for streaming reads that consume it: the disk space
391    /// of each block goes back to the file system once the block is read, and
392    /// the file is deleted when its last entry is taken.
393    ///
394    /// The run cannot be read again afterwards, so a build that is stopped
395    /// during the merge cannot resume from its chunks.
396    ///
397    /// # Errors
398    ///
399    /// As [`Self::open`].
400    pub fn open_reclaiming(path: &Path) -> Result<Self> {
401        Self::open_with(path, true)
402    }
403
404    fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
405        let file = OpenOptions::new()
406            .read(true)
407            .write(reclaim)
408            .open(path)
409            .map_err(io_error("open", path))?;
410        let mut reader = Self {
411            path: path.to_path_buf(),
412            file,
413            decoder: BlockDecoder::empty(),
414            peeked: None,
415            exhausted: false,
416            position: 0,
417            blocks: 0,
418            entries: 0,
419            reclaim,
420            reclaimed: 0,
421        };
422        reader.read_header()?;
423        reader.advance()?;
424        Ok(reader)
425    }
426
427    /// The next entry, if any, without consuming it.
428    #[inline]
429    #[must_use]
430    pub const fn peek(&self) -> Option<&SortEntry> {
431        self.peeked.as_ref()
432    }
433
434    /// Take the next entry and advance the reader.
435    ///
436    /// # Errors
437    ///
438    /// Returns an error if reading or decoding the next entry fails.
439    pub fn take(&mut self) -> Result<Option<SortEntry>> {
440        let entry = self.peeked.take();
441        if entry.is_some() {
442            self.advance()?;
443        }
444        Ok(entry)
445    }
446
447    /// Whether this reader has been fully consumed.
448    #[inline]
449    #[must_use]
450    pub const fn is_exhausted(&self) -> bool {
451        self.exhausted
452    }
453
454    fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
455        let mut done = 0;
456        while done < buf.len() {
457            match self.file.read(&mut buf[done..]) {
458                Ok(0) => break,
459                Ok(n) => done += n,
460                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
461                Err(source) => return Err(io_error("read", &self.path)(source)),
462            }
463        }
464        self.position += done as u64;
465        if done == buf.len() {
466            Ok(true)
467        } else if done == 0 {
468            Ok(false)
469        } else {
470            Err(self.truncated())
471        }
472    }
473
474    fn truncated(&self) -> TilesError {
475        SortRunError::Truncated {
476            path: self.path.clone(),
477            at: self.position,
478        }
479        .into()
480    }
481
482    fn read_header(&mut self) -> Result<()> {
483        let mut header = [0u8; HEADER_LEN];
484        if !self.fill(&mut header)? {
485            return Err(SortRunError::NotARun {
486                path: self.path.clone(),
487            }
488            .into());
489        }
490        if header[..4] != MAGIC {
491            return Err(SortRunError::NotARun {
492                path: self.path.clone(),
493            }
494            .into());
495        }
496        if header[4] != LAYOUT {
497            return Err(SortRunError::UnsupportedLayout {
498                path: self.path.clone(),
499                found: header[4],
500                expected: LAYOUT,
501            }
502            .into());
503        }
504        Ok(())
505    }
506
507    /// Read the next entry from the current block, loading the next block
508    /// or the end marker when the block is used up.
509    fn advance(&mut self) -> Result<()> {
510        if self.exhausted {
511            return Ok(());
512        }
513        if self.decoder.remaining() == 0 && !self.load_block()? {
514            return Ok(());
515        }
516        let entry = self
517            .decoder
518            .next_entry()
519            .map_err(|source| SortRunError::BadBlock {
520                path: self.path.clone(),
521                block: self.blocks.saturating_sub(1),
522                source,
523            })?;
524        if self.decoder.remaining() == 0 {
525            self.decoder
526                .check_complete()
527                .map_err(|source| SortRunError::BadBlock {
528                    path: self.path.clone(),
529                    block: self.blocks.saturating_sub(1),
530                    source,
531                })?;
532        }
533        self.peeked = Some(entry);
534        Ok(())
535    }
536
537    /// Load the next block. Returns `false` at the end marker.
538    fn load_block(&mut self) -> Result<bool> {
539        loop {
540            let at = self.position;
541            let mut kind = [0u8; 1];
542            if !self.fill(&mut kind)? {
543                return Err(self.truncated());
544            }
545            match kind[0] {
546                KIND_END => {
547                    self.read_end(at)?;
548                    return Ok(false);
549                }
550                KIND_BLOCK => {}
551                _ => {
552                    return Err(SortRunError::BadHeader {
553                        path: self.path.clone(),
554                        at,
555                        what: "unknown record kind",
556                    }
557                    .into());
558                }
559            }
560            let mut head = [0u8; BLOCK_HEADER_LEN];
561            if !self.fill(&mut head)? {
562                return Err(self.truncated());
563            }
564            let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
565            let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
566            let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
567            let checksum = u64::from_le_bytes([
568                head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
569            ]);
570            if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
571                return Err(SortRunError::BadHeader {
572                    path: self.path.clone(),
573                    at,
574                    what: "block size out of range",
575                }
576                .into());
577            }
578            let path = self.path.clone();
579            let block = self.blocks;
580            let produced = PACKED.with(|packed_cell| -> Result<usize> {
581                let mut packed = packed_cell.borrow_mut();
582                packed.resize(packed_len, 0);
583                if !self.fill(&mut packed)? && packed_len != 0 {
584                    return Err(self.truncated());
585                }
586                if xxh3_64(&packed) != checksum {
587                    return Err(SortRunError::BadChecksum {
588                        path: path.clone(),
589                        block,
590                        at,
591                    }
592                    .into());
593                }
594                let buffer = self.decoder.buffer();
595                buffer.clear();
596                buffer.reserve(raw_len);
597                DECOMPRESSOR
598                    .with(|cell| -> std::io::Result<usize> {
599                        let mut slot = cell.borrow_mut();
600                        if slot.is_none() {
601                            *slot = Some(zstd::bulk::Decompressor::new()?);
602                        }
603                        let decompressor = slot
604                            .as_mut()
605                            .ok_or_else(|| std::io::Error::other("no decompressor"))?;
606                        decompressor.decompress_to_buffer(&packed[..], buffer)
607                    })
608                    .map_err(|source| SortRunError::Io {
609                        op: "decompress",
610                        path: path.clone(),
611                        source,
612                    })
613                    .map_err(TilesError::from)
614            })?;
615            if produced != raw_len {
616                return Err(SortRunError::BadHeader {
617                    path: self.path.clone(),
618                    at,
619                    what: "block decompresses to another size",
620                }
621                .into());
622            }
623            self.decoder
624                .load(count)
625                .map_err(|source| SortRunError::BadBlock {
626                    path: self.path.clone(),
627                    block,
628                    source,
629                })?;
630            self.blocks += 1;
631            self.entries += u64::from(count);
632            self.release_read_bytes();
633            if count == 0 {
634                continue;
635            }
636            return Ok(true);
637        }
638    }
639
640    /// The bytes before `position` are in memory now: give their disk space
641    /// back, in steps, never the bytes of a block that is still to be read.
642    fn release_read_bytes(&mut self) {
643        if !self.reclaim {
644            return;
645        }
646        if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
647            self.reclaimed = upto;
648        }
649    }
650
651    fn read_end(&mut self, at: u64) -> Result<()> {
652        let mut end = [0u8; END_LEN];
653        if !self.fill(&mut end)? {
654            return Err(self.truncated());
655        }
656        let mut signed = [0u8; 17];
657        signed[0] = KIND_END;
658        signed[1..].copy_from_slice(&end[..16]);
659        let checksum = u64::from_le_bytes([
660            end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
661        ]);
662        if xxh3_64(&signed) != checksum {
663            return Err(SortRunError::BadHeader {
664                path: self.path.clone(),
665                at,
666                what: "end marker fails its checksum",
667            }
668            .into());
669        }
670        let entries = u64::from_le_bytes([
671            end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
672        ]);
673        let blocks = u64::from_le_bytes([
674            end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
675        ]);
676        if entries != self.entries || blocks != self.blocks {
677            return Err(SortRunError::CountMismatch {
678                path: self.path.clone(),
679                expected: entries,
680                found: self.entries,
681            }
682            .into());
683        }
684        let mut extra = [0u8; 1];
685        if self.fill(&mut extra)? {
686            return Err(SortRunError::TrailingBytes {
687                path: self.path.clone(),
688            }
689            .into());
690        }
691        self.exhausted = true;
692        if self.reclaim {
693            std::fs::remove_file(&self.path).map_err(io_error("remove", &self.path))?;
694        }
695        Ok(())
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    use std::sync::Arc;
704
705    use geolith::layer::Layer;
706    use geolith::tile::feature::{GeomType, TileFeature};
707
708    fn make_entry(key: u64) -> SortEntry {
709        SortEntry::new(
710            key,
711            TileFeature {
712                layer: Layer::Buildings,
713                id: key,
714                geom_type: GeomType::Polygon,
715                geometry: vec![9, 0, 0],
716                properties: Arc::new(vec![]),
717                sort_key: 0,
718            },
719        )
720    }
721
722    #[test]
723    fn roundtrip_chunk_write_read() {
724        let dir = tempfile::tempdir().expect("tmpdir");
725        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
726
727        let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
728        entries.sort_unstable();
729        sink.write_chunk(&entries).expect("write");
730
731        let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
732        assert_eq!(read_back.len(), 100);
733        // Verify sorted order
734        for window in read_back.windows(2) {
735            assert!(window[0].key <= window[1].key);
736        }
737    }
738
739    #[test]
740    fn sort_buffer_flush_threshold() {
741        let mut buf = SortBuffer::with_max_bytes(100);
742        let mut full = false;
743        for i in 0..1000 {
744            if buf.push(make_entry(i)) {
745                full = true;
746                break;
747            }
748        }
749        assert!(full, "buffer should fill up");
750        assert!(!buf.is_empty());
751    }
752
753    #[test]
754    fn chunk_reader_streaming() {
755        let dir = tempfile::tempdir().expect("tmpdir");
756        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
757
758        let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
759        sink.write_chunk(&entries).expect("write");
760
761        let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
762        let mut count = 0;
763        while !reader.is_exhausted() {
764            let entry = reader.take().expect("take");
765            if entry.is_some() {
766                count += 1;
767            }
768        }
769        assert_eq!(count, 50);
770    }
771}