/// Read `input` and spill every feature the schema classifies to `spill_path`. /// /// Features go to disk rather than into a `Vec`, because holding them was 4.9 GB of a measured /// 10.03 GB California peak and nothing reads them until the tiler does. Classified ways go to a /// scratch file beside it for the same reason. See [`crate::store`]. /// /// `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. /// 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, 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, HashMap); pub fn extract(args: ExtractArgs<'_>) -> Result { 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 // accumulators -- and guessing between them has already cost more than naming them does. let blobs = pbf::scan_blobs(input)?; let select = Select::parse(&schema::filters())?; let mut stats = Stats::default(); // Scratch for this function alone: written in pass 1, read twice below, and removed as soon as // the last read is done. Beside the feature spill, so a build directed at a writable output // directory needs nothing else to be writable. let ways_path = spill_path.with_extension("ways.tmp"); // A blob-kinds mask cached beside the routing graph -- `road_graph`'s pass 1 wrote it over this // same `.pbf` -- lets pass 1 skip node blobs outright rather than inflating them to learn they // hold no ways or relations. Guarded by blob count, file length and a content fingerprint, so a missing or stale // sidecar simply falls back to a full scan. Byte-neutral either way: the mask `run_pass1` returns // carries the skipped blobs' kinds, so it is a complete description of the file regardless. // // The sidecar also proves the graph was built over THIS pbf: when the // region filter is on, a world graph beside a california tile build (or // vice versa) would silently mismatch layers. A missing sidecar here only // warns — the blob mask itself is optional — but a region build still // validates the graph's own coverage below in `append_external_and_finish`. timer.switch("blob-kinds"); // Only from a ready graph (`--graph-ready-file`): a sidecar `road_graph` may still be writing // is not read. Without it pass 1 scans every blob -- same output, see above. let graph_kinds = if graph.ready_now() { pbf::load_blob_kinds(graph.dir(), input, &blobs) } else { None }; match &graph_kinds { Some(kinds) => println!( "pass 1: blob-kinds sidecar matches this pbf ({} blob(s), {} without ways or relations skipped)", kinds.len(), kinds.iter().filter(|&&k| k & (pbf::KIND_WAYS | pbf::KIND_RELATIONS) == 0).count(), ), None => println!("pass 1: no matching blob-kinds sidecar beside the graph; scanning every blob"), } if let Some(b) = region.as_ref() { println!( "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}", b.min_lon, b.min_lat, b.max_lon, b.max_lat, ); } let ways_plan = plan_ways_spill(input, &blobs, &ways_path)?; timer.switch("pass1"); let pass1 = run_pass1(input, &blobs, graph_kinds.as_deref(), &select, layers, &ways_path, ways_plan, &mut stats, timer)?; timer.switch("member-ways"); let members = load_member_ways(input, &blobs, &pass1.blob_kinds, &pass1.relations)?; // --- budget gate (phase 1: real counts) ------------------------------------------ // // The planet build died at the junction tail with `cannot commit anon segment` (OS error // 1455): anonymous spills charge RAM+pagefile ("commit"), and nothing checked the charge // against the limit before asking. Pass 1 measured the real counts (classified ways and // relations, total refs, max ref), the ways spill sealed at an exact byte length, and the // graph files stat to theirs -- so the feature spill's backend is decided HERE, from those // counts, failing fast with the numbers when neither backend fits. Same records either way; // the backend never changes a hash. timer.switch("spill-budget"); let spill_plan = plan_feature_spill(&pass1, &members, graph, spill_path)?; // Created before the fused node pass below, which spills `places`/`poi` label nodes straight // into it. This sits where pass 4's `Sink::create` used to, moved earlier so those labels reach // the sink in the same order -- chunk order, ahead of every way and relation -- they did when // classification was its own pass after the coordinate resolve. Nothing else touches // `spill_path` until then; the lane-fill temps hang off `with_extension`. let mut sink = Sink::create_planned(spill_path, spill_plan)?; // Take pass 1 apart so each piece can be freed the moment its last reader is done. `pass1` // itself is consumed here: nothing below sees it whole, which is what makes a use-after-free // a compile error rather than a peak. let Pass1Out { relations, promoted, blob_kinds, ways: _, way_refs: _, way_max_ref: _, ways_anon, way_blocks, region_label_nodes, mut needed, } = pass1; // The ways spill, shared by refcount with the readers below (lanefill // scan, materialise). Last use is `materialise_ways`; freed there. timer.switch("refs-collect"); // Member ways' refs join the fused bitset: the great majority carry no // tags of their own, so nothing else asked for them. for refs in members.values() { for &id in refs { needed.set_growable(id)?; } } let table = build_resolved_table( input, &blobs, &blob_kinds, &members, needed, &select, layers, region.as_ref(), &mut sink, &mut stats, timer, )?; // The node pass was the last reader of the blob-kinds mask. Freed before lanefill so the // mask (one byte per blob, small) does not pin anything beside it -- and, more importantly, // so the next large allocation cannot sit beside a dead one. drop(blob_kinds); timer.switch("lane-inherit"); let way_blocks = WayBlocks::open(&ways_path, &ways_anon, way_blocks)?; let inherited_lanes = inherit_lane_counts( spill_path, &way_blocks, &table, stats.ways_classified as usize, region.as_ref(), )?; stats.lanes_inherited = inherited_lanes.len() as u64; // --- materialise ---------------------------------------------------------------------- // // Ways in **id order**, which is the order the spill file is already in. The label nodes were // already spilled into `sink` during the fused node pass above, so this only *adds* ways and // relations after them -- the order the tiler groups by layer id from. timer.switch("materialise-ways"); materialise_ways( &ways_path, way_blocks, &promoted, &inherited_lanes, &table, region.as_ref(), &mut sink, &mut stats, )?; // The ways spill is dead from here: no later phase reads it. Dropping the `Arc`s unmaps the // anon segments, which releases pagefile commit immediately (unlike heap frees, which the // allocator may hold). This is the tens-of-GB ways spill, freed BEFORE the routing graph // is loaded below -- the two must never peak together. drop(ways_anon); drop(promoted); drop(inherited_lanes); timer.switch("materialise-relations"); let conventions = materialise_relations( &relations, &members, &table, region.as_ref(), &mut sink, &mut stats, )?; // Country headcounts for label zoom scoring (see `extract_fallback::country_zoom`): // relation id (tagged) -> `population` tag. Node/way countries have no relation to // read it from and score as unpopulated; the area term still separates Russia from // Nauru. Built BEFORE `relations` is dropped below (it dies at "OSM tables freed"). let country_populations: HashMap = relations .iter() .filter_map(|r| { r.population.and_then(|pop| { (r.class.layer == tilecodec::mamaps::dict::LAYER_PLACES) .then(|| (tagged_id(r.id, ELEMENT_RELATION), pop)) }) }) .collect(); // The OSM tables are dead from here: relations, member refs and the coordinate table serve // only materialisation. Dropping them before the externals (coastline, transit, graph) // keeps the RankIndex bitset (~1.5 GB on planet), the resolved bitset and the mapped locs // file out of the junction phase, where `Graph::load` needs its own gigabytes. drop(relations); drop(members); drop(table); timer.switch("land-polygons"); let store = append_external_and_finish(ExternalFinish { coastline, transit_routes, graph, sink, 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. let region_links: HashMap = region_label_nodes .iter() .map(|(&node, &rel)| (tagged_id(node, ELEMENT_NODE), tagged_id(rel, ELEMENT_RELATION))) .collect(); Ok((store, stats, region_links, country_populations)) } /// Spill bytes per classified feature, calibrated from measured builds. /// /// California (10.03 GB peak): ~15.5 M features spilled ~2.0 GB => ~135 B/feature raw. The record /// is a varint stream (delta-coded refs were in the *ways* spill, not here; here it is e7 /// coordinates plus a packed class plus optional names/ids/lane data), so this varies by layer /// mix -- but the gate only needs order-of-magnitude, and over-estimating pushes to files, which /// is the safe side. /// /// Stored compressed: the spill stages per-chunk DEFLATE frames (~3x on coordinate runs), so the /// file holds roughly a third of the raw bytes. 96 B lands between the compressed California /// figure (~45 B) and the raw one, leaning the safe way; the gate's job is only to pick the /// backend, and files are the safe side. const SPILL_BYTES_PER_FEATURE: u64 = 96; /// Budget gate, phase 0: which backend the *ways* spill stages in. /// /// Runs BEFORE pass 1, so no classified counts exist yet -- only the input size, the blob count /// and the commit/disk limits. The ways spill holds one delta-coded record per classified way /// (tens of bytes each: a varint id gap, a packed class, delta-coded refs at ~1 B each), and on /// planet that is 1.1 B ways => tens of GB. The estimate is deliberately crude (input bytes / 32, /// bounded below by 1 GB for planet-scale inputs): over-estimating files a build that would have /// fit anon, under-estimating pages it. Files are the safe side -- same records, removed after /// materialise -- so the bound leans that way past 8 GB of input. fn plan_ways_spill( input: &Path, blobs: &[pbf::BlobLoc], ways_path: &Path, ) -> Result { let input_bytes = std::fs::metadata(input) .map(|m| m.len()) .unwrap_or(0); // No gate on small inputs: the historical anon path, no behaviour change (unless the // `MAPS_FORCE_FILE_SPILL` test knob asks for the planet's file path). if input_bytes < (8u64 << 30) && std::env::var_os("MAPS_FORCE_FILE_SPILL").is_none() { return Ok(osm_ingest::mem::SpillPlan::Anon); } let estimate = (input_bytes / 32).max(1 << 30); 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)", osm_ingest::mem::fmt_gb(estimate), osm_ingest::mem::fmt_gb(input_bytes), blobs.len(), ); osm_ingest::mem::SpillPlan::decide(&budget, ways_path, &context) .map_err(osm_ingest::proto::Error) } /// Budget gate, phase 1: which backend the *feature* spill stages in. /// /// Runs AFTER pass 1, so every count is real: classified ways/relations, total refs, max ref, the /// sealed ways-spill length, member-way refs. The feature estimate is `ways + relations + /// externals` times [`SPILL_BYTES_PER_FEATURE`]; the graph sizes from `metadata.bin`'s /// 40-byte header before anything is mapped. Relations move the needle less (8.4 M vs 1.1 B ways /// on planet) and are counted at struct overhead -- their member refs are already inside the /// distinct-node estimate via the bitset walk. /// /// `ways`, not refs: `Pass1Out::way_refs` is the ref *total* (duplicates included, ~12 G on /// planet), which would size the spill 10x over and refuse, on estimates alone, builds whose /// real spill fits. The externals headroom leans the safe way instead: the junction connectors /// (~746 M on planet) arrive after this gate, so half the way count stands in for them plus /// land/transit, pushing continent-scale builds to files (same records, removed on success). fn plan_feature_spill( pass1: &Pass1Out, members: &MemberWays, graph: &crate::GraphGate, spill_path: &Path, ) -> Result { let member_refs: u64 = members.values().map(|refs| refs.len() as u64).sum(); let refs_total = pass1.way_refs.saturating_add(member_refs); // 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. // 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). 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. eprintln!(" [stage A] feature spill -> file backend (graph not ready to size)"); return Ok(osm_ingest::mem::SpillPlan::File); } budget.graph_bytes = graph_mapped_bytes(graph.dir()).unwrap_or(0); let context = format!( "stage A feature spill ({} ways, {} relations, {} refs, max node {})", pass1.ways, pass1.relations.len(), refs_total, pass1.way_max_ref, ); // Warn-and-file rather than fail: the counts above are order-of-magnitude (the feature // estimate most of all), and refusing on them alone would abort builds whose real spill // fits. Files are the safe side -- same records, removed on success -- and a volume that // truly is too small still fails naturally, with its path in the error. match osm_ingest::mem::SpillPlan::decide(&budget, spill_path, &context) { Ok(plan) => Ok(plan), Err(e) => { eprintln!("WARN: {e}; continuing with file staging"); Ok(osm_ingest::mem::SpillPlan::File) } } } /// Bytes the junction phase must address at once: the three mapped graph files plus `lanes.bin`, /// plus the `InEdges` reverse index (`4 * (node_count + 1)` start array + 4 per drivable edge, /// upper-bounded by 4 per edge). Sized from `metadata.bin`'s 40-byte header -- the same header /// `check_graph_dir` already validates -- before anything is mapped. fn graph_mapped_bytes(dir: &Path) -> Option { let meta = std::fs::read(dir.join("metadata.bin")).ok()?; if meta.len() < 40 { return None; } let u64_at = |at: usize| { u64::from_le_bytes([ meta[at], meta[at + 1], meta[at + 2], meta[at + 3], meta[at + 4], meta[at + 5], meta[at + 6], meta[at + 7], ]) }; let node_count = u64_at(8); let edge_count = u64_at(16); let nodes = (node_count.saturating_add(1)).saturating_mul(12); let edges = std::fs::metadata(dir.join("edges.bin")).map(|m| m.len()).unwrap_or(edge_count.saturating_mul(7)); let inter = std::fs::metadata(dir.join("intermediate.bin")).map(|m| m.len()).unwrap_or(0); let lanes = std::fs::metadata(dir.join("lanes.bin")).map(|m| m.len()).unwrap_or(0); let in_edges = (node_count.saturating_add(1)).saturating_mul(4).saturating_add(edge_count.saturating_mul(4)); Some(nodes.saturating_add(edges).saturating_add(inter).saturating_add(lanes).saturating_add(in_edges)) } /// What pass 1 hands the later phases: relations stay resident, corridors /// collapse to (way id, zoom) overrides, and the ways spill stages on whichever backend the /// budget gate chose, shared by refcount with every later reader (`Some`) or read back from /// the file at `ways_path` (`None`). struct Pass1Out { relations: Vec, promoted: Vec<(i64, u8)>, blob_kinds: Vec, /// Classified way count (one materialised feature each, at most). Distinct from /// `way_refs` below: the ref total is ~10x the way count and must not size a feature /// estimate. ways: u64, /// Node ref total, duplicates included -- a capacity for the collector, NOT a feature /// count. Planet's ~12 G refs must never be multiplied by bytes-per-feature. way_refs: u64, way_max_ref: i64, /// The sealed ways spill, shared by refcount with every later reader; `None` on the file /// plan, where readers open `ways_path` instead. ways_anon: Option>, /// The block index over the ways spill (either backend), for the parallel readers. way_blocks: Vec, /// `admin_centre`/`label` node member -> its boundary relation id, both raw OSM ids, for every /// relation that carries a region shape. The authoritative half of the place->boundary link: /// OSM points a boundary relation at its own label node directly, so no geometry test is needed. /// `label` wins over `admin_centre` when a relation lists both, since `label` is the place node /// the map actually renders. region_label_nodes: HashMap, /// The needed-node bitset, collected during the drain above: every /// classified way's refs plus (set by the caller) the member ways' refs. /// Pass 3 resolves exactly these ids, without re-reading the ways spill. needed: NeededBits, } include!("extract_part1_s1.rs");