Modern Apps git

← Modern-Apps.git

maps: mamaps_build --graph-ready-file overlaps road_graph (#perf)

Commit
17469fe04e6fb135cbc933ab73db661d902d1c0d
Author
Vayun Mathur <[email protected]>
When
2026-11-11 05:36 UTC (25 days ago)
Parents
0c35f69
What: a new optional flag, `--graph-ready-file PATH`. The build
starts immediately; every stage that does not read --graph runs
first, and before the first stage that does it waits for PATH to
exist (polling once a second, logging "waiting for graph" and a
line every minute), validates the graph directory exactly as the
preflight does, and carries on. Without the flag behaviour is
unchanged: the graph is ready by definition and validated before
stage A as before.

Which stages read the graph (documented on GraphGate):
- preflight check_graph_dir: deferred to the gate;
- pass 1's blob-kinds sidecar (blob_kinds.bin, a skip list):
  skipped while not ready -- pass 1 scans every blob, same output;
- the feature-spill budget (graph file sizes): file-staged backend
  while not ready, the safe side, same records;
- the junction layer (schema::junction::stream_junctions): the one
  stage that waits.
Passes 1-3, corridors, lane inheritance, materialise ways and
relations, land polygons and transit routes need only the .osm.pbf,
coastline and transit routes; the tiler never reads the graph.
The wait is its own TIMING subphase, "graph-wait".

Why: on the planet road_graph (~28 min, 107 GB peak) and
mamaps_build's stage A ran back to back; the orchestrator can now
start mamaps_build beside road_graph and `touch $GRAPH/.ready` after
road_graph + road_overlay succeed.

Verified on California: started with the ready file absent, ran
stage A, logged "waiting for graph", resumed 20 s later when it was
touched; archive sha256 identical to baseline (94cb7eef...).

Diff

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 ad7bddce77..418685f9ab 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -12,7 +12,7 @@ pub fn extract(     layers: Layers,     coastline: &Path,     transit_routes: &Path,-    graph: &Path,+    graph: &crate::GraphGate,     spill_path: &Path,     region: Option<osm_ingest::bbox::BBox>,     timer: &mut crate::timing::PhaseTimer,@@ -41,7 +41,13 @@ pub fn extract(     // 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");-    let graph_kinds = pbf::load_blob_kinds(graph, input, &blobs);+    // 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+    };     if let Some(b) = region.as_ref() {         println!(             "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}",@@ -264,7 +270,7 @@ fn plan_ways_spill( fn plan_feature_spill(     pass1: &Pass1Out,     members: &MemberWays,-    graph: &Path,+    graph: &crate::GraphGate,     spill_path: &Path, ) -> Result<osm_ingest::mem::SpillPlan> {     let member_refs: u64 = members.values().map(|refs| refs.len() as u64).sum();@@ -290,7 +296,13 @@ fn plan_feature_spill(         .saturating_add(2_000_000);     budget.bytes_per_feature = SPILL_BYTES_PER_FEATURE;     budget.relations = pass1.relations.len() as u64;-    budget.graph_bytes = graph_mapped_bytes(graph).unwrap_or(0);+    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,
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 ef301379f7..9e99ccfec2 100644--- a/scripts/maps/mamaps_build/src/extract_part3.rs+++ b/scripts/maps/mamaps_build/src/extract_part3.rs@@ -206,7 +206,7 @@ fn materialise_relations( fn append_external_and_finish(     coastline: &Path,     transit_routes: &Path,-    graph: &Path,+    graph: &crate::GraphGate,     mut sink: Sink,     stats: &mut Stats,     conventions: schema::boundaries::Conventions,@@ -260,9 +260,16 @@ fn append_external_and_finish(     // node's own incident edges, so there is nothing to read that the traffic pass did not     // already need. `conventions` decides which side of a road the direction of travel sits     // on, and is borrowed here because it is moved into the store below.+    // The first stage that reads `--graph`: with `--graph-ready-file`, everything above ran while+    // `road_graph` was still working, and this is where the build waits for it.+    if !graph.ready_now() {+        timer.switch("graph-wait");+    }+    graph.wait().map_err(osm_ingest::proto::Error)?;     timer.switch("junctions");     println!("building lane connectors from the v6 routing graph for the junction layer");-    stats.junction_connectors = schema::junction::stream_junctions(graph, &conventions, &mut sink)?;+    stats.junction_connectors =+        schema::junction::stream_junctions(graph.dir(), &conventions, &mut sink)?;     stats.features += stats.junction_connectors;     println!("  {} lane connector(s)", stats.junction_connectors);     // `sink.finish` itself is a flush, not a loop: every feature was serialised and its coordinates
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 a834546797..4700095036 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -19,6 +19,11 @@ //! region's bbox. Everything else is always included regardless. `world` (the //! default) disables the filter. //!+//! `--graph-ready-file PATH` lets the build start while `road_graph` is still writing+//! `--graph`: every stage that does not read the graph runs first, and the build waits for PATH+//! to exist (polling once a second, logging "waiting for graph") before the first one that does.+//! See [`GraphGate`] for exactly which stages those are. Without the flag nothing changes.+//! //! `--build-graph-to` / `--build-poi-to` fold the routing graph and POI //! sidecars into this process instead of running `road_graph` / `poi_extract` //! as separate binaries first. Same thread pool, one shared blob scan, and the@@ -122,6 +127,7 @@ fn main() -> ExitCode {     let mut region: Option<String> = None;     let mut build_graph_to: Option<PathBuf> = None;     let mut build_poi_to: Option<PathBuf> = None;+    let mut graph_ready_file: Option<PathBuf> = None;      let mut i = 1;     while i < args.len() {@@ -165,6 +171,10 @@ fn main() -> ExitCode {                 build_poi_to = Some(PathBuf::from(v));                 2             }),+            "--graph-ready-file" => value("--graph-ready-file").map(|v| {+                graph_ready_file = Some(PathBuf::from(v));+                2+            }),             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -209,6 +219,7 @@ fn main() -> ExitCode {         region,         build_graph_to,         build_poi_to,+        graph_ready_file,     };     match run(&input, &out, &settings) {         Ok(()) => ExitCode::SUCCESS,@@ -241,6 +252,9 @@ struct RunSettings {     /// When set, build the POI sidecars in-process into this dir instead of     /// expecting them from a prior `poi_extract` run.     build_poi_to: Option<PathBuf>,+    /// `--graph-ready-file`: start before the routing graph exists and wait for this file to+    /// appear before the first stage that reads `--graph`. See [`GraphGate`].+    graph_ready_file: Option<PathBuf>, }  include!("main_part1.rs");
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 4b00dc5c01..8d2a91d972 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -56,7 +56,18 @@ fn run(     // The graph is validated HERE, before stage A โ€” not 43 minutes in when     // `traffic` tries to read it. This is the failure the world build hit:     // an empty graph dir with no `metadata.bin`, paid for in full.-    check_graph_dir(&graph_dir, run.region)?;+    //+    // With `--graph-ready-file` and the graph not yet ready, validation moves to the gate: it+    // runs the moment the ready file appears, before the first stage that reads the graph.+    let gate = GraphGate::new(graph_dir.clone(), run.graph_ready_file.clone(), run.region);+    if gate.ready_now() {+        gate.wait()?;+    } else {+        println!(+            "graph not ready yet: starting without it, will wait for {} before the junction layer",+            run.graph_ready_file.as_ref().expect("only without the flag is the graph always ready").display(),+        );+    }      // The run's gapless phase clock. Opens in `"other"`, so the setup above (graph/POI builds,     // validation) books as overhead; every major stage below switches it, and `finish` emits the@@ -67,7 +78,7 @@ fn run(         layers,         &run.coastline,         &run.transit_routes,-        &graph_dir,+        &gate,         &spill,         run.region.bbox(),         &mut timer,
scripts/maps/mamaps_build/src/main_part2.rs
diff --git a/scripts/maps/mamaps_build/src/main_part2.rs b/scripts/maps/mamaps_build/src/main_part2.rsindex e0caf6007d..2b6c803998 100644--- a/scripts/maps/mamaps_build/src/main_part2.rs+++ b/scripts/maps/mamaps_build/src/main_part2.rs@@ -1,3 +1,69 @@+/// The routing graph's availability, for `--graph-ready-file`.+///+/// Exactly three things in `mamaps_build` read `--graph`, and they are the only stages that wait:+///+/// | stage | what it reads | without the graph yet |+/// |---|---|---|+/// | preflight (`check_graph_dir`) | `metadata.bin`, `nodes.bin`, `edges.bin`, `intermediate.bin` | deferred to the gate |+/// | pass 1 blob-kinds sidecar (`pbf::load_blob_kinds`) | `blob_kinds.bin` (optional, a skip list) | skipped: pass 1 scans every blob, same output |+/// | feature-spill budget (`plan_feature_spill`) | file sizes of the graph | sized as file-staged (the safe backend), same output |+/// | **junction layer** (`schema::junction::stream_junctions`) | the whole graph + `lanes.bin` | **waits here** |+///+/// Everything before the junction layer -- passes 1-3, corridors, lane inheritance, materialise+/// ways and relations, land polygons, transit routes -- reads only the `.osm.pbf`, the coastline+/// and the transit routes, and runs while `road_graph` is still working. The tiler and+/// everything after it never read the graph. Without the flag the graph is ready by definition+/// and none of this changes behaviour.+pub(crate) struct GraphGate {+    dir: PathBuf,+    ready_file: Option<PathBuf>,+    region: osm_ingest::region::Region,+    validated: std::cell::Cell<bool>,+}++impl GraphGate {+    fn new(dir: PathBuf, ready_file: Option<PathBuf>, region: osm_ingest::region::Region) -> GraphGate {+        GraphGate { dir, ready_file, region, validated: std::cell::Cell::new(false) }+    }++    /// The graph directory.+    pub(crate) fn dir(&self) -> &std::path::Path {+        &self.dir+    }++    /// Whether the graph may be read right now without waiting.+    pub(crate) fn ready_now(&self) -> bool {+        self.validated.get() || self.ready_file.as_ref().is_none_or(|p| p.exists())+    }++    /// Block until the ready file exists (polling once a second), then validate the graph+    /// directory exactly as the preflight does. Idempotent.+    pub(crate) fn wait(&self) -> Result<(), String> {+        if self.validated.get() {+            return Ok(());+        }+        if let Some(ready) = &self.ready_file {+            if !ready.exists() {+                println!("waiting for graph: {}", ready.display());+                let start = std::time::Instant::now();+                let mut said = 0u64;+                while !ready.exists() {+                    std::thread::sleep(std::time::Duration::from_secs(1));+                    let waited = start.elapsed().as_secs();+                    if waited >= said + 60 {+                        said = waited;+                        println!("waiting for graph: {} ({waited}s)", ready.display());+                    }+                }+                println!("graph ready after {:.0}s", start.elapsed().as_secs_f64());+            }+        }+        check_graph_dir(&self.dir, self.region)?;+        self.validated.set(true);+        Ok(())+    }+}+ fn usage() {     eprintln!(         "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\@@ -7,11 +73,13 @@ fn usage() {         \x20                   --dem HEIGHTMAPS.mdem\n\         \x20                   [--region california|world]\n\         \x20                   [--build-graph-to DIR] [--build-poi-to DIR]\n\+        \x20                   [--graph-ready-file PATH]\n\         \n\         \x20All six flags are required. Every build carries all 9 layers at\n\         \x20z0-14 as FORMAT_VERSION 8. --region filters roads/pois/buildings\n\         \x20to the region (default world = no filter); everything else is\n\-        \x20always included."+        \x20always included. --graph-ready-file starts before GRAPH_DIR is\n\+        \x20written and waits for PATH before the junction layer reads it."     ); }