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
//! K-way merge of sorted chunk files using a min-heap.
//!
//! Reads from multiple `ChunkReader` streams and yields `SortEntry`
//! items in globally sorted order. Memory usage is O(k) where k is
//! the number of chunk files (one peek entry per reader).

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::path::Path;

use crate::sort::chunk::ChunkReader;
use crate::sort::entry::SortEntry;
use crate::tiles_error::Result;

/// A cursor wrapping a `ChunkReader` with a peeked key for the heap.
struct MergeCursor {
    reader: ChunkReader,
    /// Index of this cursor (the last tie-break, for byte-equal entries).
    index: usize,
}

impl Eq for MergeCursor {}

impl PartialEq for MergeCursor {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl PartialOrd for MergeCursor {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MergeCursor {
    fn cmp(&self, other: &Self) -> Ordering {
        // BinaryHeap is a max-heap; reverse for min-heap behavior. Whole
        // entries are compared, not just keys: chunk order depends on which
        // worker finished first, so it must never decide between two
        // different features with the same key.
        match (self.reader.peek(), other.reader.peek()) {
            (Some(a), Some(b)) => b.cmp(a).then_with(|| other.index.cmp(&self.index)),
            (Some(_), None) => Ordering::Greater,
            (None, Some(_)) => Ordering::Less,
            (None, None) => Ordering::Equal,
        }
    }
}

/// K-way merge iterator over sorted chunk files.
///
/// Yields `SortEntry` items in globally sorted order (ascending key).
pub struct KWayMerge {
    heap: BinaryHeap<MergeCursor>,
}

impl KWayMerge {
    /// Open all chunk files and initialise the merge heap.
    ///
    /// # Errors
    ///
    /// Returns an error if any `ChunkReader::open` call fails.
    pub fn open(paths: &[impl AsRef<Path>]) -> Result<Self> {
        Self::open_with(paths, false)
    }

    /// Open all chunk files like [`Self::open`], and consume them: the disk
    /// space of every block goes back to the file system once the block is
    /// read, and each file is deleted when its last entry is taken. The
    /// chunks cannot be merged a second time.
    ///
    /// # Errors
    ///
    /// Returns an error if any `ChunkReader::open_reclaiming` call fails.
    pub fn open_reclaiming(paths: &[impl AsRef<Path>]) -> Result<Self> {
        Self::open_with(paths, true)
    }

    fn open_with(paths: &[impl AsRef<Path>], reclaim: bool) -> Result<Self> {
        let mut heap = BinaryHeap::with_capacity(paths.len());
        for (i, path) in paths.iter().enumerate() {
            let reader = if reclaim {
                ChunkReader::open_reclaiming(path.as_ref())?
            } else {
                ChunkReader::open(path.as_ref())?
            };
            if !reader.is_exhausted() {
                heap.push(MergeCursor { reader, index: i });
            }
        }
        Ok(Self { heap })
    }

    /// Take the next smallest entry from the merge.
    ///
    /// Returns `None` when all chunk files are fully consumed.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from any chunk reader fails.
    pub fn next_entry(&mut self) -> Result<Option<SortEntry>> {
        let Some(mut cursor) = self.heap.pop() else {
            return Ok(None);
        };

        let entry = cursor.reader.take()?;

        // Re-insert cursor if it still has entries
        if !cursor.reader.is_exhausted() {
            self.heap.push(cursor);
        }

        Ok(entry)
    }
}

/// Convenience: collect all merged entries into a `Vec`.
///
/// Only suitable for testing — planet-scale builds stream entries.
///
/// # Errors
///
/// Returns an error if opening chunk files or reading entries fails.
pub fn merge_all(paths: &[impl AsRef<Path>]) -> Result<Vec<SortEntry>> {
    let mut merger = KWayMerge::open(paths)?;
    let mut result = Vec::new();
    while let Some(entry) = merger.next_entry()? {
        result.push(entry);
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sort::chunk::ChunkSink;
    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::Point,
                geometry: vec![9, 0, 0],
                properties: std::sync::Arc::new(vec![]),
                sort_key: 0,
            },
        )
    }

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

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

        let merged = merge_all(sink.chunk_paths()).expect("merge");
        assert_eq!(merged.len(), 20);
        for window in merged.windows(2) {
            assert!(window[0].key <= window[1].key);
        }
    }

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

        // Chunk A: even keys
        let evens: Vec<SortEntry> = (0..30).filter(|k| k % 2 == 0).map(make_entry).collect();
        sink.write_chunk(&evens).expect("write evens");

        // Chunk B: odd keys
        let odds: Vec<SortEntry> = (0..30).filter(|k| k % 2 == 1).map(make_entry).collect();
        sink.write_chunk(&odds).expect("write odds");

        let merged = merge_all(sink.chunk_paths()).expect("merge");
        assert_eq!(merged.len(), 30);
        // Globally sorted
        for window in merged.windows(2) {
            assert!(window[0].key <= window[1].key);
        }
        // Contains all keys 0..30
        let keys: Vec<u64> = merged.iter().map(|e| e.key).collect();
        assert_eq!(keys, (0..30).collect::<Vec<u64>>());
    }

    /// Features that tie on the key come out in the same order whichever
    /// chunk holds which: chunk order reflects thread scheduling, not input.
    #[test]
    fn tied_keys_merge_the_same_whatever_the_chunk_order() {
        use geolith::tile::feature::PropValue;
        let tied = |id: u64, props: Vec<(&str, PropValue)>| {
            let mut e = make_entry(7);
            e.feature.id = id;
            e.feature.properties =
                std::sync::Arc::new(props.into_iter().map(|(k, v)| (k.to_string(), v)).collect());
            e
        };
        let entries = vec![
            tied(2, vec![]),
            tied(1, vec![("kind", PropValue::Str("b".into()))]),
            tied(1, vec![("kind", PropValue::Str("a".into()))]),
            tied(1, vec![("kind", PropValue::F64(f64::NAN))]),
            tied(1, vec![("kind", PropValue::F64(1.5))]),
            tied(1, vec![("kind", PropValue::I64(-3))]),
            tied(1, vec![("kind", PropValue::U64(3))]),
            tied(1, vec![("kind", PropValue::Bool(true))]),
            tied(1, vec![("kind", PropValue::Bool(false))]),
            tied(1, vec![("rank", PropValue::I64(4))]),
        ];
        let merged_in = |order: &mut dyn Iterator<Item = &SortEntry>| {
            let dir = tempfile::tempdir().expect("tmpdir");
            let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
            for e in order {
                sink.write_chunk(std::slice::from_ref(e)).expect("write");
            }
            merge_all(sink.chunk_paths()).expect("merge")
        };
        let forward = merged_in(&mut entries.iter());
        let backward = merged_in(&mut entries.iter().rev());
        assert_eq!(forward.len(), entries.len());
        // Compare serialized bytes: NaN never equals itself under PartialEq.
        let bytes = |v: &[SortEntry]| -> Vec<Vec<u8>> {
            v.iter().map(|e| e.to_bytes().expect("encode")).collect()
        };
        assert_eq!(bytes(&forward), bytes(&backward));
    }

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

        sink.write_chunk(&[]).expect("write empty");
        // Chunk with one entry
        sink.write_chunk(&[make_entry(42)]).expect("write one");

        let merged = merge_all(sink.chunk_paths()).expect("merge");
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].key, 42);
    }
}