Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / extract_part1.rs

extract_part1.rs396 lines · 19.9 KiBRaw
1/// Read `input` and spill every feature the schema classifies to `spill_path`.
2///
3/// Features go to disk rather than into a `Vec`, because holding them was 4.9 GB of a measured
4/// 10.03 GB California peak and nothing reads them until the tiler does. Classified ways go to a
5/// scratch file beside it for the same reason. See [`crate::store`].
6///
7/// `region` filters the **built** layers (`roads`, `poi`, `buildings`) to the
8/// region's bbox. Every other layer is always included regardless. `None`
9/// (world) disables the filter entirely.
10/// Inputs for [`extract`], grouped so call sites name them.
11pub struct ExtractArgs<'a> {
12 pub input: &'a Path,
13 pub layers: Layers,
14 pub coastline: &'a Path,
15 pub transit_routes: &'a Path,
16 pub graph: &'a crate::GraphGate,
17 pub spill_path: &'a Path,
18 pub region: Option<osm_ingest::bbox::BBox>,
19 pub timer: &'a mut crate::timing::PhaseTimer,
20}
21
22/// What [`extract`] hands back: the sealed store, its stats, and the two id maps.
23type ExtractOut = (Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>);
24
25pub fn extract(args: ExtractArgs<'_>) -> Result<ExtractOut> {
26 let ExtractArgs { input, layers, coastline, transit_routes, graph, spill_path, region, timer } = args;
27 // Stage A's boundaries are subphase switches on the run's `PhaseTimer`, so an external RSS
28 // sampler can say which of them the peak belongs to. Three candidates sit within seconds of
29 // each other -- the ref vector, the id index built beside it, and the node pass's per-chunk
30 // accumulators -- and guessing between them has already cost more than naming them does.
31 let blobs = pbf::scan_blobs(input)?;
32 let select = Select::parse(&schema::filters())?;
33 let mut stats = Stats::default();
34 // Scratch for this function alone: written in pass 1, read twice below, and removed as soon as
35 // the last read is done. Beside the feature spill, so a build directed at a writable output
36 // directory needs nothing else to be writable.
37 let ways_path = spill_path.with_extension("ways.tmp");
38
39 // A blob-kinds mask cached beside the routing graph -- `road_graph`'s pass 1 wrote it over this
40 // same `.pbf` -- lets pass 1 skip node blobs outright rather than inflating them to learn they
41 // hold no ways or relations. Guarded by blob count, file length and a content fingerprint, so a missing or stale
42 // sidecar simply falls back to a full scan. Byte-neutral either way: the mask `run_pass1` returns
43 // carries the skipped blobs' kinds, so it is a complete description of the file regardless.
44 //
45 // The sidecar also proves the graph was built over THIS pbf: when the
46 // region filter is on, a world graph beside a california tile build (or
47 // vice versa) would silently mismatch layers. A missing sidecar here only
48 // warns — the blob mask itself is optional — but a region build still
49 // validates the graph's own coverage below in `append_external_and_finish`.
50 timer.switch("blob-kinds");
51 // Only from a ready graph (`--graph-ready-file`): a sidecar `road_graph` may still be writing
52 // is not read. Without it pass 1 scans every blob -- same output, see above.
53 let graph_kinds = if graph.ready_now() {
54 pbf::load_blob_kinds(graph.dir(), input, &blobs)
55 } else {
56 None
57 };
58 match &graph_kinds {
59 Some(kinds) => println!(
60 "pass 1: blob-kinds sidecar matches this pbf ({} blob(s), {} without ways or relations skipped)",
61 kinds.len(),
62 kinds.iter().filter(|&&k| k & (pbf::KIND_WAYS | pbf::KIND_RELATIONS) == 0).count(),
63 ),
64 None => println!("pass 1: no matching blob-kinds sidecar beside the graph; scanning every blob"),
65 }
66 if let Some(b) = region.as_ref() {
67 println!(
68 "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}",
69 b.min_lon, b.min_lat, b.max_lon, b.max_lat,
70 );
71 }
72
73 let ways_plan = plan_ways_spill(input, &blobs, &ways_path)?;
74 timer.switch("pass1");
75 let pass1 = run_pass1(input, &blobs, graph_kinds.as_deref(), &select, layers, &ways_path, ways_plan, &mut stats, timer)?;
76 timer.switch("member-ways");
77 let members = load_member_ways(input, &blobs, &pass1.blob_kinds, &pass1.relations)?;
78 // --- budget gate (phase 1: real counts) ------------------------------------------
79 //
80 // The planet build died at the junction tail with `cannot commit anon segment` (OS error
81 // 1455): anonymous spills charge RAM+pagefile ("commit"), and nothing checked the charge
82 // against the limit before asking. Pass 1 measured the real counts (classified ways and
83 // relations, total refs, max ref), the ways spill sealed at an exact byte length, and the
84 // graph files stat to theirs -- so the feature spill's backend is decided HERE, from those
85 // counts, failing fast with the numbers when neither backend fits. Same records either way;
86 // the backend never changes a hash.
87 timer.switch("spill-budget");
88 let spill_plan = plan_feature_spill(&pass1, &members, graph, spill_path)?;
89 // Created before the fused node pass below, which spills `places`/`poi` label nodes straight
90 // into it. This sits where pass 4's `Sink::create` used to, moved earlier so those labels reach
91 // the sink in the same order -- chunk order, ahead of every way and relation -- they did when
92 // classification was its own pass after the coordinate resolve. Nothing else touches
93 // `spill_path` until then; the lane-fill temps hang off `with_extension`.
94 let mut sink = Sink::create_planned(spill_path, spill_plan)?;
95 // Take pass 1 apart so each piece can be freed the moment its last reader is done. `pass1`
96 // itself is consumed here: nothing below sees it whole, which is what makes a use-after-free
97 // a compile error rather than a peak.
98 let Pass1Out {
99 relations,
100 promoted,
101 blob_kinds,
102 ways: _,
103 way_refs: _,
104 way_max_ref: _,
105 ways_anon,
106 way_blocks,
107 region_label_nodes,
108 mut needed,
109 } = pass1;
110 // The ways spill, shared by refcount with the readers below (lanefill
111 // scan, materialise). Last use is `materialise_ways`; freed there.
112 timer.switch("refs-collect");
113 // Member ways' refs join the fused bitset: the great majority carry no
114 // tags of their own, so nothing else asked for them.
115 for refs in members.values() {
116 for &id in refs {
117 needed.set_growable(id)?;
118 }
119 }
120 let table = build_resolved_table(
121 input,
122 &blobs,
123 &blob_kinds,
124 &members,
125 needed,
126 &select,
127 layers,
128 region.as_ref(),
129 &mut sink,
130 &mut stats,
131 timer,
132 )?;
133 // The node pass was the last reader of the blob-kinds mask. Freed before lanefill so the
134 // mask (one byte per blob, small) does not pin anything beside it -- and, more importantly,
135 // so the next large allocation cannot sit beside a dead one.
136 drop(blob_kinds);
137 timer.switch("lane-inherit");
138 let way_blocks = WayBlocks::open(&ways_path, &ways_anon, way_blocks)?;
139 let inherited_lanes = inherit_lane_counts(
140 spill_path,
141 &way_blocks,
142 &table,
143 stats.ways_classified as usize,
144 region.as_ref(),
145 )?;
146 stats.lanes_inherited = inherited_lanes.len() as u64;
147
148 // --- materialise ----------------------------------------------------------------------
149 //
150 // Ways in **id order**, which is the order the spill file is already in. The label nodes were
151 // already spilled into `sink` during the fused node pass above, so this only *adds* ways and
152 // relations after them -- the order the tiler groups by layer id from.
153 timer.switch("materialise-ways");
154 materialise_ways(
155 &ways_path,
156 way_blocks,
157 &promoted,
158 &inherited_lanes,
159 &table,
160 region.as_ref(),
161 &mut sink,
162 &mut stats,
163 )?;
164 // The ways spill is dead from here: no later phase reads it. Dropping the `Arc`s unmaps the
165 // anon segments, which releases pagefile commit immediately (unlike heap frees, which the
166 // allocator may hold). This is the tens-of-GB ways spill, freed BEFORE the routing graph
167 // is loaded below -- the two must never peak together.
168 drop(ways_anon);
169 drop(promoted);
170 drop(inherited_lanes);
171 timer.switch("materialise-relations");
172 let conventions = materialise_relations(
173 &relations,
174 &members,
175 &table,
176 region.as_ref(),
177 &mut sink,
178 &mut stats,
179 )?;
180 // Country headcounts for label zoom scoring (see `extract_fallback::country_zoom`):
181 // relation id (tagged) -> `population` tag. Node/way countries have no relation to
182 // read it from and score as unpopulated; the area term still separates Russia from
183 // Nauru. Built BEFORE `relations` is dropped below (it dies at "OSM tables freed").
184 let country_populations: HashMap<u64, u64> = relations
185 .iter()
186 .filter_map(|r| {
187 r.population.and_then(|pop| {
188 (r.class.layer == tilecodec::mamaps::dict::LAYER_PLACES)
189 .then(|| (tagged_id(r.id, ELEMENT_RELATION), pop))
190 })
191 })
192 .collect();
193 // The OSM tables are dead from here: relations, member refs and the coordinate table serve
194 // only materialisation. Dropping them before the externals (coastline, transit, graph)
195 // keeps the RankIndex bitset (~1.5 GB on planet), the resolved bitset and the mapped locs
196 // file out of the junction phase, where `Graph::load` needs its own gigabytes.
197 drop(relations);
198 drop(members);
199 drop(table);
200 timer.switch("land-polygons");
201 let store = append_external_and_finish(ExternalFinish {
202 coastline,
203 transit_routes,
204 graph,
205 sink,
206 stats: &mut stats,
207 conventions,
208 spill_path,
209 timer,
210 })?;
211 // The place-label -> boundary link, tagged into the id space the archive uses (a place carries
212 // its node id tagged as a node; the mask keys on the boundary's relation id tagged as a
213 // relation). The tiler stamps each `places` label with its linked id from this.
214 let region_links: HashMap<u64, u64> = region_label_nodes
215 .iter()
216 .map(|(&node, &rel)| (tagged_id(node, ELEMENT_NODE), tagged_id(rel, ELEMENT_RELATION)))
217 .collect();
218 Ok((store, stats, region_links, country_populations))
219}
220
221/// Spill bytes per classified feature, calibrated from measured builds.
222///
223/// California (10.03 GB peak): ~15.5 M features spilled ~2.0 GB => ~135 B/feature raw. The record
224/// is a varint stream (delta-coded refs were in the *ways* spill, not here; here it is e7
225/// coordinates plus a packed class plus optional names/ids/lane data), so this varies by layer
226/// mix -- but the gate only needs order-of-magnitude, and over-estimating pushes to files, which
227/// is the safe side.
228///
229/// Stored compressed: the spill stages per-chunk DEFLATE frames (~3x on coordinate runs), so the
230/// file holds roughly a third of the raw bytes. 96 B lands between the compressed California
231/// figure (~45 B) and the raw one, leaning the safe way; the gate's job is only to pick the
232/// backend, and files are the safe side.
233const SPILL_BYTES_PER_FEATURE: u64 = 96;
234
235/// Budget gate, phase 0: which backend the *ways* spill stages in.
236///
237/// Runs BEFORE pass 1, so no classified counts exist yet -- only the input size, the blob count
238/// and the commit/disk limits. The ways spill holds one delta-coded record per classified way
239/// (tens of bytes each: a varint id gap, a packed class, delta-coded refs at ~1 B each), and on
240/// planet that is 1.1 B ways => tens of GB. The estimate is deliberately crude (input bytes / 32,
241/// bounded below by 1 GB for planet-scale inputs): over-estimating files a build that would have
242/// fit anon, under-estimating pages it. Files are the safe side -- same records, removed after
243/// materialise -- so the bound leans that way past 8 GB of input.
244fn plan_ways_spill(
245 input: &Path,
246 blobs: &[pbf::BlobLoc],
247 ways_path: &Path,
248) -> Result<osm_ingest::mem::SpillPlan> {
249 let input_bytes = std::fs::metadata(input)
250 .map(|m| m.len())
251 .unwrap_or(0);
252 // No gate on small inputs: the historical anon path, no behaviour change (unless the
253 // `MAPS_FORCE_FILE_SPILL` test knob asks for the planet's file path).
254 if input_bytes < (8u64 << 30) && std::env::var_os("MAPS_FORCE_FILE_SPILL").is_none() {
255 return Ok(osm_ingest::mem::SpillPlan::Anon);
256 }
257 let estimate = (input_bytes / 32).max(1 << 30);
258 let budget = osm_ingest::mem::StageBudget { ways_spill_bytes: estimate, ..Default::default() };
259 // Phase 0 knows nothing else yet; the rest is zero, so `anon_commit_bytes` is just this.
260 let context = format!(
261 "stage A ways spill (pre-pass estimate {} from {} input over {} blobs)",
262 osm_ingest::mem::fmt_gb(estimate),
263 osm_ingest::mem::fmt_gb(input_bytes),
264 blobs.len(),
265 );
266 osm_ingest::mem::SpillPlan::decide(&budget, ways_path, &context)
267 .map_err(osm_ingest::proto::Error)
268}
269
270/// Budget gate, phase 1: which backend the *feature* spill stages in.
271///
272/// Runs AFTER pass 1, so every count is real: classified ways/relations, total refs, max ref, the
273/// sealed ways-spill length, member-way refs. The feature estimate is `ways + relations +
274/// externals` times [`SPILL_BYTES_PER_FEATURE`]; the graph sizes from `metadata.bin`'s
275/// 40-byte header before anything is mapped. Relations move the needle less (8.4 M vs 1.1 B ways
276/// on planet) and are counted at struct overhead -- their member refs are already inside the
277/// distinct-node estimate via the bitset walk.
278///
279/// `ways`, not refs: `Pass1Out::way_refs` is the ref *total* (duplicates included, ~12 G on
280/// planet), which would size the spill 10x over and refuse, on estimates alone, builds whose
281/// real spill fits. The externals headroom leans the safe way instead: the junction connectors
282/// (~746 M on planet) arrive after this gate, so half the way count stands in for them plus
283/// land/transit, pushing continent-scale builds to files (same records, removed on success).
284fn plan_feature_spill(
285 pass1: &Pass1Out,
286 members: &MemberWays,
287 graph: &crate::GraphGate,
288 spill_path: &Path,
289) -> Result<osm_ingest::mem::SpillPlan> {
290 let member_refs: u64 = members.values().map(|refs| refs.len() as u64).sum();
291 let refs_total = pass1.way_refs.saturating_add(member_refs);
292 // Distinct nodes <= total refs; the collector dedups, so size the table on the upper bound.
293 // `max_node_id` bounds the rank bitset; `distinct` (upper-bounded here) sizes the resolved
294 // bit and the locs file.
295 // Features to come: every classified way and relation materialises at most one feature, plus
296 // the externals below (the junction connectors dominate: ~746 M on planet, arriving after
297 // this gate, hence the ways/2 headroom on the safe side).
298 let mut budget = osm_ingest::mem::StageBudget {
299 distinct_nodes: refs_total,
300 max_node_id: pass1.way_max_ref.max(0) as u64,
301 ways_spill_bytes: pass1
302 .ways_anon
303 .as_ref()
304 .map(|a| a.len())
305 .unwrap_or_else(|| std::fs::metadata(spill_path.with_extension("ways.tmp")).map(|m| m.len()).unwrap_or(0)),
306 features_expected: pass1
307 .ways
308 .saturating_add(pass1.relations.len() as u64)
309 .saturating_add(pass1.ways / 2)
310 .saturating_add(2_000_000),
311 bytes_per_feature: SPILL_BYTES_PER_FEATURE,
312 relations: pass1.relations.len() as u64,
313 ..Default::default()
314 };
315 if !graph.ready_now() {
316 // The graph's size is unknown until `road_graph` finishes, and it shares the junction
317 // phase's peak: take the file backend, the safe side. Same records either way.
318 eprintln!(" [stage A] feature spill -> file backend (graph not ready to size)");
319 return Ok(osm_ingest::mem::SpillPlan::File);
320 }
321 budget.graph_bytes = graph_mapped_bytes(graph.dir()).unwrap_or(0);
322 let context = format!(
323 "stage A feature spill ({} ways, {} relations, {} refs, max node {})",
324 pass1.ways, pass1.relations.len(), refs_total, pass1.way_max_ref,
325 );
326 // Warn-and-file rather than fail: the counts above are order-of-magnitude (the feature
327 // estimate most of all), and refusing on them alone would abort builds whose real spill
328 // fits. Files are the safe side -- same records, removed on success -- and a volume that
329 // truly is too small still fails naturally, with its path in the error.
330 match osm_ingest::mem::SpillPlan::decide(&budget, spill_path, &context) {
331 Ok(plan) => Ok(plan),
332 Err(e) => {
333 eprintln!("WARN: {e}; continuing with file staging");
334 Ok(osm_ingest::mem::SpillPlan::File)
335 }
336 }
337}
338
339/// Bytes the junction phase must address at once: the three mapped graph files plus `lanes.bin`,
340/// plus the `InEdges` reverse index (`4 * (node_count + 1)` start array + 4 per drivable edge,
341/// upper-bounded by 4 per edge). Sized from `metadata.bin`'s 40-byte header -- the same header
342/// `check_graph_dir` already validates -- before anything is mapped.
343fn graph_mapped_bytes(dir: &Path) -> Option<u64> {
344 let meta = std::fs::read(dir.join("metadata.bin")).ok()?;
345 if meta.len() < 40 {
346 return None;
347 }
348 let u64_at = |at: usize| {
349 u64::from_le_bytes([
350 meta[at], meta[at + 1], meta[at + 2], meta[at + 3],
351 meta[at + 4], meta[at + 5], meta[at + 6], meta[at + 7],
352 ])
353 };
354 let node_count = u64_at(8);
355 let edge_count = u64_at(16);
356 let nodes = (node_count.saturating_add(1)).saturating_mul(12);
357 let edges = std::fs::metadata(dir.join("edges.bin")).map(|m| m.len()).unwrap_or(edge_count.saturating_mul(7));
358 let inter = std::fs::metadata(dir.join("intermediate.bin")).map(|m| m.len()).unwrap_or(0);
359 let lanes = std::fs::metadata(dir.join("lanes.bin")).map(|m| m.len()).unwrap_or(0);
360 let in_edges = (node_count.saturating_add(1)).saturating_mul(4).saturating_add(edge_count.saturating_mul(4));
361 Some(nodes.saturating_add(edges).saturating_add(inter).saturating_add(lanes).saturating_add(in_edges))
362}
363/// What pass 1 hands the later phases: relations stay resident, corridors
364/// collapse to (way id, zoom) overrides, and the ways spill stages on whichever backend the
365/// budget gate chose, shared by refcount with every later reader (`Some`) or read back from
366/// the file at `ways_path` (`None`).
367struct Pass1Out {
368 relations: Vec<Relation>,
369 promoted: Vec<(i64, u8)>,
370 blob_kinds: Vec<u8>,
371 /// Classified way count (one materialised feature each, at most). Distinct from
372 /// `way_refs` below: the ref total is ~10x the way count and must not size a feature
373 /// estimate.
374 ways: u64,
375 /// Node ref total, duplicates included -- a capacity for the collector, NOT a feature
376 /// count. Planet's ~12 G refs must never be multiplied by bytes-per-feature.
377 way_refs: u64,
378 way_max_ref: i64,
379 /// The sealed ways spill, shared by refcount with every later reader; `None` on the file
380 /// plan, where readers open `ways_path` instead.
381 ways_anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>,
382 /// The block index over the ways spill (either backend), for the parallel readers.
383 way_blocks: Vec<WayBlockLoc>,
384 /// `admin_centre`/`label` node member -> its boundary relation id, both raw OSM ids, for every
385 /// relation that carries a region shape. The authoritative half of the place->boundary link:
386 /// OSM points a boundary relation at its own label node directly, so no geometry test is needed.
387 /// `label` wins over `admin_centre` when a relation lists both, since `label` is the place node
388 /// the map actually renders.
389 region_label_nodes: HashMap<i64, i64>,
390 /// The needed-node bitset, collected during the drain above: every
391 /// classified way's refs plus (set by the caller) the member ways' refs.
392 /// Pass 3 resolves exactly these ids, without re-reading the ways spill.
393 needed: NeededBits,
394}
395
396include!("extract_part1_s1.rs");