Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/file_source.rs

//! **The file-backed [`MapSource`]** — GeoParquet 1.1 native files on disk, the fake the
//! tests and the Streamlit client use until korp-map's store exists.
//!
//! A region is a directory of osm-katana native exports, `<table>.<encoding>.parquet`
//! with `encoding` ∈ `point` (→ `points`), `multilinestring` (→ `lines`), `multipolygon`
//! (→ `areas`); other files are ignored. The region's name is the directory's name.
//! A kind may have several files (`ways.multipolygon` and
//! `relations.resolved.multipolygon`); the `nodes`/`ways` file comes first, then the
//! others by name, and each must carry the same `geometry` type.
//!
//! **The reply (contract v1.1)** has four columns: `id`, `tags`, `min_zoom` and one
//! `geometry` in the kind's native type. Which stored geometry fills it follows `lod`:
//! the files keep simplified copies `geometry_z6/z9/z12` beside the full `geometry`, and
//! the coarsest one exact enough is sent (lod ≤ 6 → z6, ≤ 9 → z9, ≤ 12 → z12, else full;
//! a copy every file of the kind lacks falls back to the next finer one). Each file's
//! `geo` document says how a copy is stored: in the kind's native type (osm-katana
//! writes them so since `osm-katana-native-zcols`; a copy that shrank below a pixel is
//! NULL there) it is sent as it is; declared `"WKB"` (older exports) it is turned into
//! the native type here. Either way a row whose copy is NULL or does not fit the kind
//! (an area simplified down to a `Point`) is left out. The `geo` document is rewritten
//! for the one column, and `geometry_source` names what was sent.
//!
//! **A query** keeps the rows whose `bbox` covering intersects the viewport and whose
//! `min_zoom` ≤ `lod` (for `points` also: the node is tagged — not null, `""` or `{}`),
//! in file order. A `lod` below the lowest stored `min_zoom` is answered as that level
//! (`geometry_source` then reads e.g. `z6 (as lod 6)`). When more than `max` rows match,
//! the reply takes them by importance, not by file order: every row of the lowest
//! `min_zoom` levels that fit, and what is left of `max` spread evenly over the rows of
//! the level where it runs out — every k-th in file order across all files and row
//! groups, so the whole viewport is covered (file order is Hilbert order within a level,
//! so its first rows would be one corner of the map). Steps:
//!
//! 1. *prune*: row groups whose `bbox.*`/`min_zoom` statistics cannot match are skipped;
//! 2. *scan*: the survivors' `bbox`, `min_zoom` (and, for points, `tags`) leaves are read
//!    and every matching row is recorded with its level (`Cap`) — so `truncated` is
//!    known before the reply starts. Levels deeper than the one where `max` runs out are
//!    not recorded, and a file's scan stops once its remaining row groups hold only such
//!    levels. A row counts only if its geometry will be sent: when the chosen column may
//!    hold a NULL (its statistics say so) or is WKB, it is read here too (for a native
//!    column one coordinate leaf, which carries the row's validity), so `truncated`
//!    means the reply holds `max` rows and at least one more matched;
//! 3. *read*: the kept rows, only the four reply columns' sources, in batches of
//!    `batch_rows`.
//!
//! `row_groups_total` counts the kind's row groups, `row_groups_scanned` the ones step 2
//! read.

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::cast::AsArray;
use arrow_array::{
    Array, ArrayRef, BooleanArray, Float32Array, RecordBatch, StringArray, StructArray, UInt8Array,
};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use bytes::Bytes;
use parquet::arrow::ProjectionMask;
use parquet::arrow::arrow_reader::{
    ArrowReaderMetadata, ArrowReaderOptions, ParquetRecordBatchReader,
    ParquetRecordBatchReaderBuilder, RowSelection, RowSelector,
};
use parquet::file::metadata::RowGroupMetaData;
use parquet::file::statistics::Statistics;

use crate::error::{Code, WireError};
use crate::geoarrow::NativeBuilder;
use crate::source::{BBox, BatchIter, Kind, MapQuery, MapReply, MapSource, Region, ReplyMeta};

/// Rows per reply batch unless told otherwise.
pub const DEFAULT_BATCH_ROWS: usize = 8192;

/// The reply's column names, in order.
pub const REPLY_COLUMNS: [&str; 4] = ["id", "tags", "min_zoom", "geometry"];

fn src_err(what: impl std::fmt::Display) -> WireError {
    WireError::new(Code::SourceFailed, what.to_string())
}

/// Which stored geometry a reply carries.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GeometrySource {
    /// `geometry_z6`.
    Z6,
    /// `geometry_z9`.
    Z9,
    /// `geometry_z12`.
    Z12,
    /// The full `geometry`.
    Full,
}

impl GeometrySource {
    /// Coarsest first.
    pub const ALL: [GeometrySource; 4] = [Self::Z6, Self::Z9, Self::Z12, Self::Full];

    /// The coarsest stored geometry exact enough for `lod`.
    #[must_use]
    pub const fn for_lod(lod: u8) -> Self {
        match lod {
            0..=6 => Self::Z6,
            7..=9 => Self::Z9,
            10..=12 => Self::Z12,
            _ => Self::Full,
        }
    }

    /// The file column it is read from.
    #[must_use]
    pub const fn column(self) -> &'static str {
        match self {
            Self::Z6 => "geometry_z6",
            Self::Z9 => "geometry_z9",
            Self::Z12 => "geometry_z12",
            Self::Full => "geometry",
        }
    }

    /// The `geometry_source` metadata value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Z6 => "z6",
            Self::Z9 => "z9",
            Self::Z12 => "z12",
            Self::Full => "full",
        }
    }
}

/// Leaf column indices the pruning and selection read.
#[derive(Clone, Debug)]
struct Leaves {
    xmin: usize,
    ymin: usize,
    xmax: usize,
    ymax: usize,
    min_zoom: usize,
    tags: usize,
}

/// How a file stores one of its geometries, as its `geo` document declares it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stored {
    /// In the kind's native type.
    Native,
    /// WKB, turned into the native type on the way out.
    Wkb,
}

/// **A served file opened once.** Every read is a positional read (`pread`) on the one
/// descriptor: no read opens, duplicates or seeks a descriptor, so any number of
/// queries and their parts read one file at once, a busy server holds one descriptor
/// per served file whatever its load, and a query never mixes two versions of a file
/// replaced on disk while it runs.
#[derive(Clone, Debug)]
pub struct SharedFile {
    file: Arc<File>,
    len: u64,
}

impl SharedFile {
    /// Open `path` for reading.
    pub fn open(path: &Path) -> std::io::Result<Self> {
        let file = File::open(path)?;
        let len = file.metadata()?.len();
        Ok(Self {
            file: Arc::new(file),
            len,
        })
    }
}

impl parquet::file::reader::Length for SharedFile {
    fn len(&self) -> u64 {
        self.len
    }
}

impl parquet::file::reader::ChunkReader for SharedFile {
    type T = PositionalRead;

    fn get_read(&self, start: u64) -> parquet::errors::Result<PositionalRead> {
        Ok(PositionalRead {
            file: self.file.clone(),
            at: start,
        })
    }

    fn get_bytes(&self, start: u64, length: usize) -> parquet::errors::Result<Bytes> {
        let mut buf = vec![0u8; length];
        self.file.read_exact_at(&mut buf, start)?;
        Ok(buf.into())
    }
}

/// A reader at an offset of a [`SharedFile`], advancing its own position only.
#[derive(Debug)]
pub struct PositionalRead {
    file: Arc<File>,
    at: u64,
}

impl std::io::Read for PositionalRead {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.file.read_at(buf, self.at)?;
        self.at += n as u64;
        Ok(n)
    }
}

/// One native file, its footer cached and opened once.
#[derive(Clone, Debug)]
struct NativeFile {
    path: PathBuf,
    file: SharedFile,
    meta: ArrowReaderMetadata,
    leaves: Leaves,
    /// The stored geometries this file can serve, coarsest first, and how each is stored.
    stored: Vec<(GeometrySource, Stored)>,
}

struct KindData {
    /// The reply's data schema: the four columns and the rewritten `geo` document.
    schema: SchemaRef,
    files: Vec<NativeFile>,
    /// The stored geometries every file of the kind carries.
    sources: Vec<GeometrySource>,
    /// The lowest `min_zoom` stored (row group statistics), if known.
    min_level: Option<u8>,
}

struct RegionData {
    region: Region,
    kinds: BTreeMap<Kind, KindData>,
}

/// GeoParquet native files in directories, one region per directory.
pub struct FileSource {
    regions: Vec<RegionData>,
    batch_rows: usize,
}

fn stat_f64(s: Option<&Statistics>, want_min: bool) -> Option<f64> {
    let s = s?;
    let pick = |min: Option<f64>, max: Option<f64>| if want_min { min } else { max };
    match s {
        Statistics::Float(v) => pick(
            v.min_opt().map(|x| f64::from(*x)),
            v.max_opt().map(|x| f64::from(*x)),
        ),
        Statistics::Double(v) => pick(v.min_opt().copied(), v.max_opt().copied()),
        Statistics::Int32(v) => pick(
            v.min_opt().map(|x| f64::from(*x)),
            v.max_opt().map(|x| f64::from(*x)),
        ),
        Statistics::Int64(v) => pick(
            v.min_opt().map(|x| *x as f64),
            v.max_opt().map(|x| *x as f64),
        ),
        _ => None,
    }
}

/// Does the table stem sort first among the files of its kind?
fn primary_rank(stem: &str) -> u8 {
    match stem {
        "nodes" | "ways" => 0,
        _ => 1,
    }
}

fn geo_doc(schema: &Schema) -> Option<serde_json::Value> {
    serde_json::from_str(schema.metadata().get("geo")?).ok()
}

/// Is a `tags` value a tagged node? (`null`, `""` and `{}` are untagged.)
fn tagged(t: &str) -> bool {
    let t = t.trim();
    !(t.is_empty() || t == "{}")
}

impl NativeFile {
    fn open(path: &Path, kind: Kind) -> Result<Self, WireError> {
        let what = path.display();
        let f = SharedFile::open(path).map_err(|e| src_err(format!("open {what}: {e}")))?;
        let meta = ArrowReaderMetadata::load(&f, ArrowReaderOptions::new())
            .map_err(|e| src_err(format!("parquet footer of {what}: {e}")))?;
        let enc = geo_doc(meta.schema()).and_then(|g| {
            let p = g.get("primary_column")?.as_str()?.to_string();
            Some(g["columns"][p]["encoding"].as_str()?.to_ascii_lowercase())
        });
        if enc.as_deref() != Some(kind.native_encoding()) {
            return Err(src_err(format!(
                "{what}: geo metadata says encoding {enc:?}, the name says {}",
                kind.native_encoding()
            )));
        }
        let s = meta.schema();
        for (name, want) in [
            ("id", DataType::Int64),
            ("tags", DataType::Utf8),
            ("min_zoom", DataType::UInt8),
        ] {
            match s.field_with_name(name) {
                Ok(f) if f.data_type() == &want => {}
                Ok(f) => {
                    return Err(src_err(format!(
                        "{what}: column {name} is {}, not {want}",
                        f.data_type()
                    )));
                }
                Err(_) => return Err(src_err(format!("{what}: no {name} column"))),
            }
        }
        let leaf = |p: &str| {
            meta.metadata()
                .file_metadata()
                .schema_descr()
                .columns()
                .iter()
                .position(|c| c.path().string() == p)
                .ok_or_else(|| src_err(format!("{what}: no {p} column")))
        };
        let leaves = Leaves {
            xmin: leaf("bbox.xmin")?,
            ymin: leaf("bbox.ymin")?,
            xmax: leaf("bbox.xmax")?,
            ymax: leaf("bbox.ymax")?,
            min_zoom: leaf("min_zoom")?,
            tags: leaf("tags")?,
        };
        let stored = Self::stored_sources(&meta, kind);
        Ok(Self {
            path: path.to_path_buf(),
            file: f,
            meta,
            leaves,
            stored,
        })
    }

    /// The stored geometries a file can serve, read off its `geo` document: the primary
    /// `geometry` (checked native at open), and each `geometry_z*` declared either in the
    /// kind's native encoding (with that Arrow type) or `"WKB"` (with a binary type).
    /// A copy declared anything else, or not declared, is not served.
    fn stored_sources(meta: &ArrowReaderMetadata, kind: Kind) -> Vec<(GeometrySource, Stored)> {
        let s = meta.schema();
        let geo = geo_doc(s);
        let native = crate::geoarrow::geometry_type(kind);
        GeometrySource::ALL
            .into_iter()
            .filter_map(|g| {
                if g == GeometrySource::Full {
                    return Some((g, Stored::Native));
                }
                let f = s.field_with_name(g.column()).ok()?;
                let enc = geo.as_ref()?["columns"][g.column()]["encoding"]
                    .as_str()?
                    .to_ascii_lowercase();
                let stored = if enc == "wkb"
                    && matches!(f.data_type(), DataType::Binary | DataType::LargeBinary)
                {
                    Stored::Wkb
                } else if enc == kind.native_encoding() && f.data_type() == &native {
                    Stored::Native
                } else {
                    return None;
                };
                Some((g, stored))
            })
            .collect()
    }

    /// How this file stores `g`, if it has it.
    fn stored(&self, g: GeometrySource) -> Option<Stored> {
        self.stored.iter().find(|(s, _)| *s == g).map(|(_, st)| *st)
    }

    /// The first Parquet leaf of the column `name` (for a native column, its `x`).
    fn first_leaf(&self, name: &str) -> Option<usize> {
        self.meta
            .metadata()
            .file_metadata()
            .schema_descr()
            .columns()
            .iter()
            .position(|c| c.path().parts().first().map(String::as_str) == Some(name))
    }

    fn row_groups(&self) -> &[RowGroupMetaData] {
        self.meta.metadata().row_groups()
    }

    fn geometry_field(&self) -> Result<&Field, WireError> {
        self.meta
            .schema()
            .field_with_name("geometry")
            .map_err(|_| src_err(format!("{}: no geometry column", self.path.display())))
    }

    /// The stored geometries this file can serve.
    fn sources(&self) -> Vec<GeometrySource> {
        self.stored.iter().map(|(g, _)| *g).collect()
    }

    /// The row groups whose statistics may hold a matching row.
    fn prune(&self, q: &MapQuery) -> Vec<usize> {
        let l = &self.leaves;
        self.row_groups()
            .iter()
            .enumerate()
            .filter(|(_, rg)| {
                let st = |i: usize, min: bool| stat_f64(rg.column(i).statistics(), min);
                let ok_le = |v: Option<f64>, bound: f64| v.is_none_or(|v| v <= bound);
                let ok_ge = |v: Option<f64>, bound: f64| v.is_none_or(|v| v >= bound);
                ok_le(st(l.xmin, true), q.bbox.max_lon)
                    && ok_ge(st(l.xmax, false), q.bbox.min_lon)
                    && ok_le(st(l.ymin, true), q.bbox.max_lat)
                    && ok_ge(st(l.ymax, false), q.bbox.min_lat)
                    && ok_le(st(l.min_zoom, true), f64::from(q.lod))
            })
            .map(|(i, _)| i)
            .collect()
    }

    fn builder(&self) -> Result<ParquetRecordBatchReaderBuilder<SharedFile>, WireError> {
        Ok(ParquetRecordBatchReaderBuilder::new_with_metadata(
            self.file.clone(),
            self.meta.clone(),
        ))
    }

    /// The lowest `min_zoom` a row group may hold (its statistics; 0 when unknown).
    fn rg_min_level(&self, rg: usize) -> f64 {
        stat_f64(
            self.row_groups()[rg]
                .column(self.leaves.min_zoom)
                .statistics(),
            true,
        )
        .unwrap_or(0.0)
    }

    /// Step 2: read the candidates' selection leaves and record every matching row
    /// whose `source` geometry will be sent, with its `min_zoom` — only the levels
    /// `cap` still needs, and the scan stops at a row group boundary once every row
    /// group left holds only deeper levels.
    fn scan(
        &self,
        cands: Vec<usize>,
        q: &MapQuery,
        source: GeometrySource,
        batch_rows: usize,
        cap: &mut Cap,
    ) -> Result<Scan, WireError> {
        let l = &self.leaves;
        let what = self.path.display();
        let cands: Vec<usize> = cands
            .into_iter()
            .filter(|&i| {
                cap.level
                    .is_none_or(|c| self.rg_min_level(i) <= f64::from(c))
            })
            .collect();
        let mut out = Scan {
            file: self.clone(),
            cands: cands.clone(),
            hits: Vec::new(),
            touched: 0,
        };
        if cands.is_empty() {
            return Ok(out);
        }
        let mut leaves = vec![l.xmin, l.ymin, l.xmax, l.ymax, l.min_zoom];
        let need_tags = q.kind == Kind::Points;
        if need_tags {
            leaves.push(l.tags);
        }
        // The geometry is read here only when a row may not be sent: a WKB copy (it
        // may not fit the kind) or a native column whose statistics count a null.
        let stored = self
            .stored(source)
            .ok_or_else(|| src_err(format!("{what}: no {}", source.column())))?;
        let geom_leaf = self
            .first_leaf(source.column())
            .ok_or_else(|| src_err(format!("{what}: no {} leaf", source.column())))?;
        let need_geom = stored == Stored::Wkb
            || cands.iter().any(|&i| {
                self.row_groups()[i]
                    .column(geom_leaf)
                    .statistics()
                    .and_then(Statistics::null_count_opt)
                    != Some(0)
            });
        if need_geom {
            leaves.push(geom_leaf);
        }
        let mask =
            ProjectionMask::leaves(self.meta.metadata().file_metadata().schema_descr(), leaves);
        let reader = self
            .builder()?
            .with_row_groups(cands.clone())
            .with_projection(mask)
            .with_batch_size(batch_rows.max(1024))
            .build()
            .map_err(|e| src_err(format!("{}: {e}", self.path.display())))?;

        let rg_rows: Vec<usize> = cands
            .iter()
            .map(|&i| self.row_groups()[i].num_rows() as usize)
            .collect();
        // The lowest level any row group from here on may hold.
        let mut floor_from = vec![f64::INFINITY; cands.len() + 1];
        for k in (0..cands.len()).rev() {
            floor_from[k] = floor_from[k + 1].min(self.rg_min_level(cands[k]));
        }
        let (mut ci, mut done_in_rg, mut pos) = (0usize, 0usize, 0u32);
        out.touched = 1;
        let b = q.bbox;

        'scan: for batch in reader {
            let batch = batch.map_err(|e| src_err(format!("{what}: {e}")))?;
            let bbox = batch
                .column_by_name("bbox")
                .and_then(|c| c.as_any().downcast_ref::<StructArray>())
                .ok_or_else(|| src_err(format!("{what}: bbox is not a struct")))?;
            let child = |n: &str| {
                bbox.column_by_name(n)
                    .and_then(|c| c.as_any().downcast_ref::<Float32Array>())
                    .ok_or_else(|| src_err(format!("{what}: bbox.{n} is not float")))
            };
            let (x0, y0, x1, y1) = (
                child("xmin")?,
                child("ymin")?,
                child("xmax")?,
                child("ymax")?,
            );
            let zoom = batch
                .column_by_name("min_zoom")
                .and_then(|c| c.as_any().downcast_ref::<UInt8Array>())
                .ok_or_else(|| src_err(format!("{what}: min_zoom is not uint8")))?;
            let tags = if need_tags {
                Some(
                    batch
                        .column_by_name("tags")
                        .and_then(|c| c.as_any().downcast_ref::<StringArray>())
                        .ok_or_else(|| src_err(format!("{what}: tags is not a string")))?,
                )
            } else {
                None
            };
            let geom = if need_geom {
                Some(batch.column_by_name(source.column()).ok_or_else(|| {
                    src_err(format!("{what}: no {} in the read", source.column()))
                })?)
            } else {
                None
            };
            let sent = |r: usize| match (geom, stored) {
                (None, _) => true,
                (Some(g), Stored::Native) => g.is_valid(r),
                (Some(g), Stored::Wkb) => {
                    let v = match g.as_binary_opt::<i32>() {
                        Some(a) => a.is_valid(r).then(|| a.value(r)),
                        None => {
                            let a = g.as_binary::<i64>();
                            a.is_valid(r).then(|| a.value(r))
                        }
                    };
                    v.is_some_and(|w| crate::geoarrow::wkb_fits(q.kind, w))
                }
            };
            for r in 0..batch.num_rows() {
                while done_in_rg == rg_rows[ci] {
                    ci += 1;
                    done_in_rg = 0;
                    if cap.level.is_some_and(|c| floor_from[ci] > f64::from(c)) {
                        break 'scan;
                    }
                    out.touched += 1;
                }
                let level = zoom.is_valid(r).then(|| zoom.value(r));
                let hit = level.is_some_and(|z| z <= q.lod && cap.needs(z))
                    && bbox.is_valid(r)
                    && x0.is_valid(r)
                    && y0.is_valid(r)
                    && x1.is_valid(r)
                    && y1.is_valid(r)
                    && f64::from(x0.value(r)) <= b.max_lon
                    && f64::from(x1.value(r)) >= b.min_lon
                    && f64::from(y0.value(r)) <= b.max_lat
                    && f64::from(y1.value(r)) >= b.min_lat
                    && tags.is_none_or(|t| t.is_valid(r) && tagged(t.value(r)))
                    && sent(r);
                if let (true, Some(z)) = (hit, level) {
                    out.hits.push((pos, z));
                    cap.add(z);
                }
                done_in_rg += 1;
                pos += 1;
            }
        }
        Ok(out)
    }
}

/// **The `max` budget of one query, across its files.** Matching rows are counted per
/// `min_zoom` level; once the levels up to some `L` hold more than `max`, rows deeper
/// than `L` are not needed and are not recorded. The reply then keeps every row above
/// `L` (more important) and spreads what is left of `max` evenly over the level-`L`
/// rows in file order (every k-th, across all files and row groups) — never the
/// first rows in file order, which the Hilbert packing makes one corner of the map.
struct Cap {
    max: u64,
    /// Recorded rows per level, `0..=lod`.
    counts: Vec<u64>,
    total: u64,
    /// The cut level `L`, once reached.
    level: Option<u8>,
}

impl Cap {
    fn new(max: u64, lod: u8) -> Self {
        Self {
            max,
            counts: vec![0; usize::from(lod) + 1],
            total: 0,
            level: None,
        }
    }

    /// Is a row of `level` still needed?
    fn needs(&self, level: u8) -> bool {
        self.level.is_none_or(|c| level <= c)
    }

    /// Record one matching row of `level` (one [`Cap::needs`]).
    fn add(&mut self, level: u8) {
        self.counts[usize::from(level)] += 1;
        self.total += 1;
        if self.total <= self.max {
            return;
        }
        let mut cum = 0u64;
        for (l, n) in self.counts.iter().enumerate() {
            cum += n;
            if cum > self.max {
                self.level = Some(l as u8);
                break;
            }
        }
    }

    /// The keep rule for step 3, in the order the rows were recorded.
    fn keep(&self) -> Keep {
        match self.level {
            None => Keep::All,
            Some(l) => {
                let below: u64 = self.counts[..usize::from(l)].iter().sum();
                Keep::Spread {
                    level: l,
                    take: self.max - below,
                    count: self.counts[usize::from(l)],
                    seen: 0,
                }
            }
        }
    }
}

/// Which recorded rows the reply keeps.
enum Keep {
    /// `max` was not reached.
    All,
    /// Rows above `level`, and `take` of the `count` rows at `level`, evenly spaced.
    Spread {
        level: u8,
        take: u64,
        count: u64,
        seen: u64,
    },
}

impl Keep {
    fn keep(&mut self, level: u8) -> bool {
        match self {
            Keep::All => true,
            Keep::Spread {
                level: l,
                take,
                count,
                seen,
            } => {
                if level != *l {
                    return level < *l;
                }
                let i = *seen;
                *seen += 1;
                (i + 1) * *take / *count > i * *take / *count
            }
        }
    }
}

/// What step 2 recorded in one file.
struct Scan {
    file: NativeFile,
    /// The candidate row groups, in order; positions count rows across them.
    cands: Vec<usize>,
    /// Matching rows: position among the candidates' rows, and `min_zoom`.
    hits: Vec<(u32, u8)>,
    /// Row groups whose selection leaves were read.
    touched: u64,
}

impl Scan {
    /// Step 3's plan for this file: the rows `keep` keeps, `None` when it keeps none.
    fn plan(self, keep: &mut Keep) -> Option<FilePlan> {
        let mut hits = self
            .hits
            .into_iter()
            .filter(|&(_, z)| keep.keep(z))
            .peekable();
        let (mut rgs, mut selectors) = (Vec::new(), Vec::new());
        let mut start = 0u32;
        for &rg in &self.cands {
            let end = start + self.file.row_groups()[rg].num_rows() as u32;
            let mut sel = Vec::new();
            let mut cursor = start;
            while let Some(&(p, _)) = hits.peek() {
                if p >= end {
                    break;
                }
                hits.next();
                push_sel(&mut sel, true, (p - cursor) as usize);
                push_sel(&mut sel, false, 1);
                cursor = p + 1;
            }
            if !sel.is_empty() {
                push_sel(&mut sel, true, (end - cursor) as usize);
                rgs.push(rg);
                selectors.extend(sel);
            }
            start = end;
        }
        (!rgs.is_empty()).then(|| FilePlan {
            file: self.file,
            rgs,
            selection: RowSelection::from(selectors),
        })
    }
}

/// Append `n` rows skipped (or selected), merged into the last run when it is the same.
fn push_sel(sel: &mut Vec<RowSelector>, skip: bool, n: usize) {
    if n == 0 {
        return;
    }
    match sel.last_mut() {
        Some(last) if last.skip == skip => last.row_count += n,
        _ => sel.push(if skip {
            RowSelector::skip(n)
        } else {
            RowSelector::select(n)
        }),
    }
}

/// Step 3 for one file.
struct FilePlan {
    file: NativeFile,
    rgs: Vec<usize>,
    selection: RowSelection,
}

/// Reads the planned files one after the other and shapes each batch into the reply.
struct PlanIter {
    schema: SchemaRef,
    kind: Kind,
    source: GeometrySource,
    plans: std::vec::IntoIter<FilePlan>,
    current: Option<(ParquetRecordBatchReader, PathBuf, Stored)>,
    batch_rows: usize,
}

impl PlanIter {
    /// `id, tags, min_zoom, geometry` from a batch of the file's source columns, the
    /// geometry `stored` as the file declares it; rows whose geometry is NULL or does not
    /// fit the kind are left out (step 2 selected none, so this only guards).
    fn shape(
        &self,
        b: &RecordBatch,
        path: &Path,
        stored: Stored,
    ) -> Result<RecordBatch, WireError> {
        let col = |n: &str| {
            b.column_by_name(n)
                .cloned()
                .ok_or_else(|| src_err(format!("{}: no {n} in the read", path.display())))
        };
        let g = col(self.source.column())?;
        let (geometry, keep): (ArrayRef, Option<BooleanArray>) = match stored {
            Stored::Wkb => {
                let mut nb = NativeBuilder::new(self.kind);
                let mut keep = Vec::with_capacity(g.len());
                let mut any_drop = false;
                let mut push = |v: Option<&[u8]>| {
                    let ok = v.is_some_and(|w| nb.push_wkb(w));
                    if v.is_none() {
                        nb.push_null();
                    }
                    any_drop |= !ok;
                    keep.push(ok);
                };
                if let Some(a) = g.as_binary_opt::<i32>() {
                    a.iter().for_each(&mut push);
                } else {
                    g.as_binary::<i64>().iter().for_each(&mut push);
                }
                (nb.finish(), any_drop.then(|| BooleanArray::from(keep)))
            }
            Stored::Native => {
                let keep = (g.null_count() > 0).then(|| {
                    BooleanArray::from((0..g.len()).map(|i| g.is_valid(i)).collect::<Vec<_>>())
                });
                (g, keep)
            }
        };
        let out = RecordBatch::try_new(
            self.schema.clone(),
            vec![col("id")?, col("tags")?, col("min_zoom")?, geometry],
        )
        .map_err(|e| src_err(format!("{}: shape the reply: {e}", path.display())))?;
        match keep {
            Some(k) => arrow_select::filter::filter_record_batch(&out, &k)
                .map_err(|e| src_err(format!("filter: {e}"))),
            None => Ok(out),
        }
    }
}

impl Iterator for PlanIter {
    type Item = Result<RecordBatch, WireError>;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some((reader, path, stored)) = &mut self.current {
                match reader.next() {
                    Some(Ok(b)) => {
                        let (path, stored) = (path.clone(), *stored);
                        match self.shape(&b, &path, stored) {
                            Ok(o) if o.num_rows() == 0 => continue,
                            r => return Some(r),
                        }
                    }
                    Some(Err(e)) => {
                        let e = src_err(format!("{}: {e}", path.display()));
                        self.current = None;
                        self.plans = Vec::new().into_iter();
                        return Some(Err(e));
                    }
                    None => self.current = None,
                }
            }
            let p = self.plans.next()?;
            let source = self.source;
            let stored = p.file.stored(source).ok_or_else(|| {
                src_err(format!("{}: no {}", p.file.path.display(), source.column()))
            });
            let built = stored
                .and_then(|st| p.file.builder().map(|b| (b, st)))
                .and_then(|(bld, st)| {
                    let s = bld.schema().clone();
                    let roots: Vec<usize> = ["id", "tags", "min_zoom", source.column()]
                        .iter()
                        .filter_map(|n| s.index_of(n).ok())
                        .collect();
                    let mask = ProjectionMask::roots(bld.parquet_schema(), roots);
                    bld.with_row_groups(p.rgs)
                        .with_row_selection(p.selection)
                        .with_projection(mask)
                        .with_batch_size(self.batch_rows)
                        .build()
                        .map_err(|e| src_err(format!("{}: {e}", p.file.path.display())))
                        .map(|r| (r, st))
                });
            match built {
                Ok((r, st)) => self.current = Some((r, p.file.path.clone(), st)),
                Err(e) => {
                    self.plans = Vec::new().into_iter();
                    return Some(Err(e));
                }
            }
        }
    }
}

/// FNV-1a over the files' names, sizes and modification times: changes when a file does.
fn data_version(files: &[PathBuf]) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mut eat = |bytes: &[u8]| {
        for b in bytes {
            h ^= u64::from(*b);
            h = h.wrapping_mul(0x0100_0000_01b3);
        }
    };
    for p in files {
        eat(p
            .file_name()
            .map(|n| n.as_encoded_bytes())
            .unwrap_or_default());
        if let Ok(m) = std::fs::metadata(p) {
            eat(&m.len().to_le_bytes());
            let t = m
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .unwrap_or_default();
            eat(&t.as_nanos().to_le_bytes());
        }
    }
    format!("files-{h:016x}")
}

/// The reply schema of a kind whose first file is `first`: the four columns, each as the
/// file declares it, and a `geo` document for the one `geometry` column (no covering:
/// the `bbox` column is not sent).
fn reply_schema(first: &NativeFile) -> Result<SchemaRef, WireError> {
    let s = first.meta.schema();
    let fields: Vec<Field> = REPLY_COLUMNS
        .iter()
        .map(|n| s.field_with_name(n).cloned())
        .collect::<Result<_, _>>()
        .map_err(|e| src_err(format!("{}: {e}", first.path.display())))?;
    let mut geo = geo_doc(s).ok_or_else(|| src_err("no geo metadata"))?;
    let mut col = geo["columns"]["geometry"].clone();
    if let Some(o) = col.as_object_mut() {
        o.remove("covering");
    }
    geo["columns"] = serde_json::json!({ "geometry": col });
    geo["primary_column"] = serde_json::json!("geometry");
    Ok(Arc::new(Schema::new_with_metadata(
        fields,
        HashMap::from([("geo".to_string(), geo.to_string())]),
    )))
}

impl FileSource {
    /// One region: the directory `dir`, named by its last path component.
    pub fn open_dir(dir: &Path) -> Result<Self, WireError> {
        let name = dir
            .canonicalize()
            .ok()
            .and_then(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()))
            .ok_or_else(|| src_err(format!("{}: not a directory with a name", dir.display())))?;
        Self::open(&[(name, dir.to_path_buf())])
    }

    /// Several regions, `(name, directory)`.
    pub fn open(regions: &[(String, PathBuf)]) -> Result<Self, WireError> {
        let mut out = Vec::new();
        for (name, dir) in regions {
            out.push(Self::open_region(name, dir)?);
        }
        Ok(Self {
            regions: out,
            batch_rows: DEFAULT_BATCH_ROWS,
        })
    }

    /// Rows per reply batch.
    #[must_use]
    pub fn with_batch_rows(mut self, n: usize) -> Self {
        self.batch_rows = n.max(1);
        self
    }

    fn open_region(name: &str, dir: &Path) -> Result<RegionData, WireError> {
        let rd =
            std::fs::read_dir(dir).map_err(|e| src_err(format!("read {}: {e}", dir.display())))?;
        let mut found: BTreeMap<Kind, Vec<(u8, String, PathBuf)>> = BTreeMap::new();
        for entry in rd.flatten() {
            let fname = entry.file_name().to_string_lossy().into_owned();
            let Some(stem) = fname.strip_suffix(".parquet") else {
                continue;
            };
            let Some((table, enc)) = stem.rsplit_once('.') else {
                continue;
            };
            let Some(kind) = Kind::from_native_encoding(enc) else {
                continue;
            };
            found
                .entry(kind)
                .or_default()
                .push((primary_rank(table), fname.clone(), entry.path()));
        }
        if found.is_empty() {
            return Err(src_err(format!(
                "{}: no <table>.point|multilinestring|multipolygon.parquet files — native \
                 exports only; an old cut (ways/nodes/relations.parquet) is re-cut, not converted",
                dir.display()
            )));
        }
        let mut kinds = BTreeMap::new();
        let mut all_paths = Vec::new();
        let mut ext: Option<BBox> = None;
        for (kind, mut files) in found {
            files.sort();
            let mut natives = Vec::new();
            for (_, _, p) in &files {
                natives.push(NativeFile::open(p, kind)?);
                all_paths.push(p.clone());
            }
            let schema = reply_schema(&natives[0])?;
            let gtype = schema
                .field_with_name("geometry")
                .map(|f| f.data_type().clone())
                .ok();
            let mut sources: Vec<GeometrySource> = GeometrySource::ALL.to_vec();
            let mut min_level: Option<u8> = None;
            for nf in &natives {
                for rg in 0..nf.row_groups().len() {
                    if let Some(m) = stat_f64(
                        nf.row_groups()[rg].column(nf.leaves.min_zoom).statistics(),
                        true,
                    ) {
                        let m = m.clamp(0.0, 255.0) as u8;
                        min_level = Some(min_level.map_or(m, |x| x.min(m)));
                    }
                }
                let t = nf.geometry_field()?.data_type();
                if Some(t) != gtype.as_ref() {
                    return Err(src_err(format!(
                        "{}: geometry is {t}, the first file's is {gtype:?}",
                        nf.path.display()
                    )));
                }
                let have = nf.sources();
                sources.retain(|s| have.contains(s));
                for rg in nf.row_groups() {
                    let st = |i: usize, min: bool| stat_f64(rg.column(i).statistics(), min);
                    let l = &nf.leaves;
                    if let (Some(a), Some(b), Some(c), Some(d)) = (
                        st(l.xmin, true),
                        st(l.ymin, true),
                        st(l.xmax, false),
                        st(l.ymax, false),
                    ) {
                        let (a, b, c, d) = (a.max(-180.0), b.max(-90.0), c.min(180.0), d.min(90.0));
                        ext = Some(match ext {
                            None => BBox {
                                min_lon: a,
                                min_lat: b,
                                max_lon: c,
                                max_lat: d,
                            },
                            Some(e) => BBox {
                                min_lon: e.min_lon.min(a),
                                min_lat: e.min_lat.min(b),
                                max_lon: e.max_lon.max(c),
                                max_lat: e.max_lat.max(d),
                            },
                        });
                    }
                }
            }
            kinds.insert(
                kind,
                KindData {
                    schema,
                    files: natives,
                    sources,
                    min_level,
                },
            );
        }
        all_paths.sort();
        let bbox = ext.unwrap_or(BBox {
            min_lon: -180.0,
            min_lat: -90.0,
            max_lon: 180.0,
            max_lat: 90.0,
        });
        Ok(RegionData {
            region: Region {
                name: name.to_string(),
                bbox,
                data_version: data_version(&all_paths),
            },
            kinds,
        })
    }

    /// The files serving `kind` in `region`, in reply order.
    #[must_use]
    pub fn files(&self, region: &str, kind: Kind) -> Vec<PathBuf> {
        self.regions
            .iter()
            .find(|r| r.region.name == region)
            .and_then(|r| r.kinds.get(&kind))
            .map(|k| k.files.iter().map(|f| f.path.clone()).collect())
            .unwrap_or_default()
    }

    /// The stored geometry a query of `kind` at `lod` is answered from in `region`.
    #[must_use]
    pub fn geometry_source(&self, region: &str, kind: Kind, lod: u8) -> Option<GeometrySource> {
        let k = self
            .regions
            .iter()
            .find(|r| r.region.name == region)?
            .kinds
            .get(&kind)?;
        let want = GeometrySource::for_lod(lod);
        k.sources.iter().copied().find(|s| *s >= want)
    }
}

impl MapSource for FileSource {
    fn regions(&self) -> Result<Vec<Region>, WireError> {
        Ok(self.regions.iter().map(|r| r.region.clone()).collect())
    }

    fn query(&self, q: &MapQuery) -> Result<MapReply, WireError> {
        q.validate()?;
        let rd = self
            .regions
            .iter()
            .find(|r| r.region.name == q.region)
            .ok_or_else(|| {
                let names: Vec<&str> = self
                    .regions
                    .iter()
                    .map(|r| r.region.name.as_str())
                    .collect();
                WireError::new(
                    Code::UnknownRegion,
                    format!(
                        "region {:?} is not served here (served: {names:?})",
                        q.region
                    ),
                )
            })?;
        let kd = rd.kinds.get(&q.kind).ok_or_else(|| {
            WireError::new(
                Code::UnknownRegion,
                format!("region {:?} serves no {}", q.region, q.kind),
            )
        })?;
        // A lod below every stored `min_zoom` would answer nothing: it is answered as the
        // lowest stored level, and `geometry_source` says so.
        let lod_asked = q.lod;
        let lod = match kd.min_level {
            Some(m) if q.lod < m => m,
            _ => q.lod,
        };
        let q = &MapQuery { lod, ..q.clone() };
        let source = self
            .geometry_source(&q.region, q.kind, lod)
            .ok_or_else(|| src_err(format!("{} {}: no stored geometry", q.region, q.kind)))?;
        let mut cap = Cap::new(q.max.unwrap_or(u64::MAX), lod);
        let (mut total, mut scanned) = (0u64, 0u64);
        let mut scans = Vec::new();
        for f in &kd.files {
            total += f.row_groups().len() as u64;
            let cands = f.prune(q);
            if cands.is_empty() {
                continue;
            }
            let scan = f.scan(cands, q, source, self.batch_rows, &mut cap)?;
            scanned += scan.touched;
            scans.push(scan);
        }
        let truncated = cap.level.is_some();
        let mut keep = cap.keep();
        let plans: Vec<FilePlan> = scans
            .into_iter()
            .filter_map(|s| s.plan(&mut keep))
            .collect();
        let meta = ReplyMeta {
            data_version: rd.region.data_version.clone(),
            truncated,
            row_groups_total: total,
            row_groups_scanned: scanned,
            status: "ok".to_string(),
            geometry_source: if lod == lod_asked {
                source.as_str().to_string()
            } else {
                format!("{} (as lod {lod})", source.as_str())
            },
        };
        let iter = PlanIter {
            schema: kd.schema.clone(),
            kind: q.kind,
            source,
            plans: plans.into_iter(),
            current: None,
            batch_rows: self.batch_rows,
        };
        let batches: BatchIter = Box::new(iter);
        Ok(MapReply::new(&kd.schema, meta, batches))
    }
}

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

    #[test]
    fn lod_picks_the_coarsest_exact_enough_geometry() {
        let got: Vec<&str> = [0u8, 6, 7, 9, 10, 12, 13, 30]
            .map(|l| GeometrySource::for_lod(l).as_str())
            .to_vec();
        assert_eq!(got, ["z6", "z6", "z9", "z9", "z12", "z12", "full", "full"]);
    }

    #[test]
    fn untagged_means_empty_or_an_empty_object() {
        assert!(!tagged(""));
        assert!(!tagged("{}"));
        assert!(!tagged(" {} "));
        assert!(tagged("{\"shop\":\"kiosk\"}"));
    }

    #[test]
    fn a_shared_file_reads_what_the_file_holds_at_any_offset() {
        use parquet::file::reader::{ChunkReader, Length};
        use std::io::Read;
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("f");
        let data: Vec<u8> = (0..10_000u32).map(|i| (i * 7 % 251) as u8).collect();
        std::fs::write(&p, &data).unwrap();
        let f = SharedFile::open(&p).unwrap();
        assert_eq!(f.len(), 10_000);
        assert_eq!(&f.get_bytes(1234, 100).unwrap()[..], &data[1234..1334]);
        // Two readers at once keep their own positions.
        let (mut a, mut b) = (f.get_read(10).unwrap(), f.get_read(5000).unwrap());
        let (mut x, mut y) = ([0u8; 8], [0u8; 8]);
        a.read_exact(&mut x).unwrap();
        b.read_exact(&mut y).unwrap();
        a.read_exact(&mut x).unwrap();
        assert_eq!(&x, &data[18..26]);
        assert_eq!(&y, &data[5000..5008]);
        assert!(f.get_bytes(9_990, 100).is_err());
    }
}