mamaps_build: fix all cargo check and clippy warnings
- Commit
4ac8f5dd6e24aa9a9e412cdceed6a2dae467223e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 14:18 UTC (18 days ago)
- Parents
e27eef7
Params structs and type aliases, dead code deleted or cfg(test)-gated, doc/mechanical lint fixes; adapted to osm_ingest PassSpec/Paths APIs. Verified: check/clippy --all-targets 0 warnings, test 293 passed.
Diff
scripts/maps/mamaps_build/src/coalesce.rs
diff --git a/scripts/maps/mamaps_build/src/coalesce.rs b/scripts/maps/mamaps_build/src/coalesce.rsindex da1276945c..3c79565de2 100644--- a/scripts/maps/mamaps_build/src/coalesce.rs+++ b/scripts/maps/mamaps_build/src/coalesce.rs@@ -119,6 +119,7 @@ pub(crate) type Span = (u32, u32); /// /// Polygon features are left exactly as they were, in place; only the parts table and the arena are /// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway.+#[cfg(test)] pub fn coalesce_lines(layer: &mut Layer) -> Stats { coalesce_lines_with_ids(layer, None, None, None, None) }
scripts/maps/mamaps_build/src/dem.rs
diff --git a/scripts/maps/mamaps_build/src/dem.rs b/scripts/maps/mamaps_build/src/dem.rsindex 11680bc2e9..f41c125c9f 100644--- a/scripts/maps/mamaps_build/src/dem.rs+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -199,7 +199,7 @@ impl DemStats { pub fn report(&self) { use std::sync::atomic::Ordering::Relaxed;- println!("DEM grids (error vs the full {}-sample dataset grid, metres):", "dim^2");+ println!("DEM grids (error vs the full dim^2-sample dataset grid, metres):"); let (mut gmx, mut gss, mut gn) = (0.0f64, 0.0f64, 0u64); for z in 0..15 { let g = self.grids[z].load(Relaxed);
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex fdac5ab755..22feb68862 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -68,7 +68,7 @@ use rayon::prelude::*; use crate::schema::{self, Class, Layers}; use crate::store::{- PreRecord, RecordRun, Sink, Store, WayBlock, WayBlockLoc, WayBlocks, WayCounts, WayReader, WaySink,+ PreRecord, RecordRun, Sink, Store, WayBlock, WayBlockLoc, WayBlocks, WayReader, WaySink, WAY_BLOCK_WAYS, }; use tilecodec::mamaps::body::{BuildingAttrs, Carriageway};
scripts/maps/mamaps_build/src/extract_fallback.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback.rs b/scripts/maps/mamaps_build/src/extract_fallback.rsindex 43d597805c..e901bf8518 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -369,6 +369,7 @@ fn select_link(point: (f64, f64), band: Band, candidates: &[&Boundary]) -> Optio /// Reads the finished store twice (boundaries, then places), inserts only keys still missing so /// member links always win, and returns the counts the build log reports. The tiler reads the /// extended map unchanged.+#[cfg(test)] pub fn extend_region_links( store: &crate::store::Store, region_links: &mut HashMap<u64, u64>,@@ -408,7 +409,7 @@ pub fn extend_region_links_with( Boundary(Boundary), Place(PlacePoint), }- // The scan decodes the whole store across the pool (`Store::par_scan`, file order kept), and+ // The scan decodes the whole store across the pool (`Store::par_scan_where`, file order kept), and // the per-feature filter -- including `Boundary::new`'s area and bbox walk -- runs there too. // The split into the two vectors below is in file order, so both are exactly what the // one-cursor loop built.
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 1fd894452d..9df762734f 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -7,16 +7,23 @@ /// `region` filters the **built** layers (`roads`, `poi`, `buildings`) to the /// region's bbox. Every other layer is always included regardless. `None` /// (world) disables the filter entirely.-pub fn extract(- input: &Path,- layers: Layers,- coastline: &Path,- transit_routes: &Path,- graph: &crate::GraphGate,- spill_path: &Path,- region: Option<osm_ingest::bbox::BBox>,- timer: &mut crate::timing::PhaseTimer,-) -> Result<(Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>)> {+/// Inputs for [`extract`], grouped so call sites name them.+pub struct ExtractArgs<'a> {+ pub input: &'a Path,+ pub layers: Layers,+ pub coastline: &'a Path,+ pub transit_routes: &'a Path,+ pub graph: &'a crate::GraphGate,+ pub spill_path: &'a Path,+ pub region: Option<osm_ingest::bbox::BBox>,+ pub timer: &'a mut crate::timing::PhaseTimer,+}++/// What [`extract`] hands back: the sealed store, its stats, and the two id maps.+type ExtractOut = (Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>);++pub fn extract(args: ExtractArgs<'_>) -> Result<ExtractOut> {+ let ExtractArgs { input, layers, coastline, transit_routes, graph, spill_path, region, timer } = args; // Stage A's boundaries are subphase switches on the run's `PhaseTimer`, so an external RSS // sampler can say which of them the peak belongs to. Three candidates sit within seconds of // each other -- the ref vector, the id index built beside it, and the node pass's per-chunk@@ -93,8 +100,8 @@ pub fn extract( promoted, blob_kinds, ways: _,- way_refs,- way_max_ref,+ way_refs: _,+ way_max_ref: _, ways_anon, way_blocks, region_label_nodes,@@ -191,16 +198,16 @@ pub fn extract( drop(members); drop(table); timer.switch("land-polygons");- let store = append_external_and_finish(+ let store = append_external_and_finish(ExternalFinish { coastline, transit_routes, graph, sink,- &mut stats,+ stats: &mut stats, conventions, spill_path, timer,- )?;+ })?; // The place-label -> boundary link, tagged into the id space the archive uses (a place carries // its node id tagged as a node; the mask keys on the boundary's relation id tagged as a // relation). The tiler stamps each `places` label with its linked id from this.@@ -248,8 +255,7 @@ fn plan_ways_spill( return Ok(osm_ingest::mem::SpillPlan::Anon); } let estimate = (input_bytes / 32).max(1 << 30);- let mut budget = osm_ingest::mem::StageBudget::default();- budget.ways_spill_bytes = estimate;+ let budget = osm_ingest::mem::StageBudget { ways_spill_bytes: estimate, ..Default::default() }; // Phase 0 knows nothing else yet; the rest is zero, so `anon_commit_bytes` is just this. let context = format!( "stage A ways spill (pre-pass estimate {} from {} input over {} blobs)",@@ -286,24 +292,26 @@ fn plan_feature_spill( // Distinct nodes <= total refs; the collector dedups, so size the table on the upper bound. // `max_node_id` bounds the rank bitset; `distinct` (upper-bounded here) sizes the resolved // bit and the locs file.- let mut budget = osm_ingest::mem::StageBudget::default();- budget.distinct_nodes = refs_total;- budget.max_node_id = pass1.way_max_ref.max(0) as u64;- budget.ways_spill_bytes = pass1- .ways_anon- .as_ref()- .map(|a| a.len())- .unwrap_or_else(|| std::fs::metadata(spill_path.with_extension("ways.tmp")).map(|m| m.len()).unwrap_or(0)); // Features to come: every classified way and relation materialises at most one feature, plus // the externals below (the junction connectors dominate: ~746 M on planet, arriving after // this gate, hence the ways/2 headroom on the safe side).- budget.features_expected = pass1- .ways- .saturating_add(pass1.relations.len() as u64)- .saturating_add(pass1.ways / 2)- .saturating_add(2_000_000);- budget.bytes_per_feature = SPILL_BYTES_PER_FEATURE;- budget.relations = pass1.relations.len() as u64;+ let mut budget = osm_ingest::mem::StageBudget {+ distinct_nodes: refs_total,+ max_node_id: pass1.way_max_ref.max(0) as u64,+ ways_spill_bytes: pass1+ .ways_anon+ .as_ref()+ .map(|a| a.len())+ .unwrap_or_else(|| std::fs::metadata(spill_path.with_extension("ways.tmp")).map(|m| m.len()).unwrap_or(0)),+ features_expected: pass1+ .ways+ .saturating_add(pass1.relations.len() as u64)+ .saturating_add(pass1.ways / 2)+ .saturating_add(2_000_000),+ bytes_per_feature: SPILL_BYTES_PER_FEATURE,+ relations: pass1.relations.len() as u64,+ ..Default::default()+ }; if !graph.ready_now() { // The graph's size is unknown until `road_graph` finishes, and it shares the junction // phase's peak: take the file backend, the safe side. Same records either way.@@ -415,7 +423,7 @@ fn run_pass1( // // `blob_kinds` comes back from this pass and lets the later ones skip whole blobs, which on a // planet extract is most of the file.- let mut ways = WaySink::create_planned(&ways_path, spill_plan)?;+ let mut ways = WaySink::create_planned(ways_path, spill_plan)?; let mut relations: Vec<Relation> = Vec::new(); // The needed-node bitset, fused into this pass: every classified way sets // its refs here in the drain below, so pass 3 never re-reads the ways@@ -430,10 +438,12 @@ fn run_pass1( let mut corridors: Vec<crate::corridor::Segment> = Vec::new(); let blob_kinds = pbf::run_pass_sink( input,- &blobs,- blob_kinds_in,- KIND_WAYS | KIND_RELATIONS,- "Pass 1: ways and relations",+ blobs,+ pbf::PassSpec {+ blob_kinds: blob_kinds_in,+ want: KIND_WAYS | KIND_RELATIONS,+ label: "Pass 1: ways and relations",+ }, || { ( Vec::<WayBlock>::new(),@@ -510,7 +520,7 @@ fn run_pass1( if state.0.last().is_none_or(|b| b.len() >= WAY_BLOCK_WAYS) { state.0.push(WayBlock::new()); }- let refs: &[i64] = &way.refs[..];+ let refs: &[i64] = way.refs; state.0.last_mut().expect("pushed above").push( way.id, &class,
scripts/maps/mamaps_build/src/extract_part2.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part2.rs b/scripts/maps/mamaps_build/src/extract_part2.rsindex ca97bc5e75..e6e4fd06e1 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -26,8 +26,8 @@ fn load_member_ways( if !wanted.is_empty() { let (chunks, _) = pbf::run_pass( input,- &blobs,- Some(&blob_kinds),+ blobs,+ Some(blob_kinds), KIND_WAYS, "Pass 2: member ways", Vec::<(i64, Vec<i64>)>::new,@@ -93,10 +93,12 @@ impl MemberWays { } /// How many member ways are held.+ #[cfg(test)] pub fn len(&self) -> usize { self.entries.len() } + #[cfg(test)] pub fn is_empty(&self) -> bool { self.entries.is_empty() }@@ -229,7 +231,7 @@ fn build_resolved_table( } Ok(()) };- let table = resolve_nodes_with(input, &blobs, &blob_kinds, "Pass 3: nodes", table, classify, drain)?;+ let table = resolve_nodes_with(input, blobs, blob_kinds, "Pass 3: nodes", table, classify, drain)?; Ok(table) }
scripts/maps/mamaps_build/src/extract_part3.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part3.rs b/scripts/maps/mamaps_build/src/extract_part3.rsindex 50c6e01908..25cef3eba4 100644--- a/scripts/maps/mamaps_build/src/extract_part3.rs+++ b/scripts/maps/mamaps_build/src/extract_part3.rs@@ -203,16 +203,20 @@ fn materialise_relations( } /// Coastline, transit, graph, then finish the store. Moved whole from `extract`.-fn append_external_and_finish(- coastline: &Path,- transit_routes: &Path,- graph: &crate::GraphGate,- mut sink: Sink,- stats: &mut Stats,+/// Inputs for [`append_external_and_finish`], grouped so the one call site names them.+struct ExternalFinish<'a> {+ coastline: &'a Path,+ transit_routes: &'a Path,+ graph: &'a crate::GraphGate,+ sink: Sink,+ stats: &'a mut Stats, conventions: schema::boundaries::Conventions,- spill_path: &Path,- timer: &mut crate::timing::PhaseTimer,-) -> Result<Store> {+ spill_path: &'a Path,+ timer: &'a mut crate::timing::PhaseTimer,+}++fn append_external_and_finish(args: ExternalFinish<'_>) -> Result<Store> {+ let ExternalFinish { coastline, transit_routes, graph, mut sink, stats, conventions, spill_path, timer } = args; // The mainland, last, because clipping it needs the extract's own bounding box and that is // only known once every OSM feature has been through the sink. Order in the file does not // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it@@ -324,6 +328,7 @@ struct NeededBits { } impl NeededBits {+ #[cfg(test)] fn new(max_id: i64) -> Result<NeededBits> { if max_id > MAX_NODE_ID { return err(format!(@@ -372,6 +377,7 @@ impl NeededBits { Ok(()) } + #[cfg(test)] fn set(&mut self, id: i64) -> Result<()> { // A negative ref is not a node this planet has. Refused rather than skipped: it means the // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it.
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 12afc62395..4cb28b4db3 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -241,15 +241,13 @@ fn main() -> ExitCode { // `--region` defaults to world (no filtering). Parsed here so a bad value // fails in seconds, not after stage A.- let region = match region.as_deref().unwrap_or("world") {- s => match osm_ingest::region::Region::parse(s) {- Ok(r) => r,- Err(e) => {- eprintln!("mamaps_build: {}", e.0);- usage();- return ExitCode::from(2);- }- },+ let region = match osm_ingest::region::Region::parse(region.as_deref().unwrap_or("world")) {+ Ok(r) => r,+ Err(e) => {+ eprintln!("mamaps_build: {}", e.0);+ usage();+ return ExitCode::from(2);+ } }; if tiler::SIZE_OPTS.set(size).is_err() {
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex 107903b93d..f581171b7d 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -29,9 +29,7 @@ fn run( // Without them `--graph` must already exist and is validated below. let graph_dir: std::path::PathBuf = if let Some(dir) = run.build_graph_to.as_ref() { println!("building the routing graph in-process -> {}", dir.display());- let mut opts = osm_ingest::graph_build::Options::default();- opts.within_way_chains = true;- opts.bbox = run.region.bbox();+ let opts = osm_ingest::graph_build::Options { within_way_chains: true, bbox: run.region.bbox(), ..Default::default() }; osm_ingest::graph_build::build_with(input, dir, opts) .map_err(|e| format!("graph build: {e}"))?; let ov = osm_ingest::overlay::build(dir, &dir.join("overlay.bin"))@@ -46,14 +44,16 @@ fn run( println!("building the POI sidecars in-process -> {}", dir.display()); let poi_index = dir.join("poi_index.bin"); osm_ingest::poi_build::build_with(- input,- &dir.join("poi.geojsonseq"),- &dir.join("poi_names.bin"),- &poi_index,- &dir.join("poi_attrs.bin"),- &dir.join("poi_spatial.bin"),- &dir.join("poi_name_index.bin"),- &dir.join("poi_region.bin"),+ osm_ingest::poi_build::Paths {+ input,+ geojson: &dir.join("poi.geojsonseq"),+ names: &dir.join("poi_names.bin"),+ index: &poi_index,+ attrs: &dir.join("poi_attrs.bin"),+ spatial: &dir.join("poi_spatial.bin"),+ name_index: &dir.join("poi_name_index.bin"),+ region: &dir.join("poi_region.bin"),+ }, run.region.bbox(), ) .map_err(|e| format!("poi build: {e}"))?;@@ -79,16 +79,16 @@ fn run( // validation) books as overhead; every major stage below switches it, and `finish` emits the // single `TIMING` line before the summary prints. let mut timer = crate::timing::PhaseTimer::start("tiles");- let (store, stats, mut region_links, country_populations) = extract::extract(+ let (store, stats, mut region_links, country_populations) = extract::extract(extract::ExtractArgs { input, layers,- &run.coastline,- &run.transit_routes,- &gate,- &spill,- run.region.bbox(),- &mut timer,- )+ coastline: &run.coastline,+ transit_routes: &run.transit_routes,+ graph: &gate,+ spill_path: &spill,+ region: run.region.bbox(),+ timer: &mut timer,+ }) .map_err(|e| format!("{}: {e}", input.display()))?; // The containment fallback: member-less place labels gain links from the whole-polygon // shapes above, never overwriting a member link. Runs here — after the store is sealed
scripts/maps/mamaps_build/src/rings.rs
diff --git a/scripts/maps/mamaps_build/src/rings.rs b/scripts/maps/mamaps_build/src/rings.rsindex 4600e1237e..18810acac1 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -32,6 +32,9 @@ use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, WINDING_HOLE, WINDING_OUTER}; +/// A kept ring with its bounding box `(min_x, min_y, max_x, max_y)`.+type RingWithBox = (Vec<(i16, i16)>, (i16, i16, i16, i16));+ /// What normalising a build cost, for the report. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct Stats {@@ -63,6 +66,7 @@ impl Stats { /// /// Rebuilds the parts table and the coordinate arena, because dropping a ring changes both and the /// encoder requires the parts to tile the arena exactly.+#[cfg(test)] pub fn normalise(layer: &mut Layer) -> Stats { normalise_with_ids(layer, None, None, None) }@@ -131,7 +135,7 @@ pub fn normalise_with_ids( // field states a fact about the coordinates and the two must agree. // `(ring, box)`, because every containment test below needs the box and computing it per // comparison would put back the quadratic cost the boxes exist to remove.- let mut kept: Vec<(Vec<(i16, i16)>, (i16, i16, i16, i16))> =+ let mut kept: Vec<RingWithBox> = Vec::with_capacity(group.len()); let mut exterior_ring = exterior.to_vec(); if exterior_area < 0.0 {
scripts/maps/mamaps_build/src/rings_part1.rs
diff --git a/scripts/maps/mamaps_build/src/rings_part1.rs b/scripts/maps/mamaps_build/src/rings_part1.rsindex 9de1de8381..662e837c5e 100644--- a/scripts/maps/mamaps_build/src/rings_part1.rs+++ b/scripts/maps/mamaps_build/src/rings_part1.rs@@ -361,7 +361,6 @@ mod tests { /// shape (and its tile-edge crossings) while the test stays instant. #[test] fn lake_superior_survives_coarse_and_fine() {- use crate::schema::Class; use tilecodec::mamaps::body::Body; use tilecodec::mamaps::dict; @@ -447,7 +446,6 @@ mod tests { /// must never hide a country. #[test] fn country_labels_start_at_their_scored_zoom() {- use crate::schema::Class; use tilecodec::mamaps::body::Body; use tilecodec::mamaps::dict;
scripts/maps/mamaps_build/src/schema/boundaries.rs
diff --git a/scripts/maps/mamaps_build/src/schema/boundaries.rs b/scripts/maps/mamaps_build/src/schema/boundaries.rsindex 896f54661c..2870c283aa 100644--- a/scripts/maps/mamaps_build/src/schema/boundaries.rs+++ b/scripts/maps/mamaps_build/src/schema/boundaries.rs@@ -335,6 +335,7 @@ impl Conventions { /// Does the grid know anything at all? Empty for a build with the `boundaries` layer switched /// off, or one whose extract holds no country relation.+ #[cfg(test)] pub fn is_empty(&self) -> bool { self.at.is_empty() }@@ -342,6 +343,7 @@ impl Conventions { /// The grid as the store index carries it: a `u32` count, then a `u32` cell key and a /// [`MarkingConvention`] byte each, ascending by key so a reused store reproduces the run that /// built it byte for byte.+ #[cfg(test)] pub fn to_bytes(&self) -> Vec<u8> { let mut keys: Vec<&u32> = self.at.keys().collect(); keys.sort_unstable();@@ -355,6 +357,7 @@ impl Conventions { } /// The inverse of [`Conventions::to_bytes`], returning the grid and the bytes it consumed.+ #[cfg(test)] pub fn from_bytes(raw: &[u8]) -> osm_ingest::proto::Result<(Conventions, usize)> { if raw.len() < 4 { return osm_ingest::proto::err(
scripts/maps/mamaps_build/src/schema/junction_part1.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part1.rs b/scripts/maps/mamaps_build/src/schema/junction_part1.rsindex e80746a12e..9b3432f603 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part1.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part1.rs@@ -443,17 +443,21 @@ fn effective_lanes(arm: &Arm) -> usize { /// two headings so the curve leaves the approach and meets the exit tangentially. Sampled here, in /// `f64` and once per build, rather than on device once per frame — which is the whole point of /// carrying a polyline instead of control points.-fn connector(+/// Inputs for [`connector`], grouped so the one call site names them.+struct ConnectorArgs<'a> { node: (i32, i32),- approach: &Arm,+ approach: &'a Arm, in_lane: usize, approach_lanes: usize,- exit: &Arm,+ exit: &'a Arm, out_lane: usize, exit_lanes: usize, turn: Turn, left_hand: bool,-) -> Option<Vec<(f64, f64)>> {+}++fn connector(args: ConnectorArgs<'_>) -> Option<Vec<(f64, f64)>> {+ let ConnectorArgs { node, approach, in_lane, approach_lanes, exit, out_lane, exit_lanes, turn, left_hand } = args; let back = (SETBACK_M).min(approach.length_m * SETBACK_EDGE_FRACTION); let ahead = (SETBACK_M).min(exit.length_m * SETBACK_EDGE_FRACTION); if back < MIN_SETBACK_M || ahead < MIN_SETBACK_M {
scripts/maps/mamaps_build/src/schema/junction_part2.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part2.rs b/scripts/maps/mamaps_build/src/schema/junction_part2.rsindex c4819d16b5..23e24b721b 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part2.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part2.rs@@ -197,17 +197,17 @@ fn junctions_for_node( let rank = siblings.iter().position(|&l| l == in_lane).unwrap_or(0); let out_lane = exit_lane(*turn, in_lane, approach_lanes, out_lanes, rank, siblings.len());- let Some(points) = connector(+ let Some(points) = connector(ConnectorArgs { node, approach, in_lane, approach_lanes, exit, out_lane,- out_lanes,- *turn,+ exit_lanes: out_lanes,+ turn: *turn, left_hand,- ) else {+ }) else { continue; }; out.push(points);
scripts/maps/mamaps_build/src/schema/junction_part5.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part5.rs b/scripts/maps/mamaps_build/src/schema/junction_part5.rsindex d1d1f14077..cde754bda6 100644--- a/scripts/maps/mamaps_build/src/schema/junction_part5.rs+++ b/scripts/maps/mamaps_build/src/schema/junction_part5.rs@@ -11,7 +11,9 @@ mod reconstruct_from_planet5 { //! mamaps_build --release reconstruct_from_planet5 -- --ignored --nocapture` use super::*; - fn connectors(dir: &Path, stride: u64) -> Vec<(u64, Vec<Vec<(f64, f64)>>)> {+ type NodeConnectors = Vec<(u64, Vec<Vec<(f64, f64)>>)>;++ fn connectors(dir: &Path, stride: u64) -> NodeConnectors { let graph = Graph::load(dir).expect("graph"); let lanes = LaneTable::load(dir).expect("lanes"); let incoming = InEdges::build(&graph).expect("incoming");
scripts/maps/mamaps_build/src/schema/safety.rs
diff --git a/scripts/maps/mamaps_build/src/schema/safety.rs b/scripts/maps/mamaps_build/src/schema/safety.rsindex ddf40507dd..5785184109 100644--- a/scripts/maps/mamaps_build/src/schema/safety.rs+++ b/scripts/maps/mamaps_build/src/schema/safety.rs@@ -12,6 +12,7 @@ use super::{kind, Class, TagSource}; /// Carried at the archive max only: dense at every intersection and drawn from z16 by overzoom. pub const MIN_ZOOM: u8 = 14; +#[cfg(test)] pub const KINDS: &[&str] = &["speed_camera", "alpr", "surveillance", "stop_sign", "traffic_signals"]; pub const FILTERS: &[&str] = &["highway", "man_made", "enforcement"];
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex 58b795b170..644d87febf 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -35,10 +35,14 @@ use std::path::Path; use osm_ingest::proto::{err, Result};+#[cfg(test)] use tile_build::geom::Geometry;+#[cfg(test)] use tilecodec::mamaps::dict::{self, LAYER_TRAFFIC}; +#[cfg(test)] use super::Class;+#[cfg(test)] use crate::store::Sink; /// The zoom the traffic overlay first surfaces at.@@ -49,16 +53,20 @@ use crate::store::Sink; /// cost 0.38GB on the california build). Raise it to trim the archive further, lower it to show /// motorway congestion sooner. The store packs `min_zoom` in five bits, so anything up to 31 is /// representable.+#[cfg(test)] pub const MIN_ZOOM: u8 = 13; /// Bits reserved for the component-segment index inside a packed component id. Shared on-disk/wire /// contract with the server and the device — keep in sync with `graph.rs::COMPONENT_SEG_BITS` and /// `analysis/traffic_id_contract.md` §1.+#[cfg(test)] pub const COMPONENT_SEG_BITS: u32 = 16;+#[cfg(test)] pub const COMPONENT_SEG_MASK: u64 = (1 << COMPONENT_SEG_BITS) - 1; /// `component_id = (big_edge_id << 16) | seg_index`. #[inline]+#[cfg(test)] pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 { debug_assert!(u64::from(seg_index) <= COMPONENT_SEG_MASK); (big_edge_id << COMPONENT_SEG_BITS) | u64::from(seg_index)@@ -66,6 +74,7 @@ pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 { /// The inverse of [`pack_component_id`]. #[inline]+#[cfg(test)] pub fn unpack_component_id(component_id: u64) -> (u64, u32) { (component_id >> COMPONENT_SEG_BITS, (component_id & COMPONENT_SEG_MASK) as u32) }@@ -76,6 +85,7 @@ pub fn unpack_component_id(component_id: u64) -> (u64, u32) { /// and recoloured by the renderer from a pushed id→speed table, keyed on the `component_id` in the /// body's id side table rather than on any interned attribute. Keeping it out of [`dict::KINDS`] /// avoids disturbing the frozen kind table for a value nothing matches by name.+#[cfg(test)] pub fn traffic_class() -> Class { Class { layer: LAYER_TRAFFIC,@@ -108,6 +118,7 @@ pub(crate) const INTERMEDIATE_BLOCK: u64 = 32; /// One rank word per 512 edges = 64 present bytes (`graph.rs` RANK_BLOCK_BYTES). const RANK_BLOCK_BYTES: usize = 64; /// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`.+#[cfg(test)] const REVERSE_GEOMETRY_FLAG: u8 = 0x40; /// The low six bits of `type_` are the road class. pub(crate) const ROAD_TYPE_MASK: u8 = 0x3F;@@ -513,7 +524,7 @@ impl Graph { let q = |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5); let (mut qlat, mut qlon) = (q(slat), q(slon)); let mut at = 0usize;- let mut uvar = |at: &mut usize| -> Option<u64> {+ let uvar = |at: &mut usize| -> Option<u64> { let (mut r, mut sh) = (0u64, 0u32); while *at < b.len() { let x = b[*at];@@ -580,6 +591,7 @@ impl Graph { /// after the OSM passes and streamed straight into the feature sink. Unlike those two it is not /// clipped to a bbox here — the graph is already the built region, and the tiler clips each segment /// per tile like any other line.+#[cfg(test)] pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result<u64> { let graph = Graph::load(dir)?; let class = traffic_class();
scripts/maps/mamaps_build/src/shapefile.rs
diff --git a/scripts/maps/mamaps_build/src/shapefile.rs b/scripts/maps/mamaps_build/src/shapefile.rsindex d0e506fb8d..2aabf4607e 100644--- a/scripts/maps/mamaps_build/src/shapefile.rs+++ b/scripts/maps/mamaps_build/src/shapefile.rs@@ -25,6 +25,9 @@ use std::path::Path; use osm_ingest::proto::{err, Error, Result}; +/// One record's rings as `(ring, is_exterior)` pairs.+pub type PolygonRings = Vec<(Vec<(f64, f64)>, bool)>;+ /// `.shp` files start with this, big-endian. const FILE_CODE: u32 = 9994; const HEADER_BYTES: usize = 100;@@ -109,7 +112,7 @@ impl ShapeReader { /// /// Rings come back as `(ring, is_exterior)` in file order, so the caller can group them without /// re-deriving orientation.- pub fn next(&mut self) -> Result<Option<Vec<(Vec<(f64, f64)>, bool)>>> {+ pub fn next(&mut self) -> Result<Option<PolygonRings>> { // A record header is 8 bytes; anything less than that left is the end. if self.remaining < 8 { return Ok(None);@@ -153,7 +156,7 @@ impl ShapeReader { } /// One record's rings.-fn parse_polygon(body: &[u8]) -> Result<Option<Vec<(Vec<(f64, f64)>, bool)>>> {+fn parse_polygon(body: &[u8]) -> Result<Option<PolygonRings>> { if body.len() < 4 { return err("a record is too short to name its shape type".to_string()); }
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsindex ce57ef4cf9..0ed7573023 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -51,7 +51,9 @@ //! with the coordinate table after materialise, before the externals. use std::fs::File;-use std::io::{BufRead, BufReader, BufWriter, Write};+use std::io::{BufWriter, Write};+#[cfg(test)]+use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use osm_ingest::proto::{err, zigzag, Error, Result};
scripts/maps/mamaps_build/src/store_part1.rs
diff --git a/scripts/maps/mamaps_build/src/store_part1.rs b/scripts/maps/mamaps_build/src/store_part1.rsindex 01743d7d8c..14f61e2902 100644--- a/scripts/maps/mamaps_build/src/store_part1.rs+++ b/scripts/maps/mamaps_build/src/store_part1.rs@@ -1,7 +1,18 @@+/// A road's extra spill data, grouped for [`Sink::push_road`].+#[cfg(test)]+pub struct RoadAttrs<'a> {+ pub name: Option<&'a str>,+ pub lane_count: u8,+ pub turn_fwd: &'a [u16],+ pub turn_bwd: &'a [u16],+ pub carriageway: Carriageway,+}+ impl Sink { /// The feature spill stages in anonymous pagefile-backed memory (no `.tmp` /// file, nothing stranded on kill). `path` names nothing — it only rides /// along for error messages.+ #[cfg(test)] pub fn create(path: impl AsRef<Path>) -> Result<Sink> { Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon) }@@ -102,17 +113,14 @@ impl Sink { /// masks (body turn-lane table) and the [`Carriageway`] (body carriageway table). Refused with /// no name and all lane data empty — a plain, nameless road goes through [`Sink::push`] and /// carries no extra property at all, so the spill pays nothing for it.+ #[cfg(test)] pub fn push_road( &mut self, class: &Class, geometry: &EncodedGeom,- name: Option<&str>,- lane_count: u8,- turn_fwd: &[u16],- turn_bwd: &[u16],- carriageway: Carriageway,+ road: RoadAttrs<'_>, ) -> Result<()> {- fill_road(&mut self.props, class, name, lane_count, turn_fwd, turn_bwd, carriageway)?;+ fill_road(&mut self.props, class, road.name, road.lane_count, road.turn_fwd, road.turn_bwd, road.carriageway)?; self.write_record(class, geometry) } @@ -121,6 +129,7 @@ impl Sink { /// an all-default building — so the tiler can build a side table dense-parallel to the /// `buildings` layer. A name is written only when present (a building is rarely named; its /// label is usually a `poi`).+ #[cfg(test)] pub fn push_building( &mut self, class: &Class,@@ -168,29 +177,6 @@ impl Sink { } } - /// Extend the bounding box by a geometry, in degrees times 1e7.- fn grow(&mut self, geometry: &Geometry) {- let mut visit = |&(lon, lat): &(f64, f64)| {- let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);- match &mut self.bbox {- None => self.bbox = Some((x, y, x, y)),- Some(b) => {- b.0 = b.0.min(x);- b.1 = b.1.min(y);- b.2 = b.2.max(x);- b.3 = b.3.max(y);- }- }- };- match geometry {- Geometry::Points(points) => points.iter().for_each(&mut visit),- Geometry::Lines(lines) => lines.iter().flatten().for_each(&mut visit),- Geometry::Polygons(polygons) => {- polygons.iter().flatten().flatten().for_each(&mut visit)- }- }- }- pub fn finish(mut self, path: impl Into<PathBuf>) -> Result<Store> { let (count, bbox) = (self.count, self.bbox); // The last chunk is usually partial and still needs an entry.
scripts/maps/mamaps_build/src/store_part2.rs
diff --git a/scripts/maps/mamaps_build/src/store_part2.rs b/scripts/maps/mamaps_build/src/store_part2.rsindex 74171b55f4..f786649542 100644--- a/scripts/maps/mamaps_build/src/store_part2.rs+++ b/scripts/maps/mamaps_build/src/store_part2.rs@@ -36,18 +36,6 @@ impl Store { .collect() } - pub fn from_parts(path: PathBuf, chunks: Vec<u64>, chunk_mins: Vec<u8>) -> Self {- Self {- path,- anon: None,- chunks,- chunk_mins,- count: 0,- bbox: (0, 0, 0, 0),- conventions: crate::schema::boundaries::Conventions::default(),- }- }- /// Open the staged bytes for chunked reading, anonymous or file according to the plan the /// sink was created with. One helper so the three reader constructors agree. fn open_chunks(&self) -> Result<NormalizedChunks> {@@ -76,17 +64,6 @@ impl Store { } } - /// Attach the anonymous store after construction. Used by tests that build- /// a `Store` from parts and then read it back without a file.- #[cfg(test)]- pub fn with_anon(- mut self,- store: std::sync::Arc<tile_build::anon::AnonStore>,- ) -> Self {- self.anon = Some(store);- self- }- /// Take the marking-convention grid stage A resolved from the country relations. pub fn with_conventions( mut self,@@ -159,11 +136,13 @@ impl Store { sink.push_road( &feature.class, &encoded,- feature.name.as_deref(),- feature.lane_count,- &feature.turn_fwd,- &feature.turn_bwd,- feature.carriageway,+ RoadAttrs {+ name: feature.name.as_deref(),+ lane_count: feature.lane_count,+ turn_fwd: &feature.turn_fwd,+ turn_bwd: &feature.turn_bwd,+ carriageway: feature.carriageway,+ }, )?; } else { sink.push_named(&feature.class, &encoded, feature.name.as_deref(), feature.id)?;
scripts/maps/mamaps_build/src/store_part3.rs
diff --git a/scripts/maps/mamaps_build/src/store_part3.rs b/scripts/maps/mamaps_build/src/store_part3.rsindex 2fb293f3b2..ada7308872 100644--- a/scripts/maps/mamaps_build/src/store_part3.rs+++ b/scripts/maps/mamaps_build/src/store_part3.rs@@ -298,6 +298,7 @@ enum WayOut { } impl WaySink {+ #[cfg(test)] pub fn create(path: &Path) -> Result<WaySink> { let file = File::create(path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;@@ -317,6 +318,7 @@ impl WaySink { /// Anonymous twin of [`create`](Self::create): same records in pagefile-backed /// memory, no file. `path` names nothing — it only rides /// along for error messages. Pair with [`WaySink::finish_anon`].+ #[cfg(test)] pub fn create_anon(path: &Path) -> Result<WaySink> { Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon) }@@ -359,6 +361,7 @@ impl WaySink { /// no lane tags; a handful of trailing varints per record, which the scratch file (removed /// after materialise) affords. #[allow(clippy::too_many_arguments)]+ #[cfg(test)] pub fn push( &mut self, id: i64,@@ -474,6 +477,7 @@ impl WaySink { /// capacity, and the realloc that gets it there holds the old and new allocations at once), and /// above it sizes a bitset from `max_ref`. Both numbers are free here, where every ref is already /// being walked to encode it, and neither is recoverable later without a second pass.+ #[cfg(test)] pub fn finish(mut self) -> Result<WayCounts> { match &mut self.out { WayOut::File(f) => f.flush().map_err(|e| Error(format!("cannot flush the ways spill: {e}")))?,@@ -490,6 +494,7 @@ impl WaySink { /// Anonymous twin of [`finish`](Self::finish): seals the pagefile-backed /// spill and hands back the counts plus the staged store. Errors on a /// file-backed sink.+ #[cfg(test)] pub fn finish_anon(mut self) -> Result<(WayCounts, tile_build::anon::AnonStore)> { match &mut self.out { WayOut::File(_) => {@@ -556,8 +561,9 @@ pub struct WayReader { /// Where a [`WayReader`] reads from. enum WayIn {-#[cfg_attr(not(test), allow(dead_code))]+ #[cfg(test)] File(BufReader<File>),+ #[cfg(test)] Anon { store: std::sync::Arc<tile_build::anon::AnonStore>, at: u64,
scripts/maps/mamaps_build/src/store_part4.rs
diff --git a/scripts/maps/mamaps_build/src/store_part4.rs b/scripts/maps/mamaps_build/src/store_part4.rsindex e5c8510af6..1791a88880 100644--- a/scripts/maps/mamaps_build/src/store_part4.rs+++ b/scripts/maps/mamaps_build/src/store_part4.rs@@ -1,5 +1,5 @@ impl WayReader {-#[cfg_attr(not(test), allow(dead_code))]+ #[cfg(test)] pub fn open(path: &Path) -> Result<WayReader> { let file = File::open(path) .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;@@ -13,6 +13,7 @@ impl WayReader { /// Anonymous twin of [`open`](Self::open): reads the sealed store from /// [`WaySink::finish_anon`], shared by refcount. `path` names nothing — /// it only rides along for error messages.+ #[cfg(test)] pub fn open_anon( path: &Path, store: std::sync::Arc<tile_build::anon::AnonStore>,@@ -28,6 +29,7 @@ impl WayReader { /// Open whichever backend the sink sealed: the shared anon store when present, else the file /// at `path`. One helper so the four stage-A readers (two ref collectors, lanefill scan, /// materialise) agree.+ #[cfg(test)] pub fn open_either( path: &Path, store: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,@@ -168,9 +170,11 @@ impl WayReader { /// Peek at the buffered bytes without consuming, filling from the backend first. fn fill_buf(&mut self) -> Result<&[u8]> { match &mut self.inner {+ #[cfg(test)] WayIn::File(f) => f .fill_buf() .map_err(|e| Error(format!("cannot read the ways spill: {e}"))),+ #[cfg(test)] WayIn::Anon { store, at, buf, used } => { if *used >= buf.len() { // Refill: read the next window from the store. 1MB like the@@ -200,7 +204,9 @@ impl WayReader { fn consume(&mut self, n: usize) { match &mut self.inner {+ #[cfg(test)] WayIn::File(f) => f.consume(n),+ #[cfg(test)] WayIn::Anon { used, .. } => *used += n, WayIn::Slice { used, .. } => *used += n, }
scripts/maps/mamaps_build/src/store_part5.rs
diff --git a/scripts/maps/mamaps_build/src/store_part5.rs b/scripts/maps/mamaps_build/src/store_part5.rsindex 5d3126b833..12e6a83cb1 100644--- a/scripts/maps/mamaps_build/src/store_part5.rs+++ b/scripts/maps/mamaps_build/src/store_part5.rs@@ -1,5 +1,6 @@ #[cfg(test)] mod tests {+ type WayCase = (i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway); /// **The guard on chunk skipping.** A zoom-filtered read must yield exactly what a full read /// yields after the same filter, in the same order. Otherwise skipping drops real geometry, and /// the symptom would be a few tiles quietly missing features at one zoom -- no error, no crash.@@ -15,8 +16,8 @@ mod tests { let class = Class::line(dict::LAYER_ROADS, kind, min_zoom); let line = vec![(-120.0 + i as f64 * 0.001, 35.0), (-119.9, 35.1)]; sink.push(&class, &EncodedGeom::live(&Geometry::Lines(vec![line])).expect("encode")).expect("push");- for z in min_zoom as usize..15 {- expected_by_zoom[z].push(kind);+ for expected in expected_by_zoom.iter_mut().skip(min_zoom as usize) {+ expected.push(kind); } } let store = sink.finish(&path).expect("finish");@@ -222,7 +223,7 @@ mod tests { let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3); // Refs chosen to exercise the delta coding: a large first id, a run of neighbours, a jump // backwards, and a way with none at all.- let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway)> = vec![+ let cases: Vec<WayCase> = vec![ (1, lake, vec![10_000_000_001, 10_000_000_002, 10_000_000_003, 9_000_000_000], 0, vec![], vec![], Carriageway::default()), // A four-lane road with forward and backward turn masks and a 3/1 split, all surviving // the spill.@@ -271,7 +272,7 @@ mod tests { fn spilled_ways_come_back_identical_from_anonymous_memory() { let lake = Class::area(dict::LAYER_LANDTYPE, schema::kind("lake"), 6); let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);- let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway)> = vec![+ let cases: Vec<WayCase> = vec![ (1, lake, vec![10_000_000_001, 10_000_000_002, 9_000_000_000], 0, vec![], vec![], Carriageway::default()), ( 2,
scripts/maps/mamaps_build/src/store_part6.rs
diff --git a/scripts/maps/mamaps_build/src/store_part6.rs b/scripts/maps/mamaps_build/src/store_part6.rsindex cb02712e23..7d0125214e 100644--- a/scripts/maps/mamaps_build/src/store_part6.rs+++ b/scripts/maps/mamaps_build/src/store_part6.rs@@ -530,7 +530,8 @@ mod way_block_tests { let dir = std::env::temp_dir().join(format!("mamaps_wayblock_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap();- let mut ways: Vec<(i64, Vec<i64>, Option<String>, u8, Vec<u16>)> = Vec::new();+ type WayRow = (i64, Vec<i64>, Option<String>, u8, Vec<u16>);+ let mut ways: Vec<WayRow> = Vec::new(); let mut id = 7i64; for i in 0..10_000i64 { id += 1 + (i % 5) * 1000;@@ -675,32 +676,16 @@ pub fn geometry_vertices(geometry: &Geometry) -> usize { } impl Store {- /// Every feature in the store, in file order, passed through `keep` on the pool; the kept- /// values come back in file order.- ///- /// The same features [`reader`](Self::reader)'s one sequential cursor yields -- spill chunk by- /// spill chunk, each read with the same `read_into` and decoded with the same `feature_of` --- /// but decoded across the pool. For whole-store scans that keep a sliver (the region- /// fallback's boundary shapes and place labels): on the planet the one-cursor version decoded- /// 1.35 B features on one thread for 8+ minutes.- pub fn par_scan<T, F>(&self, keep: F) -> Result<Vec<T>>- where- T: Send,- F: Fn(Feature) -> Option<T> + Sync,- {- self.par_scan_where(|_, _| true, keep)- }-- /// [`par_scan`](Self::par_scan) with a cheap pre-filter on each record's packed class and+ /// Parallel scan with a cheap pre-filter on each record's packed class and /// whether it carries a feature id: records it rejects are never turned into features (their /// geometry is never decoded), so it must accept every record `keep` could keep. pub fn par_scan_where<T, P, F>(&self, pre: P, keep: F) -> Result<Vec<T>> where T: Send,- P: Fn(&Class, bool) -> bool + Sync,+ P: Fn(&Class, bool) -> bool + Sync + 'static, F: Fn(Feature) -> Option<T> + Sync, {- let pre = |props: &[(String, Value)]| -> bool {+ let pre = move |props: &[(String, Value)]| -> bool { let class = props.iter().find_map(|(k, v)| match (k.as_str(), v) { (CLASS_KEY, Value::Uint(bits)) => Some(unpack(*bits)), _ => None,
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 97907bc033..f3211f3708 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -1,9 +1,12 @@+type EncodedBatch = (Vec<Encoded>, usize, u64, u64);+ /// Tile every feature and write the archive. /// Tile every feature in `store` into a `.mamaps` archive. /// /// The store is read **once per zoom**, in order, rather than held in memory for all of them. Fifteen /// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of /// a measured 10.03 GB California peak.+#[cfg(test)] pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> { adopt_thread_budget(); let mut writer = writer_for(store, settings)?;@@ -381,7 +384,7 @@ fn consume_merged( } Ok(appending.elapsed().as_millis() as u64) },- || -> Result<Option<(Vec<Encoded>, usize, u64, u64)>> {+ || -> Result<Option<EncodedBatch>> { let Some((batch, cuts, merge_ms)) = pulled? else { return Ok(None) }; let tiles = batch.len(); let encoding = std::time::Instant::now();@@ -578,11 +581,10 @@ fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem if store.len() < SMALL_STORE_FEATURES { return osm_ingest::mem::SpillPlan::Anon; }- let mut budget = osm_ingest::mem::StageBudget::default(); // Reuse the anon-commit field for the chunk estimate: it is the number `decide` compares // against the commit allowance, and the chunk spill is the only anon charge this phase adds // (the feature spill is already staged and counted separately).- budget.ways_spill_bytes = store.len().saturating_mul(CHUNK_BYTES_PER_FEATURE);+ let budget = osm_ingest::mem::StageBudget { ways_spill_bytes: store.len().saturating_mul(CHUNK_BYTES_PER_FEATURE), ..Default::default() }; match osm_ingest::mem::SpillPlan::decide(&budget, scratch, "tiler chunk spill") { Ok(plan) => { if plan != osm_ingest::mem::SpillPlan::Anon {@@ -662,7 +664,7 @@ fn map_zoom( .name(format!("mamaps-tile-{i}")) .stack_size(WORKER_STACK) .spawn_scoped(scope, || {- tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms)+ tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms }) }); match worker { Ok(handle) => spawned.push(handle),@@ -672,7 +674,7 @@ fn map_zoom( } } }- tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms);+ tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms }); for handle in spawned { handle.join().map_err(|_| { tile_build::proto::Error("a tiling thread panicked".to_string())@@ -729,7 +731,6 @@ fn map_zoom( /// A feature below the zoom's own floor never arrives: [`crate::store::ZoomReader`] drops it in one /// of its prefetch lanes. That filter used to be right here, and here it was one thread discarding /// most of a billion features — see the reader's own docs for what that cost.- #[cfg(test)] mod tests_part1 { use super::*;
scripts/maps/mamaps_build/src/tiler_part2.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part2.rs b/scripts/maps/mamaps_build/src/tiler_part2.rsindex 1dda9c6263..c6250e7587 100644--- a/scripts/maps/mamaps_build/src/tiler_part2.rs+++ b/scripts/maps/mamaps_build/src/tiler_part2.rs@@ -201,16 +201,23 @@ fn read_chunks( /// /// The spill write is deliberately **outside** the `catch_unwind`, which wraps [`tile_chunk`] alone. /// A failed write records the flag and keeps draining for exactly the same reason a panic does.-fn tile_chunks(- receive: &Mutex<std::sync::mpsc::Receiver<(usize, Vec<Vec<Feature>>)>>,- done: &Mutex<Vec<(usize, ChunkRef, Tally)>>,- failed: &std::sync::atomic::AtomicBool,- spill: &ChunkSpill,+/// The chunk queue one tiling worker drains.+type ChunkReceiver = Mutex<std::sync::mpsc::Receiver<(usize, Vec<Vec<Feature>>)>>;++/// Shared inputs for [`tile_chunks`], grouped so call sites name them.+struct TileChunksCtx<'a> {+ receive: &'a ChunkReceiver,+ done: &'a Mutex<Vec<(usize, ChunkRef, Tally)>>,+ failed: &'a std::sync::atomic::AtomicBool,+ spill: &'a ChunkSpill, z: u8, tolerance: f64, buffer: f64,- country_zooms: &std::collections::HashMap<u64, u8>,-) {+ country_zooms: &'a std::collections::HashMap<u64, u8>,+}++fn tile_chunks(ctx: TileChunksCtx<'_>) {+ let TileChunksCtx { receive, done, failed, spill, z, tolerance, buffer, country_zooms } = ctx; loop { // Held to take a chunk and never while tiling one: the lock covers a pointer move, and the // work either side of it is milliseconds.
scripts/maps/mamaps_build/src/tiler_part3.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part3.rs b/scripts/maps/mamaps_build/src/tiler_part3.rsindex 652066449a..a4c668d814 100644--- a/scripts/maps/mamaps_build/src/tiler_part3.rs+++ b/scripts/maps/mamaps_build/src/tiler_part3.rs@@ -131,11 +131,11 @@ fn concatenate(into: &mut ChunkEntry, from: &mut ChunkEntry) { // the same order the features were, which is what keeps the two parallel. into.ids.extend_from_slice(&from.ids); // The turn masks ride the same way: values parallel to features, concatenated in feature order.- into.turn_lanes.extend(from.turn_lanes.drain(..));+ into.turn_lanes.append(&mut from.turn_lanes); // The building attrs ride the same way, dense-parallel to the buildings layer's features.- into.buildings.extend(from.buildings.drain(..));+ into.buildings.append(&mut from.buildings); // And the carriageways, dense-parallel to the roads layer's.- into.carriageways.extend(from.carriageways.drain(..));+ into.carriageways.append(&mut from.carriageways); } /// Translate `from`'s feature name indices into `into_names`, growing it in first-use order.@@ -201,7 +201,7 @@ fn remap_names(into_names: &mut Vec<String>, from: &ChunkEntry) -> Vec<u16> { /// returns the raw length alongside the compressed frame, because the per-zoom `bytes` column has /// always reported *uncompressed* body size and moving compression must not silently change what a /// build report means.-+/// /// The most features any one tile has carried in each layer. /// /// `body::serialize` caps a tile-layer at [`u16::MAX`] features, and that cap **has already fired**:@@ -423,6 +423,7 @@ fn histogram(chunks: &[ChunkRef], spill: &ChunkSpill) -> Result<Histogram> { /// Cost-balanced range boundaries over one zoom's tile space, with seek positions, for exactly /// `workers` ranges. See [`plan_ranges_from`].+#[cfg(test)] fn plan_ranges( chunks: &[ChunkRef], spill: &ChunkSpill,
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex dd974a003e..d265bfeebb 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -74,9 +74,11 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use tilecodec::mamaps::body::{- BuildingAttrs, Carriageway, Feature as BodyFeature, Layer as BodyLayer, Part,+ BuildingAttrs, Carriageway, Feature as BodyFeature, Part, consts::CARRIAGEWAY_RECORD_LEN, };+#[cfg(test)]+use tilecodec::mamaps::body::Layer as BodyLayer; use tilecodec::proto::{err, Error, Result}; use crate::tiler::ChunkEntry;@@ -156,6 +158,9 @@ pub fn set_read_window(bytes: usize) { WINDOW_OVERRIDE.store(bytes, Ordering::Relaxed); } +/// Tile runs recorded per chunk, keyed by `(chunk_start, chunk_len)`.+type TileRunIndex = Vec<((u64, u64), Vec<TileRun>)>;+ /// Where one chunk's bytes live in a [`ChunkSpill`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct ChunkRef {@@ -170,7 +175,7 @@ pub struct ChunkRef { /// same discipline as `tile_build::spill::NormalizedChunks`, and for the same reason: one handle, /// many threads, positional I/O and no shared cursor. ///-/// Anonymous twin: [`create_anon`](Self::create_anon) stages the same chunks in+/// Anonymous staging (via [`create_planned`](Self::create_planned)) stages the same chunks in /// pagefile-backed memory. Same offsets, same bytes, no /// file. The merge reads through the same [`ChunkReader`] either way. pub struct ChunkSpill {@@ -197,7 +202,7 @@ pub struct ChunkSpill { /// with the next one): its tile runs, recorded by `write_chunk` from /// the map it encoded. What the merge planner reads instead of skip-walking every chunk back /// off disk (twice per zoom: 78 s of the Nov 10 planet build, z14 alone 47 s).- runs: Mutex<Vec<((u64, u64), Vec<TileRun>)>>,+ runs: Mutex<TileRunIndex>, } /// One tile's entries within one chunk, as `write_chunk` laid them down. Narrow on purpose: a@@ -252,15 +257,6 @@ impl ChunkSpill { }) } - /// Anonymous twin-- /// Anonymous twin of [`create`](Self::create): same chunks and offsets in- /// pagefile-backed memory, no file. `path` names nothing — it only rides- /// along for error messages and the `check_books` accounting.- pub fn create_anon(path: impl Into<PathBuf>) -> Result<ChunkSpill> {- Self::create_planned(path, osm_ingest::mem::SpillPlan::Anon)- }- /// Create with an explicit staging plan. See [`osm_ingest::mem::SpillPlan::decide`]: the /// budget gate picks `File` when anon commit does not fit, and `File` stages through the /// scratch path (truncated like [`create`](Self::create), removed on drop). Same chunks,@@ -284,15 +280,6 @@ impl ChunkSpill { } } - /// Whether this spill stages in anonymous memory rather than a file.- pub fn is_anon(&self) -> bool {- self.anon.is_some()- }-- fn file(&self) -> &File {- self.file.as_ref().expect("the tile chunk spill outlives its readers and writers")- }- /// Write one finished chunk and say where it went. /// /// Takes the map **by value** and encodes out of `into_iter`, so the map shrinks as it is
scripts/maps/mamaps_build/src/tilespill_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill_part1.rs b/scripts/maps/mamaps_build/src/tilespill_part1.rsindex a07ab924a5..c4c47935b6 100644--- a/scripts/maps/mamaps_build/src/tilespill_part1.rs+++ b/scripts/maps/mamaps_build/src/tilespill_part1.rs@@ -5,7 +5,7 @@ impl ChunkReader<'_> { /// header, fixed arenas, name lengths, turn counts, building and /// carriageway sections — minus every allocation, UTF-8 check and struct /// build. The range planner uses it to walk chunks cheaply (cost histogram- /// + boundary offsets); the merge workers then decode for real. A corrupt+ /// plus boundary offsets); the merge workers then decode for real. A corrupt /// entry errors here exactly as `next` would surface it, so planning fails /// fast rather than handing workers a desynced stream. ///
scripts/maps/mamaps_build/src/timing.rs
diff --git a/scripts/maps/mamaps_build/src/timing.rs b/scripts/maps/mamaps_build/src/timing.rsindex 408b66a03e..d1e0525f10 100644--- a/scripts/maps/mamaps_build/src/timing.rs+++ b/scripts/maps/mamaps_build/src/timing.rs@@ -104,7 +104,7 @@ impl PhaseTimer { fn close_current(&mut self) { let secs = self.current_start.elapsed().as_secs_f64();- let name = std::mem::replace(&mut self.current, String::new());+ let name = std::mem::take(&mut self.current); self.segments.push((name, secs)); } }