scripts/maps: fix timings
- Commit
9fe3a5ae99906256cddb314857c2f569d9d4d630- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-15 16:47 UTC (1 month ago)
- Parents
f642203
Diff
scripts/maps/build_graph.ps1
diff --git a/scripts/maps/build_graph.ps1 b/scripts/maps/build_graph.ps1index f96c10e0f8..5f364b736a 100644--- a/scripts/maps/build_graph.ps1+++ b/scripts/maps/build_graph.ps1@@ -84,6 +84,98 @@ param( $ErrorActionPreference = "Stop" +# --- cohesive timing ----------------------------------------------------+# Two nested gapless chains plus machine lines from the tools.+#+# Outer chain (this script): $TotalSw runs from here to the final report;+# $PhaseSw is restarted at each phase boundary and its elapsed is booked to+# the phase just finished, so TOTAL WALL always equals the sum of the phase+# rows (within ms). No step owns its own Stopwatch anymore.+#+# Inner chain (PS1-owned subphases): $SubSw mirrors the same stop==start+# contract one level down. Switch-Phase first closes the open subphase into+# the old phase, so a subphase never spans a phase boundary. Used for phases+# with no Rust timer (tools' per-crate cargo builds, verify's steps) and for+# PS1-side work inside a Rust-timed phase (transit's manifest resolution).+#+# Rust-timed phases (graph, transit, tiles, poi, pack) report their own+# subphases as `TIMING {"phase":...,"wall_s":...,"subphases":[...]}` lines on+# stdout (see timing.rs, one copy per crate). Each binary's stdout is Tee'd+# to a per-phase log; the report parses those lines back out. Per-zoom+# `TIMING {"zoom":...}` machine rows ride the same channel.+#+# Closure rule, applied uniformly per phase at report time:+# other = phase_wall - sum(named subphases), clamped at zero.+# PS1 phase walls are ground truth; Rust subphases are the measured detail;+# `other` absorbs spawn/pipe overhead (and the microseconds of boundary skew+# between the two clocks), so subphases always sum to the phase wall.+#+# To time a new step: one Switch-Phase/Switch-Subphase call at its boundary+# (Rust side: one timer.switch), and it appears in TIME + timing.json.+$script:PhaseTimes = [ordered]@{}+$script:SubTimes = [ordered]@{} # "phase/sub" -> seconds, PS1-owned subphases only+$script:TotalSw = [System.Diagnostics.Stopwatch]::StartNew()+$script:PhaseSw = [System.Diagnostics.Stopwatch]::StartNew()+$script:SubSw = [System.Diagnostics.Stopwatch]::StartNew()+$script:PhaseCurrent = "preflight"+$script:SubCurrent = "other"+function Switch-Subphase([string] $Next) {+ # Read first, restart second: the boundary instant belongs to neither+ # subphase twice and to no gap. Bookkeeping happens after the restart so+ # it never leaks into either subphase.+ $elapsed = $script:SubSw.Elapsed.TotalSeconds+ $script:SubSw.Restart()+ $key = "$($script:PhaseCurrent)/$($script:SubCurrent)"+ if ($script:SubTimes.Contains($key)) { $script:SubTimes[$key] += $elapsed } else { $script:SubTimes[$key] = $elapsed }+ $script:SubCurrent = $Next+}+function Switch-Phase([string] $Next) {+ # Close the open subphase into the OLD phase first, so no subphase ever+ # spans a phase boundary; then the phase switch itself, as before.+ Switch-Subphase "other" | Out-Null+ $elapsed = $script:PhaseSw.Elapsed.TotalSeconds+ $script:PhaseSw.Restart()+ if ($script:PhaseTimes.Contains($script:PhaseCurrent)) { $script:PhaseTimes[$script:PhaseCurrent] += $elapsed } else { $script:PhaseTimes[$script:PhaseCurrent] = $elapsed }+ $script:PhaseCurrent = $Next+}+function Stop-Phases() {+ Switch-Subphase "other" | Out-Null+ $elapsed = $script:PhaseSw.Elapsed.TotalSeconds+ $script:PhaseSw.Stop()+ $script:TotalSw.Stop()+ $script:SubSw.Stop()+ if ($script:PhaseTimes.Contains($script:PhaseCurrent)) { $script:PhaseTimes[$script:PhaseCurrent] += $elapsed } else { $script:PhaseTimes[$script:PhaseCurrent] = $elapsed }+}+# Parse one phase log's `TIMING {...}` machine lines. Returns+# @{ wall = <phase wall_s>; subs = [ordered]@{ name = seconds } } for the+# last "phase" line found ($null when the tool never emitted one, e.g. a+# skipped -NoTransit step), plus any per-zoom rows in @{ zooms = @() }.+function Read-TimingLog([string] $Path) {+ $phase = $null+ $zooms = @()+ if (-not (Test-Path $Path)) { return @{ phase = $phase; zooms = $zooms } }+ foreach ($line in (Get-Content $Path)) {+ if ($line -notmatch '^TIMING (.*)$') { continue }+ try { $o = $Matches[1] | ConvertFrom-Json } catch { continue }+ $names = @($o.PSObject.Properties.Name)+ if ($names -contains 'phase') {+ $subs = [ordered]@{}+ foreach ($s in $o.subphases) {+ if ($subs.Contains($s.name)) { $subs[$s.name] += [double]$s.s } else { $subs[$s.name] = [double]$s.s }+ }+ $phase = @{ wall = [double]$o.wall_s; subs = $subs }+ } elseif ($names -contains 'zoom') {+ $zooms += [pscustomobject]@{+ zoom = [int]$o.zoom; tiles = [long]$o.tiles; features = [long]$o.features+ points = [long]$o.points; dropped = [long]$o.dropped; bytes = [long]$o.bytes+ map_ms = [long]$o.map_ms; merge_ms = [long]$o.merge_ms+ encode_ms = [long]$o.encode_ms; append_ms = [long]$o.append_ms+ }+ }+ }+ return @{ phase = $phase; zooms = $zooms }+}+ # Fixed inputs -- no file-location options. ALWAYS the planet: a california # build keeps only CA roads/POIs/buildings but renders borders, coastlines # and country names everywhere, so it needs the whole world as input.@@ -202,21 +294,25 @@ if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { # silently shrink a build someone asked for at full width. if ($Threads -gt 0) { $env:MAPS_THREADS = "$Threads" } else { Remove-Item Env:MAPS_THREADS -ErrorAction SilentlyContinue } Remove-Item Env:RAYON_NUM_THREADS -ErrorAction SilentlyContinue-Remove-Item Env:MAPS_TIMING -ErrorAction SilentlyContinue Remove-Item Env:MAPS_PREFETCH_LANES -ErrorAction SilentlyContinue # --- [1/7] build the host tools ------------------------------------------ # One crate builds all three PBF consumers now: road_graph, poi_extract and # mamaps_build share osm_ingest, one pool, and one blob scan via the graph's # sidecar. transit_shapes stays separate (it reads GTFS, not the PBF).+$null = Switch-Phase "tools" Write-Host "[1/7] Building the host tools ($Region)"+# PS1-owned subphases: no Rust timer covers cargo itself, so each crate build+# is one subphase named for the binary it produces. $crates = @(@("osm_ingest", "road_graph"), @("osm_ingest", "poi_extract"), @("mamaps_build", "mamaps_build")) if (-not $NoTransit) { $crates += ,@("gtfs_ingest", "transit_shapes") } foreach ($crate in $crates) {+ Switch-Subphase $crate[1] | Out-Null cargo build --release --manifest-path (Join-Path $PSScriptRoot "$($crate[0])\Cargo.toml") --bin $($crate[1]) if ($LASTEXITCODE -ne 0) { throw "cargo build $($crate[0])/$($crate[1]) failed with exit code $LASTEXITCODE" } } foreach ($bin in @("mamaps_dump", "mamaps_pack")) {+ Switch-Subphase $bin | Out-Null cargo build --release --manifest-path (Join-Path $PSScriptRoot "tile_build\Cargo.toml") --bin $bin if ($LASTEXITCODE -ne 0) { throw "cargo build tile_build/$bin failed with exit code $LASTEXITCODE" } }@@ -232,9 +328,13 @@ $pack = Find-Built "tile_build" "mamaps_pack" # touching the state bbox, so the traffic/junction layers and the pack agree # with the tiles. mamaps_build re-validates the dir before stage A — an empty # or stale graph used to cost 43 minutes of stage A before failing.+$null = Switch-Phase "graph" Write-Host "[2/7] Building the routing graph ($Region) -> $graphDir" # caonly/naonly pass world: the extract IS the region, so no bbox filtering.-& $roadGraph $Pbf --out $graphDir --region $BuildRegion+# Stdout is Tee'd to the phase log so the report can parse the TIMING line+# back out; bars stay live because Tee-Object does not redirect.+$graphLog = Join-Path $tmp "graph.log"+& $roadGraph $Pbf --out $graphDir --region $BuildRegion | Tee-Object -FilePath $graphLog if ($LASTEXITCODE -ne 0) { throw "road_graph failed with exit code $LASTEXITCODE" } # Fail HERE, not 43 minutes into stage A: the world build died on a missing # metadata.bin after paying the whole of stage A first.@@ -244,6 +344,8 @@ if (-not (Test-Path (Join-Path $graphDir "metadata.bin"))) { # --- [3/7] transit routes from the world-transit feeds -------------------- # -NoTransit skips every feed: an empty routes file, as if 0 feeds existed.+$null = Switch-Phase "transit"+$transitLog = Join-Path $tmp "transit.log" if ($NoTransit) { Write-Host "[3/7] NoTransit: skipping all GTFS feeds (empty transit-routes)" [System.IO.File]::WriteAllText($routes, "")@@ -276,7 +378,10 @@ $resolvedLines = foreach ($line in (Get-Content $TransitManifest)) { } if (-not $resolvedLines -or $resolvedLines.Count -eq 0) { throw "no usable feeds in $TransitManifest" } [System.IO.File]::WriteAllLines((Join-Path $tmp "feeds.resolved.manifest"), $resolvedLines)-& $shapes $routes --manifest (Join-Path $tmp "feeds.resolved.manifest")+# PS1-side subphase: manifest resolution above is orchestration, not tool+# work; the TIMING line below covers transit_shapes itself.+Switch-Subphase "resolve-manifest" | Out-Null+& $shapes $routes --manifest (Join-Path $tmp "feeds.resolved.manifest") | Tee-Object -FilePath $transitLog if ($LASTEXITCODE -ne 0) { throw "transit_shapes failed with exit code $LASTEXITCODE" } } @@ -284,6 +389,7 @@ if ($LASTEXITCODE -ne 0) { throw "transit_shapes failed with exit code $LASTEXIT # Started before the build, so the first spike cannot be missed. Under # MAPS_ANON_SPILL the feature spill has no file: the sampler then tracks only # the process high-water (commit charge is visible in the OS, not in a path).+$null = Switch-Phase "tiles" $spill = [System.IO.Path]::ChangeExtension($tilesTmp, "features.tmp") $sampler = Start-Job -ArgumentList "mamaps_build", $spill, $anon -ScriptBlock { param($name, $spill, $anon)@@ -306,7 +412,8 @@ Write-Host "[4/7] Building $(Split-Path $tilesTmp -Leaf) (tiles only) z0..z14$ Write-Host "" # Tee-Object keeps the bars live on the console AND captures stdout to the log, # which the summary below parses. No redirect: the bars need the console to redraw on.-$sw = [System.Diagnostics.Stopwatch]::StartNew()+# No Stopwatch here: the phase chain above already covers this step, from this+# boundary to the next Switch-Phase. (The old $sw made TOTAL WALL tiles-only.) & $build --input $Pbf --out $tilesTmp ` --coastline $Coastline ` --graph $graphDir `@@ -314,7 +421,6 @@ $sw = [System.Diagnostics.Stopwatch]::StartNew() --dem $Dem ` --region $BuildRegion | Tee-Object -FilePath $log $exit = $LASTEXITCODE-$sw.Stop() Start-Sleep -Milliseconds 400 $s = Receive-Job $sampler@@ -322,9 +428,14 @@ Stop-Job $sampler; Remove-Job $sampler -Force $peakWs = ($s | Measure-Object Ws -Maximum).Maximum $peakSpill = ($s | Measure-Object Spill -Maximum).Maximum +# Sampler teardown (job stop + 400 ms settle above) is booked to tiles so the+# POI clock starts exactly when [5/7] prints.+$null = Switch-Phase "poi" Write-Host "" if ($exit -ne 0) {- Write-Host ("FAILED, exit {0}, after {1:N1} s (temp kept at {2})" -f $exit, $sw.Elapsed.TotalSeconds, $tmp)+ Stop-Phases+ $failedSecs = $script:TotalSw.Elapsed.TotalSeconds+ Write-Host ("FAILED, exit {0}, after {1:N1} s (temp kept at {2})" -f $exit, $failedSecs, $tmp) exit $exit } @@ -336,22 +447,25 @@ if ($exit -ne 0) { # baked-vector feed and is not consumed by the pack, but poi_extract requires it. Write-Host "[5/7] Extracting POI sidecars ($Region) -> $poiDir" New-Item -ItemType Directory -Force -Path $poiDir | Out-Null+$poiLog = Join-Path $tmp "poi.log" & $poiExtract $Pbf ` --geojson (Join-Path $poiDir "poi.geojsonseq") ` --names (Join-Path $poiDir "poi_names.bin") ` --index (Join-Path $poiDir "poi_index.bin") `- --region $BuildRegion+ --region $BuildRegion | Tee-Object -FilePath $poiLog if ($LASTEXITCODE -ne 0) { throw "poi_extract failed with exit code $LASTEXITCODE" } # --- [6/7] pack the sidecars onto the tiles archive -> FINAL $Out ---------- # mamaps_build emits tiles only (no MAMA8 footer); the graph / transit / POI # sections the app's router, departure boards and POI tags need are appended # here. This is the step that turns a tiles-only archive into a complete pack.+$null = Switch-Phase "pack" Write-Host "[6/7] Packing graph + POI + transit sidecars -> $(Split-Path $Out -Leaf)"+$packLog = Join-Path $tmp "pack.log" if ($NoTransit) {- & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --out $Out+ & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --out $Out | Tee-Object -FilePath $packLog } else {- & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --transit $WorldTransit --out $Out+ & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --transit $WorldTransit --out $Out | Tee-Object -FilePath $packLog } if ($LASTEXITCODE -ne 0) { throw "mamaps_pack failed with exit code $LASTEXITCODE" } @@ -359,6 +473,9 @@ if ($LASTEXITCODE -ne 0) { throw "mamaps_pack failed with exit code $LASTEXITCOD # The binary prints its own per-zoom table (`z0 ...`, `z1 ...`) plus the # `classified ...` and `wrote ... build_id ...` lines. Parsed here rather than # re-derived.+$null = Switch-Phase "verify"+# PS1-owned subphases: header dump, hash, and (under -Verify) the rebuild.+Switch-Subphase "header" | Out-Null $logLines = Get-Content $log $zooms = @() foreach ($line in $logLines) {@@ -387,12 +504,14 @@ $prefix = [long]$h["prefix_bytes"] if ($prefix -gt 16384) { throw "prefix is $prefix bytes of 16384 -- a cold open costs two requests" } Write-Host "[7/7] Header ok: rings_validated true, prefix $prefix/16384 B, build_id $($h["build_id"])" +Switch-Subphase "hash" | Out-Null $sha = (Get-FileHash $Out -Algorithm SHA256).Hash if ($Verify) { # harden_mamaps.sh's full 1/3/32-thread matrix, folded in cheaply: one # single-threaded rebuild must be byte-identical. A differing hash means an # emit path whose order comes from a pool (e.g. a HashMap iterated on emit). Write-Host "Verifying determinism: rebuilding at 1 thread + repacking"+ Switch-Subphase "rebuild" | Out-Null $verifyTiles = Join-Path $tmp "verify-tiles.mamaps" $verifyOut = Join-Path $tmp "verify.mamaps" $env:RAYON_NUM_THREADS = "1"@@ -418,23 +537,61 @@ if ($Verify) { } $archive = (Get-Item $Out).Length-$map = ($zooms | Measure-Object map_ms -Sum).Sum-$mrg = ($zooms | Measure-Object merge_ms -Sum).Sum-$enc = ($zooms | Measure-Object encode_ms -Sum).Sum-$app = ($zooms | Measure-Object append_ms -Sum).Sum-$tiling = ($map + $mrg + $enc + $app) / 1000.0-$stageA = $sw.Elapsed.TotalSeconds - $tiling+# Stop the chain: this instant ends "verify" and freezes TOTAL WALL. From+# here on the report only reads $script:PhaseTimes -- no more timing.+Stop-Phases+$total = $script:TotalSw.Elapsed.TotalSeconds++# --- merge phase walls with Rust subphases --------------------------------+# $rustSubs["phase"] = [ordered]@{ sub = seconds } from the last TIMING line+# in each phase log. The `other` row per phase is PS1 wall minus the named+# subphases (clamped at zero): it absorbs spawn/pipe overhead and the+# microseconds of skew between the two clocks, so rows always sum to the wall.+$rustSubs = @{}+foreach ($pair in @(@("graph", $graphLog), @("transit", $transitLog), @("tiles", $log), @("poi", $poiLog), @("pack", $packLog))) {+ $parsed = Read-TimingLog $pair[1]+ if ($null -ne $parsed.phase) { $rustSubs[$pair[0]] = $parsed.phase.subs }+ if ($pair[0] -eq "tiles" -and $parsed.zooms.Count -gt 0) { $zooms = $parsed.zooms }+}+function Get-PhaseSubs([string] $phase) {+ # Merged view: Rust subphases in emission order, PS1-owned subphases+ # (tools builds, transit resolve-manifest, verify steps) in capture order,+ # then the closing `other` bucket. Every row sums to the phase wall.+ $merged = [ordered]@{}+ if ($rustSubs.Contains($phase)) {+ foreach ($k in $rustSubs[$phase].Keys) { $merged[$k] = $rustSubs[$phase][$k] }+ }+ foreach ($k in $script:SubTimes.Keys) {+ if ($k.StartsWith("$phase/")) {+ $sub = $k.Substring($phase.Length + 1)+ if ($merged.Contains($sub)) { $merged[$sub] += $script:SubTimes[$k] } else { $merged[$sub] = $script:SubTimes[$k] }+ }+ }+ $wall = $script:PhaseTimes[$phase]+ if ($null -eq $wall) { $wall = 0.0 }+ $named = 0.0+ foreach ($v in $merged.Values) { $named += $v }+ $merged["other"] = [Math]::Max(0.0, $wall - $named)+ return @{ wall = $wall; subs = $merged }+}+$phaseOrder = @("preflight", "tools", "graph", "transit", "tiles", "poi", "pack", "verify")+$phaseViews = [ordered]@{}+foreach ($name in $phaseOrder) { $phaseViews[$name] = Get-PhaseSubs $name }+ Write-Host "" Write-Host "======================== RESULT ========================" Write-Host "" Write-Host "TIME"-Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}% {3}" -f `- "stage A", $stageA, (100.0 * $stageA / $sw.Elapsed.TotalSeconds), "parse, resolve, materialise, spill")-foreach ($p in @(@("map (clip)", $map), @("merge", $mrg), @("encode", $enc), @("append", $app))) {- Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}%" -f `- $p[0], ($p[1] / 1000.0), (100.0 * $p[1] / 1000.0 / $sw.Elapsed.TotalSeconds))+foreach ($name in $phaseOrder) {+ $view = $phaseViews[$name]+ Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}%" -f $name, $view.wall, (100.0 * $view.wall / $total))+ foreach ($k in $view.subs.Keys) {+ $t = $view.subs[$k]+ if ($t -lt 0.05 -and $k -ne "other") { continue }+ Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}%" -f " $k", $t, (100.0 * $t / $total))+ } }-Write-Host (" {0,-24} {1,8:N1} s" -f "TOTAL WALL", $sw.Elapsed.TotalSeconds)+Write-Host (" {0,-24} {1,8:N1} s" -f "TOTAL WALL", $total) Write-Host "" Write-Host "PER ZOOM" Write-Host (" {0,-5}{1,12}{2,14}{3,16}{4,10}{5,9}{6,9}{7,9}" -f `@@ -457,6 +614,40 @@ Write-Host (" archive {0} {1}" -f (Size $archive), $Out) Write-Host (" build id {0,14}" -f $h["build_id"]) Write-Host (" sha256 {0}" -f $sha) +# timing.json beside the archive, before $tmp (and the phase logs) are+# deleted: the machine-readable twin of the TIME table above. Schema:+# { build_id, sha256, archive_bytes, total_wall_s, peak_rss_bytes,+# peak_spill_bytes, phases: [{ name, wall_s, subphases: [{name, s}] }],+# per_zoom: [{ zoom, tiles, features, points, dropped, bytes,+# map_s, merge_s, encode_s, append_s }] }.+$timingJson = [ordered]@{+ build_id = $h["build_id"]; sha256 = $sha; archive_bytes = $archive+ total_wall_s = [Math]::Round($total, 3)+ peak_rss_bytes = $peakWs; peak_spill_bytes = $peakSpill+ region = $Region+ phases = @()+ per_zoom = @()+}+foreach ($name in $phaseOrder) {+ $view = $phaseViews[$name]+ $subs = @()+ foreach ($k in $view.subs.Keys) {+ $subs += [ordered]@{ name = $k; s = [Math]::Round($view.subs[$k], 3) }+ }+ $timingJson.phases += [ordered]@{ name = $name; wall_s = [Math]::Round($view.wall, 3); subphases = $subs }+}+foreach ($z in ($zooms | Sort-Object zoom)) {+ $timingJson.per_zoom += [ordered]@{+ zoom = $z.zoom; tiles = $z.tiles; features = $z.features+ points = $z.points; dropped = $z.dropped; bytes = $z.bytes+ map_s = [Math]::Round($z.map_ms / 1000.0, 1); merge_s = [Math]::Round($z.merge_ms / 1000.0, 1)+ encode_s = [Math]::Round($z.encode_ms / 1000.0, 1); append_s = [Math]::Round($z.append_ms / 1000.0, 1)+ }+}+$timingPath = [System.IO.Path]::ChangeExtension($Out, "timing.json")+($timingJson | ConvertTo-Json -Depth 6).Replace("`r`n", "`n") | Set-Content -Path $timingPath -NoNewline+Write-Host (" timing {0}" -f $timingPath)+ # Temp is always removed on success now (no -Keep): the graph/POI/routes/tiles # intermediates are reproducible from the inputs, and anon spills vanish with # the process. A failed build keeps $tmp as evidence (see the FAILED branch).
scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rsindex a87d678c7a..0046388297 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs@@ -40,6 +40,7 @@ mod extra; use gtfs_ingest::bundle; use gtfs_ingest::gtfs::{self, Csv}; use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec};+use gtfs_ingest::timing::PhaseTimer; /// How many distinct services may draw over one stretch of track before the rest are dropped. ///@@ -87,15 +88,18 @@ fn main() -> ExitCode { } let out = PathBuf::from(&args[1]); + let mut timer = PhaseTimer::start("transit");+ timer.switch("manifest-resolve");+ let specs: Vec<FeedSpec> = if args[2] == "--manifest" { let Some(file) = args.get(3) else {- eprintln!("transit_shapes: --manifest requires a file path");+ eprintln!("ERROR: transit_shapes: --manifest requires a file path"); return ExitCode::from(2); }; match read_manifest(Path::new(file)) { Ok(v) => v, Err(e) => {- eprintln!("transit_shapes: {e}");+ eprintln!("ERROR: transit_shapes: {e}"); return ExitCode::FAILURE; } }@@ -104,15 +108,15 @@ fn main() -> ExitCode { }; if specs.is_empty() {- eprintln!("transit_shapes: no feeds given");+ eprintln!("ERROR: transit_shapes: no feeds given"); usage(); return ExitCode::from(2); } - match extra2::run(&out, &specs) {+ match extra2::run_with_timer(&out, &specs, Some(timer)) { Ok(()) => ExitCode::SUCCESS, Err(e) => {- eprintln!("transit_shapes: {e}");+ eprintln!("ERROR: transit_shapes: {e}"); ExitCode::FAILURE } }@@ -259,7 +263,7 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> { // Optional in GTFS, and a feed without it can still route — it just draws // nothing. Not an error, or one bus-only agency would fail a whole region. eprintln!(- "transit_shapes: warning: feed '{name}' has no usable shapes.txt, so it draws no lines"+ "WARN: transit_shapes: feed '{name}' has no usable shapes.txt, so it draws no lines" ); return Ok(FeedLines::default()); };@@ -368,7 +372,10 @@ fn shape_ids_by_route( /// becomes several out — the stretch before a corridor on its own geometry, the stretch /// inside it on the corridor's reference geometry at its lane, and a taper between. Returns /// how many pieces came out offset into a corridor.-fn expand_corridor_spans(lines: &mut Vec<Line>) -> usize {+fn expand_corridor_spans(+ lines: &mut Vec<Line>,+ timer: Option<&mut PhaseTimer>,+) -> usize { // A route is a route across every branch and short-turn it publishes, so all of // them take one lane. `BTreeMap` and first-seen ids, because a `HashMap`'s order // would decide the lanes and the output has to be byte-identical between runs.@@ -389,7 +396,7 @@ fn expand_corridor_spans(lines: &mut Vec<Line>) -> usize { name: &line.route, }) .collect();- bundle::assign(&candidates)+ bundle::assign_with_timer(&candidates, timer) }; let mut bundled = 0usize; let mut out: Vec<Line> = Vec::with_capacity(lines.len());
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rsindex bd46503ca0..9715a8c55a 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs@@ -3,8 +3,23 @@ use super::*; use rayon::prelude::*;+use std::time::Instant; +/// Untimed entry, kept for the unit tests in `transit_shapes_extra`.+#[cfg(test)] pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> {+ run_with_timer(out_path, specs, None)+}++/// Timed pipeline entry: ticks `parse-feeds` over the feed loop below, the+/// corridor stages inside [`expand_corridor_spans`], then `write-output` over+/// the sort and file write, and emits the `TIMING` line before the human+/// summary. `None` skips every tick, which is what the tests drive via [`run`].+pub(crate) fn run_with_timer(+ out_path: &Path,+ specs: &[FeedSpec],+ mut timer: Option<PhaseTimer>,+) -> Result<(), String> { let mut seen: HashSet<(u64, u32)> = HashSet::new(); let mut lines: Vec<Line> = Vec::new(); // Track already drawn, per colour and per mode. Two of one colour must never draw as@@ -34,6 +49,13 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { // Chunked rather than read-all-then-fold: a chunk of twice the pool keeps every core busy // while capping how many parsed feeds are alive at once, so peak memory follows the pool // size and not the number of feeds.+ //+ // ONE subphase for the whole feed loop below: thousands of feeds must not+ // produce thousands of entries. The sequential fold rides along inside it.+ if let Some(t) = timer.as_mut() {+ t.switch("parse-feeds");+ }+ let parse_start = Instant::now(); let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); let chunk_size = threads.saturating_mul(2).max(1); @@ -70,8 +92,7 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { shapes_read += feed.shapes_read; chunk_lines.extend(feed.lines); processed += 1;- eprint!("\rtransit_shapes: {processed}/{total} feed(s) parsed");- let _ = std::io::stderr().flush();+ print_feed_meter(processed, total, &parse_start); } // The dedup key is a content hash of the geometry, so it is order-independent and every@@ -142,7 +163,10 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { // to be cut for that lane to change. Once, over the whole set: neither the tiler nor // the renderer sees more than one tile, so deciding it there is what puts a jog in every // route at every tile seam.- let bundled = expand_corridor_spans(&mut lines);+ let bundled = expand_corridor_spans(&mut lines, timer.as_mut());+ if let Some(t) = timer.as_mut() {+ t.switch("write-output");+ } // Deterministic output, so a rebuild produces a byte-identical layer and the // tile diff is empty when nothing changed. Feed order already fixes which@@ -185,7 +209,12 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { } out.flush().map_err(io_err)?; - eprintln!(+ // TIMING before the human summary: stdout carries facts + TIMING only.+ if let Some(t) = timer {+ t.finish();+ }++ println!( "transit_shapes: wrote {} ({} feed(s), {kept} rail route(s) kept, \ {without_shape} with no usable shape, {shapes_read} shape(s) read, \ {deduped} republished byte-for-byte, {merged} already drawn in their colour, \@@ -198,3 +227,34 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { ); Ok(()) }++/// One stderr redraw of the feed-parse meter in the standard shape:+/// `\r{label:<28} [{pct:>3}%] {done}/{total} {elapsed} elapsed, ETA {eta}`.+fn print_feed_meter(done: usize, total: usize, start: &Instant) {+ let elapsed = start.elapsed().as_secs_f64();+ let pct = if total == 0 { 100 } else { (done * 100 / total.max(1)).min(100) };+ let eta = if done == 0 {+ "--".to_string()+ } else {+ fmt_dur(elapsed / done as f64 * (total - done) as f64)+ };+ eprint!(+ "\r{:<28} [{:>3}%] {done}/{total} {} elapsed, ETA {eta}",+ "Parse feeds",+ pct,+ fmt_dur(elapsed),+ );+ let _ = std::io::stderr().flush();+}++/// Short stable durations for the meter: `12s`, `2m05s`, `1h02m`.+fn fmt_dur(secs: f64) -> String {+ let s = secs.max(0.0).round() as u64;+ if s < 60 {+ format!("{s}s")+ } else if s < 3600 {+ format!("{}m{:02}s", s / 60, s % 60)+ } else {+ format!("{}h{:02}m", s / 3600, (s % 3600) / 60)+ }+}
scripts/maps/gtfs_ingest/src/bundle.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle.rs b/scripts/maps/gtfs_ingest/src/bundle.rsindex 8f9bf5a75c..a1a19d1f5b 100644--- a/scripts/maps/gtfs_ingest/src/bundle.rs+++ b/scripts/maps/gtfs_ingest/src/bundle.rs@@ -71,6 +71,7 @@ //! vector or a `BTreeMap`. use crate::shapes::{distance_m, project, resample};+use crate::timing::PhaseTimer; use rayon::prelude::*; use std::cmp::Ordering; use std::collections::BTreeMap;@@ -200,9 +201,24 @@ pub struct Span { /// Cut every candidate into spans and give each one its lane. One list out per candidate in, /// in the same order, never empty. pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> {+ assign_with_timer(candidates, None)+}++/// [`assign`], ticking the gapless timer through the corridor stages — one+/// switch per stage (`corridor-probe`, `corridor-spans`, `corridor-order`,+/// `corridor-cut`), never one entry per sample. `None` skips the ticks, which+/// is what [`assign`] and the unit tests drive.+pub fn assign_with_timer(+ candidates: &[Candidate],+ mut timer: Option<&mut PhaseTimer>,+) -> Vec<Vec<Span>> { if candidates.is_empty() { return Vec::new(); }+ // One switch per corridor stage, matching the four stderr meters below.+ // The timer ticks here on the orchestrating thread only; the worker+ // threads inside never touch it.+ tick(&mut timer, "corridor-probe"); let route_count = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0); let (samples, blocks) = sample_all(candidates); let grid = Grid::build(&samples);@@ -273,6 +289,8 @@ pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> { }); } eprintln!("\r{:<28} [100%] {} sample(s)", "Corridor probe", samples.len());+ // The runs cutting below is spans work, not probe work.+ tick(&mut timer, "corridor-spans"); // Back in sample order, then interned sequentially: first-seen order is what fixes the ids. let mut parts = parts.into_inner().expect("probe pool");@@ -328,6 +346,7 @@ pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> { // Named too: on a large set the work after the probe loop is still minutes, and without a // line here the run goes silent again the moment the bar reaches 100%. eprintln!("{:<28} {} candidate(s)", "Corridor spans", candidates.len());+ tick(&mut timer, "corridor-order"); let corridors = corridors_of(candidates, &sets, &runs, &named, &own_cum, &probe_cum); if std::env::var_os("TRANSIT_BUNDLE_DEBUG").is_some() {@@ -359,6 +378,8 @@ pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> { // long-distance rail all the work and left the rest idle: a world set sat at 98% on one // core for ten minutes with sixty-three threads finished. Sample probes are uniform enough // for a range split; candidates are not.+ // The cut below is its own stage: close the order subphase first.+ tick(&mut timer, "corridor-cut"); let total = candidates.len(); // Largest-first dispatch (longest-processing-time scheduling): hand out the heaviest // candidates first so the one transcontinental line overlaps with all the small work@@ -426,6 +447,17 @@ pub fn assign(candidates: &[Candidate]) -> Vec<Vec<Span>> { cut_parts.into_iter().map(|(_, spans)| spans).collect() } +/// One gapless tick, skipped when the caller passed `None`.+///+/// The timer lives on the orchestrating thread only, and every call site is+/// sequential code between the parallel loops, so worker threads never touch+/// it — the coarse loop/pass boundaries are the ticks.+fn tick(timer: &mut Option<&mut PhaseTimer>, name: &str) {+ if let Some(t) = timer {+ t.switch(name);+ }+}+ /// A maximal stretch of one candidate's samples holding the same membership, as inclusive /// indices into that candidate's own block of samples. struct Run {
scripts/maps/gtfs_ingest/src/lib.rs
diff --git a/scripts/maps/gtfs_ingest/src/lib.rs b/scripts/maps/gtfs_ingest/src/lib.rsindex ef0d57b6da..6f81a515e5 100644--- a/scripts/maps/gtfs_ingest/src/lib.rs+++ b/scripts/maps/gtfs_ingest/src/lib.rs@@ -22,3 +22,4 @@ pub mod reader; pub mod reader_extra; pub mod registry; pub mod shapes;+pub mod timing;
scripts/maps/gtfs_ingest/src/par.rs
diff --git a/scripts/maps/gtfs_ingest/src/par.rs b/scripts/maps/gtfs_ingest/src/par.rsindex 87c79ee6c4..dca27c2dc3 100644--- a/scripts/maps/gtfs_ingest/src/par.rs+++ b/scripts/maps/gtfs_ingest/src/par.rs@@ -62,7 +62,7 @@ fn env_threads(raw: Option<&str>) -> Option<usize> { Ok(n) if n > 0 => Some(n), _ => { WARNED.call_once(|| {- eprintln!("WARNING: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");+ eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)"); }); None }
scripts/maps/gtfs_ingest/src/timing.rs
diff --git a/scripts/maps/gtfs_ingest/src/timing.rs b/scripts/maps/gtfs_ingest/src/timing.rsnew file mode 100644index 0000000000..408b66a03e--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/timing.rs@@ -0,0 +1,154 @@+//! Gapless phase/subphase wall-clock timer for the maps pipeline.+//!+//! One `PhaseTimer` covers one tool run (which is one pipeline phase). Time is+//! booked by *switching*: `switch("next")` stops the current subphase and starts+//! the next one on the same instant, so subphases tile the phase wall with no+//! gaps and no overlaps — the stop of every subphase is the start of the next.+//! The summed subphases therefore equal the phase wall up to the microseconds+//! the switch itself costs.+//!+//! The timer starts in an implicit `"other"` subphase, which also absorbs any+//! stretch the caller never names. Callers name each major loop/pass and never+//! need to account for setup/teardown explicitly: whatever is left in `"other"`+//! at [`PhaseTimer::finish`] is the honest overhead bucket, not a fudge factor.+//!+//! Results leave the process as one parse-safe machine line on **stdout only**:+//!+//! ```text+//! TIMING {"phase":"tiles","wall_s":123.456,"subphases":[{"name":"stage-a","s":12.345}]}+//! ```+//!+//! Live progress meters stay on stderr (see `progress.rs`), warnings are+//! `WARN: ...` on stderr, errors `ERROR: ...` on stderr. Nothing else on stdout+//! may start with `TIMING `, and `TIMING` lines never go to stderr, so the+//! orchestrator can split the streams without ambiguity.+//!+//! Contract, kept identical in every crate that carries a copy of this file+//! (copies, not a shared crate: `gtfs_ingest` builds with zero dependencies,+//! and `par.rs` / `progress.rs` already follow the same copy convention):+//!+//! * std only, no dependencies.+//! * One timer per process, driven from the orchestrating (main) thread only.+//! Worker threads never touch it; coarse loop/pass boundaries are the ticks.+//! * `finish` merges repeat visits to the same subphase name (e.g. per-zoom+//! `map`/`merge`/`encode`/`append`) by summing, preserving first-seen order,+//! so fine-grained loops stay bounded instead of exploding the output.+//! * Durations print with millisecond precision (`{:.3}` seconds).+//! * Never one entry per feed / per tile / per feature: group those loops into+//! one bounded subphase (e.g. `parse-feeds`, `encode`), the way per-zoom work+//! folds into four totals here.++use std::time::Instant;++/// A single phase's gapless subphase chain. See the module docs.+pub struct PhaseTimer {+ phase: String,+ start: Instant,+ /// Name of the currently open subphase.+ current: String,+ /// When the currently open subphase started.+ current_start: Instant,+ /// Closed `(name, seconds)` segments, in close order.+ segments: Vec<(String, f64)>,+}++impl PhaseTimer {+ /// Start a phase clock. The clock opens in the `"other"` subphase, so any+ /// work before the first [`PhaseTimer::switch`] is booked as overhead.+ pub fn start(phase: &str) -> Self {+ let now = Instant::now();+ Self {+ phase: phase.to_string(),+ start: now,+ current: "other".to_string(),+ current_start: now,+ segments: Vec::new(),+ }+ }++ /// Close the current subphase and open `name`, on the same instant.+ /// Repeat visits to a name are merged (summed) at [`PhaseTimer::finish`].+ pub fn switch(&mut self, name: &str) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let old = std::mem::replace(&mut self.current, name.to_string());+ self.segments.push((old, secs));+ self.current_start = Instant::now();+ }++ /// Close the current subphase, merge repeats, and emit the `TIMING` line.+ /// Consumes the timer so a phase can only be reported once.+ pub fn finish(mut self) {+ self.close_current();+ let wall = self.start.elapsed().as_secs_f64();+ let mut merged: Vec<(String, f64)> = Vec::with_capacity(self.segments.len());+ for (name, secs) in &self.segments {+ match merged.iter_mut().find(|(n, _)| n == name) {+ Some(slot) => slot.1 += secs,+ None => merged.push((name.clone(), *secs)),+ }+ }+ let mut subs = String::new();+ for (i, (name, secs)) in merged.iter().enumerate() {+ if i > 0 {+ subs.push(',');+ }+ subs.push_str("{\"name\":\"");+ esc_json(name, &mut subs);+ subs.push_str(&format!("\",\"s\":{secs:.3}}}"));+ }+ let mut line = String::from("TIMING {\"phase\":\"");+ esc_json(&self.phase, &mut line);+ line.push_str(&format!("\",\"wall_s\":{wall:.3},\"subphases\":[{subs}]}}"));+ println!("{line}");+ }++ fn close_current(&mut self) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let name = std::mem::replace(&mut self.current, String::new());+ self.segments.push((name, secs));+ }+}++/// Append `s` to `out` with JSON string escaping.+fn esc_json(s: &str, out: &mut String) {+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if (c as u32) < 0x20 => {+ out.push_str(&format!("\\u{:04x}", c as u32));+ }+ c => out.push(c),+ }+ }+}++/// Emit one per-zoom machine line on stdout, next to (not instead of) the+/// human-readable `zN ...` table row. Integer milliseconds — unlike the+/// 0.1 s-rounded text row, these close the sum exactly.+///+/// `map_ms` / `merge_ms` / `encode_ms` / `append_ms` use the same meaning as+/// the text table: per-zoom worker time in each tiling step.+#[allow(clippy::too_many_arguments)]+pub fn emit_zoom_row(+ zoom: u8,+ tiles: u64,+ features: u64,+ points: u64,+ dropped: u64,+ bytes: u64,+ map_ms: u64,+ merge_ms: u64,+ encode_ms: u64,+ append_ms: u64,+) {+ println!(+ "TIMING {{\"zoom\":{zoom},\"tiles\":{tiles},\"features\":{features},\+ \"points\":{points},\"dropped\":{dropped},\"bytes\":{bytes},\+ \"map_ms\":{map_ms},\"merge_ms\":{merge_ms},\+ \"encode_ms\":{encode_ms},\"append_ms\":{append_ms}}}"+ );+}
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 d10ea64c20..fc1d85bd36 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -15,15 +15,12 @@ pub fn extract( graph: &Path, spill_path: &Path, region: Option<osm_ingest::bbox::BBox>,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<(Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>)> {- // Stage A's boundaries are printed with their elapsed time 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 printing them does.- let started = std::time::Instant::now();- let mark = |what: &str| {- println!(" [stage A] {what} at {:.1}s", started.elapsed().as_secs_f64());- };+ // 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();@@ -43,10 +40,8 @@ pub fn extract( // 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"); let graph_kinds = pbf::load_blob_kinds(graph, input, &blobs);- if graph_kinds.is_some() {- mark("blob kinds loaded from graph sidecar");- } if let Some(b) = region.as_ref() { println!( "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}",@@ -55,7 +50,9 @@ pub fn extract( } let ways_plan = plan_ways_spill(input, &blobs, &ways_path)?;- let pass1 = run_pass1(input, &blobs, graph_kinds.as_deref(), &select, layers, &ways_path, ways_plan, &mut stats, &mark)?;+ 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) ------------------------------------------ //@@ -66,6 +63,7 @@ pub fn extract( // 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@@ -88,6 +86,7 @@ pub fn extract( } = pass1; // The ways spill, shared by refcount with every reader below (collectors, // lanefill scan, materialise). Last use is `materialise_ways`; freed there.+ timer.switch("refs-collect"); let table = build_resolved_table( input, &blobs,@@ -102,12 +101,13 @@ pub fn extract( region.as_ref(), &mut sink, &mut stats,- &mark,+ 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 inherited_lanes = inherit_lane_counts( spill_path, &ways_path,@@ -117,14 +117,13 @@ pub fn extract( region.as_ref(), )?; stats.lanes_inherited = inherited_lanes.len() as u64;- mark("lane counts inherited"); // --- 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.- mark("materialising");+ timer.switch("materialise-ways"); materialise_ways( &ways_path, &ways_anon,@@ -142,7 +141,7 @@ pub fn extract( drop(ways_anon); drop(promoted); drop(inherited_lanes);- mark("ways spill freed");+ timer.switch("materialise-relations"); let conventions = materialise_relations( &relations, &members,@@ -171,7 +170,7 @@ pub fn extract( drop(relations); drop(members); drop(table);- mark("OSM tables freed");+ timer.switch("land-polygons"); let store = append_external_and_finish( coastline, transit_routes,@@ -180,7 +179,7 @@ pub fn extract( &mut stats, conventions, spill_path,- &mark,+ 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@@ -294,26 +293,9 @@ fn plan_feature_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) => {- println!(- " [stage A] budget: rank {} + ways spill {} + {} expected features x {} B => {:?} backend",- osm_ingest::mem::fmt_gb(budget.rank_bytes()),- osm_ingest::mem::fmt_gb(budget.ways_spill_bytes),- budget.features_expected,- budget.bytes_per_feature,- plan,- );- Ok(plan)- }+ Ok(plan) => Ok(plan), Err(e) => {- eprintln!("WARNING: {e}; continuing with file staging");- println!(- " [stage A] budget: rank {} + ways spill {} + {} expected features x {} B => File backend (over budget)",- osm_ingest::mem::fmt_gb(budget.rank_bytes()),- osm_ingest::mem::fmt_gb(budget.ways_spill_bytes),- budget.features_expected,- budget.bytes_per_feature,- );+ eprintln!("WARN: {e}; continuing with file staging"); Ok(osm_ingest::mem::SpillPlan::File) } }@@ -389,7 +371,7 @@ fn run_pass1( ways_path: &Path, spill_plan: osm_ingest::mem::SpillPlan, stats: &mut Stats,- mark: &dyn Fn(&str),+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Pass1Out> { // --- pass 1: ways and relations ------------------------------------------------------- //@@ -617,10 +599,10 @@ fn run_pass1( // a corridor into stubs at the zooms where only its motorway parts survive. Promote // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then // drop the segments: only the (way id, zoom) overrides are needed from here.+ timer.switch("corridors"); let promoted = crate::corridor::promote(&corridors); stats.corridor_promotions = promoted.len() as u64; drop(corridors);- mark("corridors promoted"); Ok(Pass1Out { relations,
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 3dd6715d8d..8217eb7a33 100644--- a/scripts/maps/mamaps_build/src/extract_part2.rs+++ b/scripts/maps/mamaps_build/src/extract_part2.rs@@ -157,7 +157,7 @@ fn build_resolved_table( region: Option<&osm_ingest::bbox::BBox>, sink: &mut Sink, stats: &mut Stats,- mark: &dyn Fn(&str),+ timer: &mut crate::timing::PhaseTimer, ) -> Result<NodeLocations> { // --- pass 3: the coordinates those two asked for, plus the label nodes ---------------- //@@ -170,11 +170,11 @@ fn build_resolved_table( .flat_map(|refs| refs.iter().copied()) .fold(way_max_ref, i64::max); let table = if refs_total <= REFS_IN_MEMORY {- collect_needed_in_memory(&ways_path, ways_anon, &members, refs_total, &mark)?+ collect_needed_in_memory(&ways_path, ways_anon, &members, refs_total, timer)? } else {- collect_needed_by_bitset(&ways_path, ways_anon, &members, max_ref, &mark)?+ collect_needed_by_bitset(&ways_path, ways_anon, &members, max_ref, timer)? };- mark("id index built, refs freed");+ timer.switch("coords-resolve"); stats.nodes_needed = table.len() as u64; // The node region is the bulk of a planet PBF, so it is inflated once: the coordinate resolve // and the label-node classification share this pass. `classify` runs in the block visitor across@@ -219,17 +219,6 @@ fn build_resolved_table( Ok(()) }; let table = resolve_nodes_with(input, &blobs, &blob_kinds, "Pass 3: nodes", table, classify, drain)?;- mark("coordinates resolved");- // The split, when asked for. Note what it does and does not separate: the first number is the- // protobuf decode of each block *plus* the id lookups inside it, because bracketing the lookups- // alone would need a clock read per node and there are billions. The second is the write, which- // is the half that is serialised behind `run_pass_sink`'s lock.- let (scan, write) = osm_ingest::nodeloc::resolve_seconds();- if scan + write > 0.0 {- println!(- " [stage A] node pass CPU: decode+lookup {scan:.1}s write {write:.1}s (serialised)",- );- } 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 fc9bd87987..d2ae35d172 100644--- a/scripts/maps/mamaps_build/src/extract_part3.rs+++ b/scripts/maps/mamaps_build/src/extract_part3.rs@@ -192,7 +192,7 @@ fn append_external_and_finish( stats: &mut Stats, conventions: schema::boundaries::Conventions, spill_path: &Path,- mark: &dyn Fn(&str),+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Store> { // 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@@ -214,6 +214,7 @@ fn append_external_and_finish( // The `transit` layer, for the same reason and against the same bounding box: its geometry is // GTFS rather than OSM (see [`schema::transit`]), so it is read here rather than classified in // any of the passes above.+ timer.switch("transit-routes"); match sink.bbox_degrees() { Some(bbox) => { println!(@@ -240,6 +241,7 @@ 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.+ 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.features += stats.junction_connectors;@@ -250,7 +252,8 @@ fn append_external_and_finish( // order is the archive's, so that write stays serial by construction — there is nothing here to // parallelise. The bar makes the finalise step visible rather than a silent tail of the ~25 s // this phase costs; `stats.features` is the count the sink is closing over.- let bar = Progress::new(+ timer.switch("finalise");+ let mut bar = Progress::new( "Finalise: features".to_string(), stats.features as usize, "feature(s)",@@ -259,10 +262,6 @@ fn append_external_and_finish( let store = sink.finish(spill_path)?; bar.finish("feature(s)"); let store = store.with_conventions(conventions);- // The one phase that had no mark after it, and it turned out to be the largest single item in the- // build outside tiling: ~25 s of a 136 s California run. It is 170 M coordinate lookups through- // the mapped node table plus 3.3 GB of spill written, all on one thread.- mark("materialised and spilled"); Ok(store) }@@ -293,7 +292,7 @@ fn collect_needed_in_memory( ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, members: &MemberWays, refs_total: usize,- mark: &dyn Fn(&str),+ timer: &mut crate::timing::PhaseTimer, ) -> Result<NodeLocations> { let mut needed: Vec<i64> = Vec::with_capacity(refs_total); {@@ -309,7 +308,7 @@ fn collect_needed_in_memory( for refs in members.values() { needed.extend_from_slice(refs); }- mark("refs collected");+ timer.switch("id-index"); NodeLocations::new(needed) } @@ -334,7 +333,7 @@ fn collect_needed_by_bitset( ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, members: &MemberWays, max_ref: i64,- mark: &dyn Fn(&str),+ timer: &mut crate::timing::PhaseTimer, ) -> Result<NodeLocations> { let mut bits = NeededBits::new(max_ref)?; {@@ -351,7 +350,7 @@ fn collect_needed_by_bitset( bits.set(id)?; } }- mark("refs collected");+ timer.switch("id-index"); // The bitset's words move into the rank index directly (`from_bitset`), not through `ids()`: // walking them out as ids and re-setting them would hold two ~1.5 GB words arrays at once. let (words, count) = bits.into_words();
scripts/maps/mamaps_build/src/extract_part4.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part4.rs b/scripts/maps/mamaps_build/src/extract_part4.rsindex 97402fab20..ccd0481226 100644--- a/scripts/maps/mamaps_build/src/extract_part4.rs+++ b/scripts/maps/mamaps_build/src/extract_part4.rs@@ -232,13 +232,15 @@ mod tests { .flat_map(|refs| refs.iter().copied()) .fold(counts.max_ref, i64::max); - let quiet = |_: &str| {};+ // A throwaway clock: the collectors take the run's timer, and this test has+ // no run. Dropped without `finish`, so no `TIMING` line reaches test output.+ let mut timer = crate::timing::PhaseTimer::start("tiles"); let anon = Some(std::sync::Arc::new(store)); let in_memory =- collect_needed_in_memory(&path, &anon, &members, counts.refs as usize + member_refs, &quiet)+ collect_needed_in_memory(&path, &anon, &members, counts.refs as usize + member_refs, &mut timer) .expect("the in-memory path"); let by_bitset =- collect_needed_by_bitset(&path, &anon, &members, max_ref, &quiet).expect("the bitset path");+ collect_needed_by_bitset(&path, &anon, &members, max_ref, &mut timer).expect("the bitset path"); assert_eq!( in_memory.len(),
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 6e8143026e..a834546797 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -51,6 +51,7 @@ mod schema; mod store; mod tiler; mod tilespill;+mod timing; /// The allocator, replaced because the default one was three quarters of the build. ///@@ -58,7 +59,7 @@ mod tilespill; /// encode pass was measured against the machine it runs on: **1358 s of worker CPU against 180 s of /// wall on a 32-core, 64-thread box** — a speed-up of 7.5 where the pool can give 64. Nothing in /// that pass is shared. [`rings::normalise`], `body::serialize_into` and DEFLATE each read one tile-/// and write one tile, there is no lock and no atomic in the path with `MAPS_TIMING` off, and the+/// and write one tile, there is no lock and no atomic in the path, and the /// memory traffic works out at a few hundred MB/s against eight channels of DDR5. The only thing /// all sixty-four threads still contend on is the heap. ///
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 33ac85e448..1aa8543278 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -5,7 +5,6 @@ fn run( ) -> Result<(), String> { let (layers, min_zoom, max_zoom, simplification) = (schema::Layers::all(), 0u8, DEFAULT_MAX_ZOOM, tiler::DEFAULT_SIMPLIFICATION);- let started = std::time::Instant::now(); println!("reading {}", input.display()); println!("region: {}", run.region.name()); // Features are spilled here rather than held: it was 4.9 GB of a measured 10.03 GB California@@ -55,6 +54,10 @@ fn run( // an empty graph dir with no `metadata.bin`, paid for in full. check_graph_dir(&graph_dir, run.region)?; + // 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+ // 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( input, layers,@@ -63,6 +66,7 @@ fn run( &graph_dir, &spill, run.region.bbox(),+ &mut timer, ) .map_err(|e| format!("{}: {e}", input.display()))?; // The containment fallback: member-less place labels gain links from the whole-polygon@@ -71,6 +75,7 @@ fn run( // It also assigns country label start zooms from footprint × headcount (same pass, // footprints in hand). let mut country_zooms: std::collections::HashMap<u64, u8> = std::collections::HashMap::new();+ timer.switch("region-fallback"); match crate::extract_fallback::extend_region_links_with( &store, &mut region_links,@@ -161,6 +166,7 @@ fn run( // The DEM heightmap dataset. Loaded here (this is where I/O belongs) and // handed to the tiler, which samples one grid per output tile into the body's heightmap section.+ timer.switch("dem-load"); let dem = dem::Dem::load(&run.dem).map_err(|e| e.to_string())?; println!("loaded the DEM dataset at {}", run.dem.display()); @@ -191,10 +197,12 @@ fn run( // holding it in a `Vec<u8>` beside the merge's own peak is the OOM after z14 merges. // `build_to_path` runs the identical zoom loop and assembles the identical // header/dictionary/root/leaves/data layout through `finish_to_path`.- let per_zoom = tiler::build_to_path(&store, &settings, out).map_err(|e| e.to_string())?;+ let per_zoom = tiler::build_to_path(&store, &settings, out, &mut timer).map_err(|e| e.to_string())?; tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?; // The spill is scratch. Removed on success; left behind on failure, where it is evidence. let _ = std::fs::remove_file(&spill);+ // After the last work, before the summary prints: closes the final subphase and emits `TIMING`.+ timer.finish(); println!( "\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8}{:>8}{:>8}{:>8}",@@ -215,6 +223,12 @@ fn run( z.encode_ms as f64 / 1000.0, z.append_ms as f64 / 1000.0, );+ // The machine-readable twin of the text row above: integer milliseconds, so the+ // columns close exactly where the 0.1 s-rounded text does not.+ crate::timing::emit_zoom_row(+ z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes, z.map_ms, z.merge_ms,+ z.encode_ms, z.append_ms,+ ); } // The four phase columns summed, because which of them dominates is the only thing that says // whether more cores would help: map and encode run on the pool, merge and append do not.@@ -242,7 +256,6 @@ fn run( lines.parts_before as f64 / lines.parts_after.max(1) as f64, ); }- let (stage_c, serialize, deflate) = tiler::encode_seconds(); // How close the archive came to the 65,535-feature cap on one tile-layer. Printed rather than // asserted because the answer is what decides whether the field has to widen, and widening it is // a `FORMAT_VERSION` bump and a matching renderer change.@@ -265,34 +278,21 @@ fn run( ); } println!(- "total map {:.1}s (of which {:.1}s deserialising the spill, on one thread) merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)",+ "total map {:.1}s merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)", map as f64 / 1000.0,- tiler::read_seconds(), merge as f64 / 1000.0, encode as f64 / 1000.0, append as f64 / 1000.0, serial / total * 100.0, );- // CPU, not wall, and summed across workers: compared against the encode wall above it says- // whether that phase is short of work or short of parallelism. Only under `MAPS_TIMING`,- // because three atomics per tile is not free at a million tiles.- if stage_c + serialize + deflate > 0.0 {- println!(- " encode CPU: stage C {stage_c:.1}s serialise {serialize:.1}s deflate {deflate:.1}s \- (={:.1}s of CPU against {:.1}s of wall)",- stage_c + serialize + deflate,- encode as f64 / 1000.0,- );- } // The archive was streamed straight to `out` (`build_to_path`), so its length is read // back from the file rather than from a buffer that no longer exists. let archive_len = std::fs::metadata(out) .map(|m| m.len()) .map_err(|e| format!("cannot stat {}: {e}", out.display()))?; println!(- "\nwrote {} ({archive_len} bytes, build_id {build_id:#018x}) in {:.1}s",+ "\nwrote {} ({archive_len} bytes, build_id {build_id:#018x})", out.display(),- started.elapsed().as_secs_f64(), ); Ok(()) }
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 fcfafc13a1..d6ebf129e4 100644--- a/scripts/maps/mamaps_build/src/store_part1.rs+++ b/scripts/maps/mamaps_build/src/store_part1.rs@@ -19,7 +19,7 @@ impl Sink { .map_err(|e| osm_ingest::proto::Error(e.to_string()))? } osm_ingest::mem::SpillPlan::File => {- println!(" [stage A] feature spill -> {} (file backend: commit budget)", path.display());+ eprintln!(" [stage A] feature spill -> {} (file backend: commit budget)", path.display()); NormalizedWriter::create(path) .map_err(|e| osm_ingest::proto::Error(e.to_string()))? }
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 1411fded35..a0da5f8041 100644--- a/scripts/maps/mamaps_build/src/store_part3.rs+++ b/scripts/maps/mamaps_build/src/store_part3.rs@@ -320,7 +320,7 @@ impl WaySink { WayOut::Anon(tile_build::anon::AnonStore::new()) } osm_ingest::mem::SpillPlan::File => {- println!(" [stage A] ways spill -> {} (file backend: commit budget)", path.display());+ eprintln!(" [stage A] ways spill -> {} (file backend: commit budget)", path.display()); let file = File::create(path) .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?; // A megabyte, because the writes are a few dozen bytes each and there are millions.
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 f5cf1d4fa8..423a96c183 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -7,7 +7,10 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> { adopt_thread_budget(); let mut writer = writer_for(store, settings)?;- let per_zoom = tile_zooms(store, settings, &mut writer)?;+ // Tests share the zoom loop but report no phase: the timer is dropped without `finish`,+ // so no `TIMING` line ever reaches test output.+ let mut timer = crate::timing::PhaseTimer::start("tiles");+ let per_zoom = tile_zooms(store, settings, &mut writer, &mut timer)?; let bytes = writer.finish()?; Ok((bytes, per_zoom)) }@@ -26,10 +29,11 @@ pub fn build_to_path( store: &Store, settings: &Settings, out: &std::path::Path,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Vec<ZoomStats>> { adopt_thread_budget(); let mut writer = writer_for(store, settings)?;- let per_zoom = tile_zooms(store, settings, &mut writer)?;+ let per_zoom = tile_zooms(store, settings, &mut writer, timer)?; writer.finish_to_path(out)?; Ok(per_zoom) }@@ -71,6 +75,7 @@ fn tile_zooms( store: &Store, settings: &Settings, writer: &mut StreamWriter,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Vec<ZoomStats>> { let mut per_zoom = Vec::new();@@ -86,7 +91,7 @@ fn tile_zooms( let chunk_plan = if settings.force_chunk_spill_file && chunk_plan == osm_ingest::mem::SpillPlan::Anon {- println!(+ eprintln!( " [tiler] chunk spill -> {} (file backend: MAPS_ANON_SPILL)", settings.scratch.display(), );@@ -105,6 +110,8 @@ fn tile_zooms( // pagefile-backed memory (no file) when commit allows, else the scratch file; the merge // reads through the same ChunkReader either way. let spill = ChunkSpill::create_planned(&settings.scratch, chunk_plan)?;+ // Per-zoom `map`: repeat visits merge into one total at `finish`.+ timer.switch("map"); let mapped = std::time::Instant::now(); let (chunks, tally) = map_zoom(store, settings, z, tolerance, buffer, &spill)?; stats.map_ms = mapped.elapsed().as_millis() as u64;@@ -121,7 +128,9 @@ fn tile_zooms( // the merge has produced it -- so the merge bar counts tiles merged and the encode line below // counts tiles written. Two numbers that converge at the end of the zoom. Still the difference // between forty silent minutes and a number that moves: the merge is single-threaded and is- // where a zoom's wall clock goes.+ // where a zoom's wall clock goes. Count shape (no percent: the total is unknowable until the+ // merge ends), with elapsed so a stalled merge is visible.+ let zoom_start = std::time::Instant::now(); let mut merged_tiles = 0usize; let mut merge_shown = 0usize; let mut written = 0usize;@@ -145,6 +154,8 @@ fn tile_zooms( // // The merge is timed around `collect` because that is where it happens: `merge` returns // a lazy iterator, so pulling a batch out of it is the k-way merge doing its work.+ // Per-zoom `merge`: repeat visits merge into one total at `finish`.+ timer.switch("merge"); let merging = std::time::Instant::now(); // `collect` into a `Result`, because a truncated scratch file must fail the build rather // than end the zoom early and publish a short archive.@@ -159,9 +170,15 @@ fn tile_zooms( merged_tiles += batch.len(); if merged_tiles - merge_shown >= 25_000 { merge_shown = merged_tiles;- eprint!("\r{:<28} [{merged_tiles:>10} tile(s)]", format!("Merge z{z}"));+ eprint!(+ "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ",+ format!("Merge z{z}"),+ tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),+ ); let _ = std::io::Write::flush(&mut std::io::stderr()); }+ // Per-zoom `encode`: repeat visits merge into one total at `finish`.+ timer.switch("encode"); let encoding = std::time::Instant::now(); let mut done = encode_batch(batch, &settings.dem, store.conventions(), &settings.region_links)?; stats.encode_ms += encoding.elapsed().as_millis() as u64;@@ -174,6 +191,8 @@ fn tile_zooms( // are present-and-empty in this batch — never across batch boundaries, so // the archive stays independent of batching and thread count. prune_barren_subtree(z, &mut done);+ // Per-zoom `append`: repeat visits merge into one total at `finish`.+ timer.switch("append"); let appending = std::time::Instant::now(); for (id, encoded, rings, lines) in done { stats.rings.add(rings);@@ -189,17 +208,29 @@ fn tile_zooms( // write itself is never the cost. if written - shown >= 25_000 { shown = written;- eprint!("\r{:<28} [{written:>10} tile(s)]", format!("Encode z{z}"));+ eprint!(+ "\r{:<28} [{written:>10} tile(s)] {} elapsed ",+ format!("Encode z{z}"),+ tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),+ ); let _ = std::io::Write::flush(&mut std::io::stderr()); } } stats.append_ms += appending.elapsed().as_millis() as u64; } if merged_tiles > 0 {- eprintln!("\r{:<28} [{merged_tiles:>10} tile(s)]", format!("Merge z{z}"));+ eprintln!(+ "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ",+ format!("Merge z{z}"),+ tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),+ ); } if written > 0 {- eprintln!("\r{:<28} [{written:>10} tile(s)]", format!("Encode z{z}"));+ eprintln!(+ "\r{:<28} [{written:>10} tile(s)] {} elapsed ",+ format!("Encode z{z}"),+ tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()),+ ); } // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries // would produce an archive with holes in it and nothing downstream could tell.@@ -349,7 +380,7 @@ fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem match osm_ingest::mem::SpillPlan::decide(&budget, scratch, "tiler chunk spill") { Ok(plan) => { if plan != osm_ingest::mem::SpillPlan::Anon {- println!(+ eprintln!( " [tiler] chunk spill -> {} (file backend: commit budget)", scratch.display(), );@@ -360,7 +391,7 @@ fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem // A zoom that fits neither backend is not a hard failure here: later zooms are // smaller, and each zoom re-creates the spill. Warn and take files -- the operator // sees the message and the build still has a chance.- eprintln!("WARNING: {e}; continuing with file staging");+ eprintln!("WARN: {e}; continuing with file staging"); osm_ingest::mem::SpillPlan::File } }@@ -422,7 +453,7 @@ fn map_zoom( match worker { Ok(handle) => spawned.push(handle), Err(e) => {- eprintln!("WARNING: cannot start tiling thread {i} ({e}); continuing without");+ eprintln!("WARN: cannot start tiling thread {i} ({e}); continuing without"); break; } }@@ -466,19 +497,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.-/// Nanoseconds spent deserialising the spill, summed across every zoom.-///-/// Measured because `map_ms` covers the whole of [`map_zoom`], reader included, so it reports the-/// single-threaded reader as though it were parallel work. This is the number that says how much of-/// the map phase cannot be spread over the pool: time inside `reader.next()` alone, excluding any-/// blocking on the bounded channel, which is the workers being slow rather than the reader being the-/// bottleneck.-static READ_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);--/// Take the accumulated reader time and reset it.-pub fn read_seconds() -> f64 {- READ_NANOS.swap(0, Ordering::Relaxed) as f64 / 1e9-} #[cfg(test)] mod tests_part1 {
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 e71ac9da03..ad8ca4339d 100644--- a/scripts/maps/mamaps_build/src/tiler_part2.rs+++ b/scripts/maps/mamaps_build/src/tiler_part2.rs@@ -19,14 +19,11 @@ fn read_chunks( let mut chunk: Vec<Feature> = Vec::new(); let mut vertices = 0usize; let mut index = 0usize;- let mut read_nanos = 0u64; let (_, total) = reader.chunks(); let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true); let mut ticked = 0usize; loop {- let at = std::time::Instant::now(); let next = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))?;- read_nanos += at.elapsed().as_nanos() as u64; let (done, _) = reader.chunks(); while ticked < done { bar.tick("chunk(s)");@@ -37,7 +34,6 @@ fn read_chunks( chunk.push(feature); if vertices >= want { if send.send((index, std::mem::take(&mut chunk))).is_err() {- READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed); return Ok(()); } index += 1;@@ -48,7 +44,6 @@ fn read_chunks( let _ = send.send((index, chunk)); } bar.finish("chunk(s)");- READ_NANOS.fetch_add(read_nanos, Ordering::Relaxed); return Ok(()); } // Bounded k-way merge: 4 dedicated decode lanes stream per-feature in@@ -169,7 +164,6 @@ fn read_chunks( break; } }- let start = std::time::Instant::now(); let mut lane_done = vec![false; lanes]; let mut lane_buffers: Vec<std::collections::VecDeque<Feature>> = (0..lanes).map(|_| std::collections::VecDeque::new()).collect();@@ -201,7 +195,6 @@ fn read_chunks( tiler_chunk.push(feature); if vertices >= want { if send.send((index, std::mem::take(&mut tiler_chunk))).is_err() {- READ_NANOS.fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed); // Unblock lanes by draining for (li, done) in lane_done.iter().enumerate() { if !*done {@@ -231,7 +224,6 @@ fn read_chunks( let _ = send.send((index, tiler_chunk)); } bar.finish("chunk(s)");- READ_NANOS.fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed); if let Some(e) = first_err.lock().unwrap().take() { // Surface decode errors after draining so downstream sees failure rather than short archive. // Error already logged; return Err to fail this zoom rather than publish short archive.
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 eb8da09ab8..7943efbe2f 100644--- a/scripts/maps/mamaps_build/src/tiler_part3.rs+++ b/scripts/maps/mamaps_build/src/tiler_part3.rs@@ -198,40 +198,9 @@ fn remap_names(into_names: &mut Vec<String>, from: &ChunkEntry) -> Vec<u16> { /// ~900 MB through one core while sixty-three sat idle. That is why a 64-thread build was *slower* /// than the sequential one it replaced. ///-/// Returns the raw length alongside the compressed frame, because the per-zoom `bytes` column has+/// 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.-/// Where the encode pass's CPU actually goes, accumulated across workers.-///-/// Nanoseconds, summed per tile. Split three ways because the three steps have nothing to do with-/// each other and the totals cannot say which is which: stage C is geometry with a quadratic-/// hole-versus-hole test in it, serialisation is a memcpy, and DEFLATE at level nine is a-/// throughput-bound compressor. This exists for the same reason-/// [`tile_build::pyramid`]'s `MVT_NANOS` and `GZIP_NANOS` do -- four rounds of plausible-sounding-/// optimisation there bought 3% between them, and splitting the measurement is what found the real-/// cost. Here it found a `clone` of every tile's coordinate arena.-///-/// **Off unless `MAPS_TIMING` is set**, and that is not tidiness. `pyramid`'s counters are hit once-/// per gzip probe, a handful per tile; these are hit three times per tile, and at 943,401 tiles-/// across 64 workers three contended atomics per tile is itself a scalability problem. Leaving them-/// always-on would mean the instrument changed what it measured.-static STAGE_C_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);-static SERIALIZE_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);-static DEFLATE_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);--/// Whether to time the encode split at all. Read once; an `Instant::now()` pair and an atomic per-/// step per tile is not free at this tile count.-fn timing() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var_os("MAPS_TIMING").is_some())-}--/// The encode split in seconds of CPU: `(stage C, serialise, deflate)`. All zero without-/// `MAPS_TIMING`.-pub fn encode_seconds() -> (f64, f64, f64) {- let s = |c: &std::sync::atomic::AtomicU64| c.load(Ordering::Relaxed) as f64 / 1e9;- (s(&STAGE_C_NANOS), s(&SERIALIZE_NANOS), s(&DEFLATE_NANOS))-} /// The most features any one tile has carried in each layer. ///@@ -261,18 +230,6 @@ pub fn widest_layers() -> Vec<(u8, u64)> { .collect() } -/// Time `f` into `counter`, or just run it when timing is off.-#[inline]-fn timed<R>(on: bool, counter: &std::sync::atomic::AtomicU64, f: impl FnOnce() -> R) -> R {- if !on {- return f();- }- let at = std::time::Instant::now();- let out = f();- counter.fetch_add(at.elapsed().as_nanos() as u64, Ordering::Relaxed);- out-}- /// One encoded tile on its way back from [`encode_batch`]: its id, the compressed body with its raw /// length and its FNV-1a dedup hash, and what stage C and coalescing did to it. ///
scripts/maps/mamaps_build/src/tiler_part5.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part5.rs b/scripts/maps/mamaps_build/src/tiler_part5.rsindex 64c98eb454..625964cbc8 100644--- a/scripts/maps/mamaps_build/src/tiler_part5.rs+++ b/scripts/maps/mamaps_build/src/tiler_part5.rs@@ -4,7 +4,6 @@ fn encode_batch( conventions: &crate::schema::boundaries::Conventions, region_links: &std::collections::HashMap<u64, u64>, ) -> Result<Vec<Encoded>> {- let on = timing(); // Split the batch into tasks by cumulative geometry cost rather than by tile count. A dense // city tile is orders of magnitude more work than a rural one, and `with_min_len` — which forces // contiguous runs of a fixed *count* — cannot give that tile a task of its own: it stays welded@@ -30,7 +29,7 @@ fn encode_batch( group .into_iter() .map(|(id, layers)| {- encode_tile(id, layers, dem, conventions, region_links, deflate, scratch, on)+ encode_tile(id, layers, dem, conventions, region_links, deflate, scratch) }) .collect::<Result<Vec<Encoded>>>() },@@ -56,7 +55,6 @@ fn encode_tile( region_links: &std::collections::HashMap<u64, u64>, deflate: &mut tilecodec::gz::Compressor, scratch: &mut tilecodec::mamaps::body::Scratch,- on: bool, ) -> Result<Encoded> { // **Coalesce first.** An OSM way is an editing unit, not a rendering one, so a road arrives as // hundreds of two-point fragments each carrying its own 28 bytes of header -- see@@ -90,20 +88,18 @@ fn encode_tile( // dropped. Once, here, in `f64` with no frame budget, instead of every frame on device in `i32` // under one. This is what makes `FLAG_RINGS_VALIDATED` true. let mut rings = crate::rings::Stats::default();- timed(on, &STAGE_C_NANOS, || {- for entry in &mut layers {- rings.add(crate::rings::normalise_with_ids(- &mut entry.layer,- Some(&mut entry.ids),- Some(&mut entry.turn_lanes),- Some(&mut entry.buildings),- ));- }- // A layer that ended up empty - every feature in it fell below the minimum area after- // clipping, or lost its exterior to stage C - costs bytes in the archive and a draw call on- // device for nothing.- layers.retain(|entry| !entry.layer.features.is_empty());- });+ for entry in &mut layers {+ rings.add(crate::rings::normalise_with_ids(+ &mut entry.layer,+ Some(&mut entry.ids),+ Some(&mut entry.turn_lanes),+ Some(&mut entry.buildings),+ ));+ }+ // A layer that ended up empty - every feature in it fell below the minimum area after+ // clipping, or lost its exterior to stage C - costs bytes in the archive and a draw call on+ // device for nothing.+ layers.retain(|entry| !entry.layer.features.is_empty()); if layers.is_empty() { return Ok((id, None, rings, lines)); }@@ -293,21 +289,17 @@ fn encode_tile( convention, region_links: region_links_table, };- let encoded_body = timed(on, &SERIALIZE_NANOS, || {- // v10 narrowed records + sparse side tables are the default: same- // geometry either way — only the fixed records shrink — so this- // changes bytes, never shapes. `MAMAPS_V8=1` opts back out to the- // dense v8 bodies (escape hatch for bisecting a suspect build).- if std::env::var("MAMAPS_V8").is_ok() {- tilecodec::mamaps::body::serialize_into(&body, scratch)- } else {- tilecodec::mamaps::body::serialize_into_v10(&body, scratch)- }- })?;+ // v10 narrowed records + sparse side tables are the default: same+ // geometry either way — only the fixed records shrink — so this+ // changes bytes, never shapes. `MAMAPS_V8=1` opts back out to the+ // dense v8 bodies (escape hatch for bisecting a suspect build).+ let encoded_body = if std::env::var("MAMAPS_V8").is_ok() {+ tilecodec::mamaps::body::serialize_into(&body, scratch)+ } else {+ tilecodec::mamaps::body::serialize_into_v10(&body, scratch)+ }?; let raw_len = encoded_body.len();- let stored = timed(on, &DEFLATE_NANOS, || {- tilecodec::mamaps::write::compress_body_with(deflate, encoded_body)- });+ let stored = tilecodec::mamaps::write::compress_body_with(deflate, encoded_body); // Compute the dedup key here, in the parallel worker, rather than on the serial append thread. // It is a pure function of the stored bytes, so the key — and every dedup decision the writer // makes from it — is unchanged; it just no longer walks the whole body downstream of this phase.
scripts/maps/mamaps_build/src/timing.rs
diff --git a/scripts/maps/mamaps_build/src/timing.rs b/scripts/maps/mamaps_build/src/timing.rsnew file mode 100644index 0000000000..408b66a03e--- /dev/null+++ b/scripts/maps/mamaps_build/src/timing.rs@@ -0,0 +1,154 @@+//! Gapless phase/subphase wall-clock timer for the maps pipeline.+//!+//! One `PhaseTimer` covers one tool run (which is one pipeline phase). Time is+//! booked by *switching*: `switch("next")` stops the current subphase and starts+//! the next one on the same instant, so subphases tile the phase wall with no+//! gaps and no overlaps — the stop of every subphase is the start of the next.+//! The summed subphases therefore equal the phase wall up to the microseconds+//! the switch itself costs.+//!+//! The timer starts in an implicit `"other"` subphase, which also absorbs any+//! stretch the caller never names. Callers name each major loop/pass and never+//! need to account for setup/teardown explicitly: whatever is left in `"other"`+//! at [`PhaseTimer::finish`] is the honest overhead bucket, not a fudge factor.+//!+//! Results leave the process as one parse-safe machine line on **stdout only**:+//!+//! ```text+//! TIMING {"phase":"tiles","wall_s":123.456,"subphases":[{"name":"stage-a","s":12.345}]}+//! ```+//!+//! Live progress meters stay on stderr (see `progress.rs`), warnings are+//! `WARN: ...` on stderr, errors `ERROR: ...` on stderr. Nothing else on stdout+//! may start with `TIMING `, and `TIMING` lines never go to stderr, so the+//! orchestrator can split the streams without ambiguity.+//!+//! Contract, kept identical in every crate that carries a copy of this file+//! (copies, not a shared crate: `gtfs_ingest` builds with zero dependencies,+//! and `par.rs` / `progress.rs` already follow the same copy convention):+//!+//! * std only, no dependencies.+//! * One timer per process, driven from the orchestrating (main) thread only.+//! Worker threads never touch it; coarse loop/pass boundaries are the ticks.+//! * `finish` merges repeat visits to the same subphase name (e.g. per-zoom+//! `map`/`merge`/`encode`/`append`) by summing, preserving first-seen order,+//! so fine-grained loops stay bounded instead of exploding the output.+//! * Durations print with millisecond precision (`{:.3}` seconds).+//! * Never one entry per feed / per tile / per feature: group those loops into+//! one bounded subphase (e.g. `parse-feeds`, `encode`), the way per-zoom work+//! folds into four totals here.++use std::time::Instant;++/// A single phase's gapless subphase chain. See the module docs.+pub struct PhaseTimer {+ phase: String,+ start: Instant,+ /// Name of the currently open subphase.+ current: String,+ /// When the currently open subphase started.+ current_start: Instant,+ /// Closed `(name, seconds)` segments, in close order.+ segments: Vec<(String, f64)>,+}++impl PhaseTimer {+ /// Start a phase clock. The clock opens in the `"other"` subphase, so any+ /// work before the first [`PhaseTimer::switch`] is booked as overhead.+ pub fn start(phase: &str) -> Self {+ let now = Instant::now();+ Self {+ phase: phase.to_string(),+ start: now,+ current: "other".to_string(),+ current_start: now,+ segments: Vec::new(),+ }+ }++ /// Close the current subphase and open `name`, on the same instant.+ /// Repeat visits to a name are merged (summed) at [`PhaseTimer::finish`].+ pub fn switch(&mut self, name: &str) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let old = std::mem::replace(&mut self.current, name.to_string());+ self.segments.push((old, secs));+ self.current_start = Instant::now();+ }++ /// Close the current subphase, merge repeats, and emit the `TIMING` line.+ /// Consumes the timer so a phase can only be reported once.+ pub fn finish(mut self) {+ self.close_current();+ let wall = self.start.elapsed().as_secs_f64();+ let mut merged: Vec<(String, f64)> = Vec::with_capacity(self.segments.len());+ for (name, secs) in &self.segments {+ match merged.iter_mut().find(|(n, _)| n == name) {+ Some(slot) => slot.1 += secs,+ None => merged.push((name.clone(), *secs)),+ }+ }+ let mut subs = String::new();+ for (i, (name, secs)) in merged.iter().enumerate() {+ if i > 0 {+ subs.push(',');+ }+ subs.push_str("{\"name\":\"");+ esc_json(name, &mut subs);+ subs.push_str(&format!("\",\"s\":{secs:.3}}}"));+ }+ let mut line = String::from("TIMING {\"phase\":\"");+ esc_json(&self.phase, &mut line);+ line.push_str(&format!("\",\"wall_s\":{wall:.3},\"subphases\":[{subs}]}}"));+ println!("{line}");+ }++ fn close_current(&mut self) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let name = std::mem::replace(&mut self.current, String::new());+ self.segments.push((name, secs));+ }+}++/// Append `s` to `out` with JSON string escaping.+fn esc_json(s: &str, out: &mut String) {+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if (c as u32) < 0x20 => {+ out.push_str(&format!("\\u{:04x}", c as u32));+ }+ c => out.push(c),+ }+ }+}++/// Emit one per-zoom machine line on stdout, next to (not instead of) the+/// human-readable `zN ...` table row. Integer milliseconds — unlike the+/// 0.1 s-rounded text row, these close the sum exactly.+///+/// `map_ms` / `merge_ms` / `encode_ms` / `append_ms` use the same meaning as+/// the text table: per-zoom worker time in each tiling step.+#[allow(clippy::too_many_arguments)]+pub fn emit_zoom_row(+ zoom: u8,+ tiles: u64,+ features: u64,+ points: u64,+ dropped: u64,+ bytes: u64,+ map_ms: u64,+ merge_ms: u64,+ encode_ms: u64,+ append_ms: u64,+) {+ println!(+ "TIMING {{\"zoom\":{zoom},\"tiles\":{tiles},\"features\":{features},\+ \"points\":{points},\"dropped\":{dropped},\"bytes\":{bytes},\+ \"map_ms\":{map_ms},\"merge_ms\":{merge_ms},\+ \"encode_ms\":{encode_ms},\"append_ms\":{append_ms}}}"+ );+}
scripts/maps/osm_ingest/src/bin/osm_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/osm_extract.rs b/scripts/maps/osm_ingest/src/bin/osm_extract.rsindex a4c361f046..f0e6ca1a5f 100644--- a/scripts/maps/osm_ingest/src/bin/osm_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/osm_extract.rs@@ -15,7 +15,7 @@ fn main() -> ExitCode { let args = match osm_ingest::extract::parse_args(&argv) { Ok(v) => v, Err(e) => {- eprintln!("error: {e}\n{USAGE}");+ eprintln!("ERROR: {e}\n{USAGE}"); eprintln!( "Layers: {}", osm_ingest::extract::Layer::names().join(", ")@@ -50,16 +50,16 @@ fn main() -> ExitCode { // empty layer is nearly always a wrong --bbox or a wrong PBF, and // the tiler downstream only warns about it. eprintln!(- "WARNING: 0 features. Check --bbox and that the PBF covers the area."+ "WARN: 0 features. Check --bbox and that the PBF covers the area." ); } if let Some(why) = stats.missing_half(args.layer) {- eprintln!("WARNING: {}: {why}", args.layer.name());+ eprintln!("WARN: {}: {why}", args.layer.name()); } ExitCode::SUCCESS } Err(e) => {- eprintln!("error: {e}");+ eprintln!("ERROR: {e}"); ExitCode::FAILURE } }
scripts/maps/osm_ingest/src/bin/poi_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/poi_extract.rs b/scripts/maps/osm_ingest/src/bin/poi_extract.rsindex 3fb052d15e..e37fd8841d 100644--- a/scripts/maps/osm_ingest/src/bin/poi_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -13,7 +13,7 @@ fn main() -> ExitCode { let args = match osm_ingest::poi_build::parse_args(&argv) { Ok(v) => v, Err(e) => {- eprintln!("error: {e}\n{USAGE}");+ eprintln!("ERROR: {e}\n{USAGE}"); return ExitCode::FAILURE; } };@@ -22,7 +22,6 @@ fn main() -> ExitCode { osm_ingest::par::set_threads(n); } - let started = std::time::Instant::now(); match osm_ingest::poi_build::build_with( &args.input, &args.geojson,@@ -36,14 +35,13 @@ fn main() -> ExitCode { Ok(stats) => { println!( "{} POI(s) ({} node, {} closed-way, {} relation), {} unique name(s) \- ({} bytes) in {:.1}s",+ ({} bytes)", stats.records, stats.from_nodes, stats.from_ways, stats.from_relations, stats.unique_names, stats.name_bytes,- started.elapsed().as_secs_f64() ); println!( "{} POI(s) with attributes, {} unique record(s), {} sidecar byte(s)",@@ -65,7 +63,7 @@ fn main() -> ExitCode { ExitCode::SUCCESS } Err(e) => {- eprintln!("error: {e}");+ eprintln!("ERROR: {e}"); ExitCode::FAILURE } }
scripts/maps/osm_ingest/src/bin/road_graph.rs
diff --git a/scripts/maps/osm_ingest/src/bin/road_graph.rs b/scripts/maps/osm_ingest/src/bin/road_graph.rsindex fe025685f0..130b3291e9 100644--- a/scripts/maps/osm_ingest/src/bin/road_graph.rs+++ b/scripts/maps/osm_ingest/src/bin/road_graph.rs@@ -89,24 +89,22 @@ fn main() -> ExitCode { let (input, out_dir, opts) = match osm_ingest::graph_build::parse_args(&args) { Ok(v) => v, Err(e) => {- eprintln!("error: {e}\n{USAGE}");+ eprintln!("ERROR: {e}\n{USAGE}"); return ExitCode::FAILURE; } }; - let started = std::time::Instant::now(); let want_stats = opts.stats; match osm_ingest::graph_build::build_with(&input, &out_dir, opts) { Ok(stats) => { println!( "{} node(s), {} edge(s), {} unique name(s) ({} bytes), largest component \- {} node(s) in {:.1}s",+ {} node(s)", stats.node_count, stats.edge_count, stats.unique_names, stats.name_bytes, stats.lcc_size,- started.elapsed().as_secs_f64() ); // The three counters that make MIN_ROUTABLE_COMPONENT auditable. A // large "found nothing" is the signal that the threshold is too high.@@ -148,7 +146,7 @@ fn main() -> ExitCode { ExitCode::SUCCESS } Err(e) => {- eprintln!("error: {e}");+ eprintln!("ERROR: {e}"); ExitCode::FAILURE } }
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsindex fd03768d32..96e63606ef 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -134,7 +134,7 @@ pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> { } let blobs = pbf::scan_blobs(input)?;- println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());+ println!("[extract] Scanned {} data blob(s) in {}", blobs.len(), input.display()); match opts.layer { Layer::Safety => build_safety(input, &blobs, out, opts),
scripts/maps/osm_ingest/src/graph_build_part1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part1.rs b/scripts/maps/osm_ingest/src/graph_build_part1.rsindex 409b773bbb..3c1f1b26a8 100644--- a/scripts/maps/osm_ingest/src/graph_build_part1.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part1.rs@@ -118,8 +118,9 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> std::fs::create_dir_all(out_dir) .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?; + let mut timer = crate::timing::PhaseTimer::start("graph"); let blobs = pbf::scan_blobs(input)?;- println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());+ println!("[graph] Scanned {} data blob(s) in {}", blobs.len(), input.display()); pbf::probe_compression(input, &blobs)?; let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));@@ -128,6 +129,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> let mut marked: u64 = 0; let mut max_id: u64 = 0; + timer.switch("refs-stops"); // --- Pass 1: which nodes the graph needs --------------------------------- // Folded through a sink rather than collected, so a chunk's ref list is // consumed and freed while later chunks are still decoding. Nothing about a@@ -169,7 +171,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // mask is complete. Best-effort: a write failure must not fail the graph build, which never // reads the sidecar itself. if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blob_kinds) {- eprintln!("warning: could not write blob-kinds sidecar: {e}");+ eprintln!("WARN: could not write blob-kinds sidecar: {e}"); } let slots = cap_u32("marked graph node", marked)?; @@ -177,6 +179,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // From here on a node's address is the number of marked ids below its own, so // the node array is implicitly ordered by OSM id and needs to store neither // the id nor a sorted side table to look it up by.+ timer.switch("rank-index"); let counted = mask.build_rank(max_id); if counted != marked { // The mask and the running count are maintained in the same loop, so a@@ -195,6 +198,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> let mut stop = Bitset::new(u64::from(slots)); let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new(); let mut node_count: u64 = 0;+ timer.switch("node-scan"); let _ = pbf::run_pass_sink( input, &blobs,@@ -230,15 +234,16 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // --- Collapse ------------------------------------------------------------ let spill_dir = opts.spill_dir.clone().unwrap_or_else(|| out_dir.to_path_buf()); let spill_pts_dir = opts.spill_pts_dir.clone().unwrap_or_else(|| spill_dir.clone());+ timer.switch("collapse"); let mut collapsed = if opts.within_way_chains { collapse_within_ways( input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,- slots, filter, &mut pool,+ slots, filter, &mut pool, &mut timer, )? } else { collapse_segments( input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,- slots, filter, &mut pool,+ slots, filter, &mut pool, &mut timer, )? }; @@ -249,6 +254,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> } prog.finish(); drop(stop_codes);+ timer.switch("rank-survivors"); // `saturating_sub` because a file with no routable ways and no stop nodes // marks nothing, and there is then no largest id to index up to.@@ -270,6 +276,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // only set the device ever binary-searches. Sorting before the collapse would // have meant carrying a 64-bit spatial key through every node that was about // to be collapsed away.+ timer.switch("morton-sort"); println!("Sorting {kept_count} surviving node(s) by spatial key..."); let mut keys: Vec<(u64, u32)> = Vec::with_capacity(kept_count as usize); let mut prog = crate::progress::Progress::new("Morton keys", u64::from(slots));@@ -317,9 +324,11 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> }; // --- The edge index ------------------------------------------------------ let csr = build_csr(&collapsed.spill, kept_count, &ids)?;+ timer.switch("edge-index");+ let csr = build_csr(&collapsed.spill, kept_count, &ids, &mut timer)?; // --- Reconnect isolated transit stops -----------------------------------+ timer.switch("components"); let rec = reconnect_isolated_stops(&node_coords, &stops_final, &csr); let synth = rec.synth; drop(stops_final);@@ -331,6 +340,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> Some(path) => Some(crate::dem::Dem::load(path)?), None => None, };+ timer.switch("write"); let written = write_graph( out_dir, &node_coords,@@ -341,12 +351,14 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> &ids, opts.round_count(), dem.as_ref(),+ &mut timer, )?; collapsed.spill.remove(); let unique_names = pool.unique_count(); let name_bytes = pool.byte_len(); pool.finish().map_err(io_err)?; + timer.finish(); println!( "Done. Nodes: {} Edges: {} intermediate.bin: {} byte(s)", kept_count, written.edge_count, written.intermediate_bytes@@ -412,7 +424,9 @@ fn collapse_segments<W: std::io::Write + Send>( slots: u32, filter: RegionFilter, pool: &mut NamePool<W>,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Collapsed> {+ timer.switch("collapse-segments"); // One record per consecutive way-node pair, still carrying both directions' // lane data. Splitting into directed edges is deferred until after // compaction, because pairing a `u -> v` edge with its `v -> u` twin is only@@ -458,6 +472,7 @@ fn collapse_segments<W: std::io::Write + Send>( segs.len() ); + timer.switch("collapse-compact"); let comp = compact::compact(slots, &segs, &lane_pool, |n| coords[n as usize], |n| { stop.get(u64::from(n)) });
scripts/maps/osm_ingest/src/graph_build_part2.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part2.rs b/scripts/maps/osm_ingest/src/graph_build_part2.rsindex 9cbdcdb933..47ec8eb0d3 100644--- a/scripts/maps/osm_ingest/src/graph_build_part2.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part2.rs@@ -13,9 +13,12 @@ fn collapse_within_ways<W: std::io::Write + Send>( slots: u32, filter: RegionFilter, pool: &mut NamePool<W>,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Collapsed> {+ timer.switch("collapse-degrees"); let degree = chains::count_degrees(input, blobs, blob_kinds, index, slots, filter)?; let spill = chains::Spill::split(spill_dir, spill_pts_dir);+ timer.switch("collapse-chains"); let built = chains::build( input, blobs, blob_kinds, index, coords, °ree, stop, slots, filter, pool, &spill, )?;@@ -147,7 +150,12 @@ struct Synth { dist_mm: u32, } -fn build_csr(spill: &chains::Spill, kept_count: u32, ids: &FinalIds) -> Result<Csr> {+fn build_csr(+ spill: &chains::Spill,+ kept_count: u32,+ ids: &FinalIds,+ timer: &mut crate::timing::PhaseTimer,+) -> Result<Csr> { println!("Building the edge index over {kept_count} node(s)..."); let chain_total = spill.chain_count()?; let mut edge_ptr = vec![0u64; kept_count as usize + 2];@@ -166,6 +174,7 @@ fn build_csr(spill: &chains::Spill, kept_count: u32, ids: &FinalIds) -> Result<C } let total = edge_ptr[kept_count as usize];+ timer.switch("edge-index-scatter"); let mut targets = vec![0u32; total as usize]; let mut cursor: Vec<u64> = edge_ptr[..=kept_count as usize].to_vec(); let mut hdr = spill.headers()?;@@ -209,6 +218,7 @@ fn build_csr(spill: &chains::Spill, kept_count: u32, ids: &FinalIds) -> Result<C consumed = end; } let ptr = &edge_ptr;+ timer.switch("edge-index-sort"); eprintln!("Sorting edge groups across {workers} worker(s)..."); par::install(|| { pieces.par_iter_mut().for_each(|(lo, hi, buf)| {
scripts/maps/osm_ingest/src/graph_build_part3.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part3.rs b/scripts/maps/osm_ingest/src/graph_build_part3.rsindex 176c10c91e..6622b1413e 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -168,7 +168,7 @@ fn reconnect_isolated_stops(coords: &[geom::Pt], stops: &Bitset, csr: &Csr) -> R // within that window stays unreachable. Say so rather than dropping it // silently: an unreachable stop is exactly what this pass exists to // prevent. A large count here means MIN_ROUTABLE_COMPONENT is too high.- println!("WARNING: {unreachable} isolated stop(s) had no routable road nearby");+ eprintln!("WARN: {unreachable} isolated stop(s) had no routable road nearby"); } synth.sort_by_key(|s| (s.source, s.target)); Reconnected {@@ -224,6 +224,7 @@ fn write_graph( ids: &FinalIds, rounds: u32, dem: Option<&crate::dem::Dem>,+ timer: &mut crate::timing::PhaseTimer, ) -> Result<Written> { let kept = node_coords.len() as u32; let edge_count = csr.edge_count() + synth.len() as u64;@@ -265,6 +266,7 @@ fn write_graph( let hi = (u64::from(kept) * u64::from(round + 1) / u64::from(rounds)) as u32; buffer.clear();+ timer.switch("write-scan"); let mut hdr = spill.headers()?; let mut ci = 0u32; let mut prog = crate::progress::Progress::new(@@ -324,6 +326,7 @@ fn write_graph( buffer.sort_by_key(|e| (e.source, e.target, e.chain)); let mut cursor = 0usize;+ timer.switch("write-write"); let mut wprog = crate::progress::Progress::new( format!("Round {}/{rounds}: write", round + 1), u64::from(hi - lo),
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 950f446e3a..31d1667078 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -35,6 +35,7 @@ pub mod pbf; pub(crate) mod progress; pub mod pbf_extra; pub mod poi_attrs;+pub mod timing; pub mod poi_build; pub mod poi_side; pub mod proto;
scripts/maps/osm_ingest/src/nodeloc_part1.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc_part1.rs b/scripts/maps/osm_ingest/src/nodeloc_part1.rsindex 4f492a890c..2439437608 100644--- a/scripts/maps/osm_ingest/src/nodeloc_part1.rs+++ b/scripts/maps/osm_ingest/src/nodeloc_part1.rs@@ -1,31 +1,3 @@-/// Where the node pass's CPU goes, split between decoding blocks and writing coordinates.-///-/// Nanoseconds. `SCAN_NANOS` covers **both** the protobuf decode of a block and the id lookups for-/// its nodes, because it brackets the whole `visit_block` call -- timing the lookups alone would need-/// a clock read per node, and there are 2.3 billion of them on a north-america extract. An earlier-/// version of this comment called it "searching" and a conclusion was drawn from it about the id-/// index; that was wrong, and the number cannot tell those two apart. What it does bound is the-/// write side, which is the part that is serialised: `run_pass_sink` calls its sink under a lock.-///-/// Timed per CHUNK rather than per node -- a chunk is eight blobs, tens of thousands of nodes -- so-/// two `Instant::now()` calls and one atomic add cost nothing measurable. Off unless `MAPS_TIMING`-/// is set regardless, for the reason `mamaps_build`'s encode counters are: an instrument hit once per-/// item across 64 workers changes what it measures.-static SCAN_NANOS: atomic::AtomicU64 = atomic::AtomicU64::new(0);-static WRITE_NANOS: atomic::AtomicU64 = atomic::AtomicU64::new(0);--fn timing() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var_os("MAPS_TIMING").is_some())-}--/// The node pass's split in seconds of CPU: `(decode and look up, write)`. Zero without-/// `MAPS_TIMING`.-pub fn resolve_seconds() -> (f64, f64) {- let s = |c: &atomic::AtomicU64| c.load(atomic::Ordering::Relaxed) as f64 / 1e9;- (s(&SCAN_NANOS), s(&WRITE_NANOS))-}- /// The node pass: fill in every coordinate the earlier passes asked for. /// /// Uses [`pbf::run_pass_sink`] rather than [`pbf::run_pass`], because `run_pass`'s contract is to@@ -87,7 +59,6 @@ where C: Fn(&NodeView) -> Option<L> + Sync, D: FnMut(Vec<L>) -> Result<()> + Send, {- let on = timing(); // Moved out so the workers can search it while the sink writes coordinates; put back below. let ids = std::mem::take(&mut table.ids); let locs = &mut table.locs;@@ -99,7 +70,6 @@ where label, || (Vec::<(u64, i32, i32)>::new(), Vec::<L>::new()), |state: &mut (Vec<(u64, i32, i32)>, Vec<L>), block| {- let at = on.then(std::time::Instant::now); let mut kinds = 0u8; // One cursor per block, because that is the run of ascending ids: a PBF block's dense // nodes are delta-encoded and therefore sorted, so this pays one binary search here and@@ -116,13 +86,9 @@ where } Ok(()) })?;- if let Some(at) = at {- SCAN_NANOS.fetch_add(at.elapsed().as_nanos() as u64, atomic::Ordering::Relaxed);- } Ok(kinds) }, |(coords, items)| {- let at = on.then(std::time::Instant::now); // Sorted by table index before the stores, so the mmap writes walk forward // instead of scattering: a chunk's ids arrive in block order (ascending within // a block, but blocks interleave across the chunk), and 8-byte stores to@@ -136,9 +102,6 @@ where for (idx, lat, lon) in coords { locs.set(idx as usize, lat, lon); }- if let Some(at) = at {- WRITE_NANOS.fetch_add(at.elapsed().as_nanos() as u64, atomic::Ordering::Relaxed);- } // After the coordinate writes, so a caller that both resolves and classifies sees the // two in the order this pass names them. drain(items)?;
scripts/maps/osm_ingest/src/par.rs
diff --git a/scripts/maps/osm_ingest/src/par.rs b/scripts/maps/osm_ingest/src/par.rsindex c42748bec4..68f205facb 100644--- a/scripts/maps/osm_ingest/src/par.rs+++ b/scripts/maps/osm_ingest/src/par.rs@@ -70,7 +70,7 @@ fn env_threads(raw: Option<&str>) -> Option<usize> { Ok(n) if n > 0 => Some(n), _ => { WARNED.call_once(|| {- eprintln!("WARNING: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");+ eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)"); }); None }@@ -108,7 +108,7 @@ fn pool() -> Arc<rayon::ThreadPool> { } } let built = Arc::new(build_pool(want).unwrap_or_else(|e| {- eprintln!("WARNING: cannot start a {want}-thread pool ({e}); continuing on one thread");+ eprintln!("WARN: cannot start a {want}-thread pool ({e}); continuing on one thread"); build_pool(1).expect("a one-thread pool") })); *cached = Some((want, Arc::clone(&built)));
scripts/maps/osm_ingest/src/pbf.rs
diff --git a/scripts/maps/osm_ingest/src/pbf.rs b/scripts/maps/osm_ingest/src/pbf.rsindex cbb67c0a00..997dec449f 100644--- a/scripts/maps/osm_ingest/src/pbf.rs+++ b/scripts/maps/osm_ingest/src/pbf.rs@@ -322,6 +322,9 @@ where let next_chunk = AtomicUsize::new(0); let done_blobs = AtomicUsize::new(0); let last_pct = AtomicUsize::new(usize::MAX);+ // Owns the meter's clock: `report` draws the progress.rs standard shape+ // (`label [pct%] done/total elapsed, ETA`) from it on every redraw.+ let pass_start = std::time::Instant::now(); let n_threads = crate::par::threads().min(n_chunks); let mut first_err: Option<Error> = None; // How far ahead of the sink the workers may run.@@ -379,7 +382,7 @@ where kinds[idx].store(seen, Ordering::Relaxed); } }- report(label, &done_blobs, &last_pct, blobs.len());+ report(label, &done_blobs, &last_pct, blobs.len(), &pass_start); } drain.lock().expect("chunk slot mutex").deposit(chunk, state); progressed.notify_all();@@ -413,7 +416,15 @@ where // Every chunk was deposited, and deposits drain in order, so nothing can be // left behind unless a sink call failed above. debug_assert_eq!(d.next, n_chunks, "chunks left undrained");- eprintln!("\r{label:<28} [100%]");+ // Snap to 100% in the same standard shape, then a fresh line so the next+ // stage starts clean instead of on top of the meter.+ {+ let n = blobs.len();+ eprintln!(+ "\r{label:<28} [100%] {n}/{n} {} elapsed, ETA 0s ",+ crate::progress::hms(pass_start.elapsed().as_secs_f64()),+ );+ } Ok(kinds.iter().map(|k| k.load(Ordering::Relaxed)).collect()) } @@ -481,7 +492,15 @@ pub(crate) fn read_exact_at(file: &mut File, loc: &BlobLoc, out: &mut Vec<u8>) - .map_err(|e| Error(format!("short read at {}: {e}", loc.offset))) } -fn report(label: &str, done: &AtomicUsize, last_pct: &AtomicUsize, total: usize) {+/// One redraw of the pass meter, in the single standard shape (`progress.rs`):+/// `label [pct%] done/total elapsed, ETA` on one stderr line.+fn report(+ label: &str,+ done: &AtomicUsize,+ last_pct: &AtomicUsize,+ total: usize,+ start: &std::time::Instant,+) { let n = done.fetch_add(1, Ordering::Relaxed) + 1; if total == 0 { return;@@ -493,7 +512,19 @@ fn report(label: &str, done: &AtomicUsize, last_pct: &AtomicUsize, total: usize) .compare_exchange(prev, pct, Ordering::Relaxed, Ordering::Relaxed) .is_ok() {- eprint!("\r{label:<28} [{pct}%] ");+ let elapsed = start.elapsed().as_secs_f64();+ // ETA extrapolates the average rate so far; meaningless until something is+ // done, so hold it at zero for the opening frame.+ let eta = if n == 0 {+ 0.0+ } else {+ elapsed * (total - n) as f64 / n as f64+ };+ eprint!(+ "\r{label:<28} [{pct:>3}%] {n}/{total} {} elapsed, ETA {} ",+ crate::progress::hms(elapsed),+ crate::progress::hms(eta),+ ); let _ = std::io::stderr().flush(); } }
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex 467074665d..33d84a9d0b 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -159,9 +159,11 @@ pub fn build_with( } } + let mut timer = crate::timing::PhaseTimer::start("poi"); let blobs = pbf::scan_blobs(input)?;- println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());+ println!("[poi] Scanned {} data blob(s) in {}", blobs.len(), input.display()); + timer.switch("relations"); // --- Pass 1: area relations --------------------------------------------- let (chunks, blob_kinds) = pbf::run_pass( input,@@ -184,6 +186,7 @@ pub fn build_with( outer_wanted.dedup(); println!("{} POI relation(s)", rel_areas.len()); + timer.switch("ways"); // --- Pass 2: closed-way areas + the relations' outer ways ---------------- let (chunks, _) = pbf::run_pass( input,@@ -215,6 +218,7 @@ pub fn build_with( needed.len() ); + timer.switch("nodes"); // --- Pass 3: node POIs + the node locations areas need ------------------- let (chunks, _) = pbf::run_pass( input,@@ -252,6 +256,7 @@ pub fn build_with( ids.filter_map(&location).any(|(lat, lon)| b.contains_e7(lat, lon)) }; + timer.switch("centroids"); // --- Area centroids ------------------------------------------------------ for area in &way_areas { if !touches(&mut area.refs.iter().copied()) {@@ -294,9 +299,12 @@ pub fn build_with( // Morton order, ties broken by osm_id, so both poi_index.bin and the geojson // are stable across runs.+ timer.switch("sort"); pois.sort_by_key(|p| (p.morton, p.osm_id)); + timer.switch("write"); let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index)?;+ timer.finish(); Ok(Stats { records: written.records, unique_names: written.unique_names,
scripts/maps/osm_ingest/src/progress.rs
diff --git a/scripts/maps/osm_ingest/src/progress.rs b/scripts/maps/osm_ingest/src/progress.rsindex a0b540eef4..1cd8b80ae2 100644--- a/scripts/maps/osm_ingest/src/progress.rs+++ b/scripts/maps/osm_ingest/src/progress.rs@@ -87,7 +87,8 @@ impl Progress { } /// Whole seconds as `HhMMmSSs`, dropping units above the largest non-zero one.-fn hms(secs: f64) -> String {+/// Shared with `pbf.rs` so every live meter draws the one standard shape.+pub(crate) fn hms(secs: f64) -> String { let s = secs.max(0.0) as u64; let (h, m, s) = (s / 3600, (s % 3600) / 60, s % 60); if h > 0 {
scripts/maps/osm_ingest/src/timing.rs
diff --git a/scripts/maps/osm_ingest/src/timing.rs b/scripts/maps/osm_ingest/src/timing.rsnew file mode 100644index 0000000000..408b66a03e--- /dev/null+++ b/scripts/maps/osm_ingest/src/timing.rs@@ -0,0 +1,154 @@+//! Gapless phase/subphase wall-clock timer for the maps pipeline.+//!+//! One `PhaseTimer` covers one tool run (which is one pipeline phase). Time is+//! booked by *switching*: `switch("next")` stops the current subphase and starts+//! the next one on the same instant, so subphases tile the phase wall with no+//! gaps and no overlaps — the stop of every subphase is the start of the next.+//! The summed subphases therefore equal the phase wall up to the microseconds+//! the switch itself costs.+//!+//! The timer starts in an implicit `"other"` subphase, which also absorbs any+//! stretch the caller never names. Callers name each major loop/pass and never+//! need to account for setup/teardown explicitly: whatever is left in `"other"`+//! at [`PhaseTimer::finish`] is the honest overhead bucket, not a fudge factor.+//!+//! Results leave the process as one parse-safe machine line on **stdout only**:+//!+//! ```text+//! TIMING {"phase":"tiles","wall_s":123.456,"subphases":[{"name":"stage-a","s":12.345}]}+//! ```+//!+//! Live progress meters stay on stderr (see `progress.rs`), warnings are+//! `WARN: ...` on stderr, errors `ERROR: ...` on stderr. Nothing else on stdout+//! may start with `TIMING `, and `TIMING` lines never go to stderr, so the+//! orchestrator can split the streams without ambiguity.+//!+//! Contract, kept identical in every crate that carries a copy of this file+//! (copies, not a shared crate: `gtfs_ingest` builds with zero dependencies,+//! and `par.rs` / `progress.rs` already follow the same copy convention):+//!+//! * std only, no dependencies.+//! * One timer per process, driven from the orchestrating (main) thread only.+//! Worker threads never touch it; coarse loop/pass boundaries are the ticks.+//! * `finish` merges repeat visits to the same subphase name (e.g. per-zoom+//! `map`/`merge`/`encode`/`append`) by summing, preserving first-seen order,+//! so fine-grained loops stay bounded instead of exploding the output.+//! * Durations print with millisecond precision (`{:.3}` seconds).+//! * Never one entry per feed / per tile / per feature: group those loops into+//! one bounded subphase (e.g. `parse-feeds`, `encode`), the way per-zoom work+//! folds into four totals here.++use std::time::Instant;++/// A single phase's gapless subphase chain. See the module docs.+pub struct PhaseTimer {+ phase: String,+ start: Instant,+ /// Name of the currently open subphase.+ current: String,+ /// When the currently open subphase started.+ current_start: Instant,+ /// Closed `(name, seconds)` segments, in close order.+ segments: Vec<(String, f64)>,+}++impl PhaseTimer {+ /// Start a phase clock. The clock opens in the `"other"` subphase, so any+ /// work before the first [`PhaseTimer::switch`] is booked as overhead.+ pub fn start(phase: &str) -> Self {+ let now = Instant::now();+ Self {+ phase: phase.to_string(),+ start: now,+ current: "other".to_string(),+ current_start: now,+ segments: Vec::new(),+ }+ }++ /// Close the current subphase and open `name`, on the same instant.+ /// Repeat visits to a name are merged (summed) at [`PhaseTimer::finish`].+ pub fn switch(&mut self, name: &str) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let old = std::mem::replace(&mut self.current, name.to_string());+ self.segments.push((old, secs));+ self.current_start = Instant::now();+ }++ /// Close the current subphase, merge repeats, and emit the `TIMING` line.+ /// Consumes the timer so a phase can only be reported once.+ pub fn finish(mut self) {+ self.close_current();+ let wall = self.start.elapsed().as_secs_f64();+ let mut merged: Vec<(String, f64)> = Vec::with_capacity(self.segments.len());+ for (name, secs) in &self.segments {+ match merged.iter_mut().find(|(n, _)| n == name) {+ Some(slot) => slot.1 += secs,+ None => merged.push((name.clone(), *secs)),+ }+ }+ let mut subs = String::new();+ for (i, (name, secs)) in merged.iter().enumerate() {+ if i > 0 {+ subs.push(',');+ }+ subs.push_str("{\"name\":\"");+ esc_json(name, &mut subs);+ subs.push_str(&format!("\",\"s\":{secs:.3}}}"));+ }+ let mut line = String::from("TIMING {\"phase\":\"");+ esc_json(&self.phase, &mut line);+ line.push_str(&format!("\",\"wall_s\":{wall:.3},\"subphases\":[{subs}]}}"));+ println!("{line}");+ }++ fn close_current(&mut self) {+ let secs = self.current_start.elapsed().as_secs_f64();+ let name = std::mem::replace(&mut self.current, String::new());+ self.segments.push((name, secs));+ }+}++/// Append `s` to `out` with JSON string escaping.+fn esc_json(s: &str, out: &mut String) {+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if (c as u32) < 0x20 => {+ out.push_str(&format!("\\u{:04x}", c as u32));+ }+ c => out.push(c),+ }+ }+}++/// Emit one per-zoom machine line on stdout, next to (not instead of) the+/// human-readable `zN ...` table row. Integer milliseconds — unlike the+/// 0.1 s-rounded text row, these close the sum exactly.+///+/// `map_ms` / `merge_ms` / `encode_ms` / `append_ms` use the same meaning as+/// the text table: per-zoom worker time in each tiling step.+#[allow(clippy::too_many_arguments)]+pub fn emit_zoom_row(+ zoom: u8,+ tiles: u64,+ features: u64,+ points: u64,+ dropped: u64,+ bytes: u64,+ map_ms: u64,+ merge_ms: u64,+ encode_ms: u64,+ append_ms: u64,+) {+ println!(+ "TIMING {{\"zoom\":{zoom},\"tiles\":{tiles},\"features\":{features},\+ \"points\":{points},\"dropped\":{dropped},\"bytes\":{bytes},\+ \"map_ms\":{map_ms},\"merge_ms\":{merge_ms},\+ \"encode_ms\":{encode_ms},\"append_ms\":{append_ms}}}"+ );+}
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex 5901ec9cb4..14a3fb5ada 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -33,6 +33,7 @@ use tile_build::mamaps::archive::{ ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, }; use tile_build::mamaps::header::Header;+use tile_build::timing::PhaseTimer; fn read_file(path: &Path) -> Result<Vec<u8>, String> { std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))@@ -65,7 +66,22 @@ struct Validated { osm_id: [u8; 8], } +/// Untimed entry point, kept for the unit tests below: identical staging and+/// validation, timed against a sink that is never finished so tests emit no+/// TIMING lines. Production `main` calls `load_sidecars_impl` with the real+/// phase timer for per-directory subphases.+#[cfg(test)] fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Validated, String> {+ let mut sink = PhaseTimer::start("pack-test");+ load_sidecars_impl(graph, poi, transit, &mut sink)+}++fn load_sidecars_impl(+ graph: &Path,+ poi: &Path,+ transit: Option<&Path>,+ timer: &mut PhaseTimer,+) -> Result<Validated, String> { let mut staged: Vec<Staged> = Vec::new(); // Canonical order = kind order (ArchiveView requires ascending kinds). let mut push = |kind: u8, path: PathBuf, required: bool| -> Result<(), String> {@@ -80,6 +96,7 @@ fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Val Err(e) => Err(format!("cannot stat {}: {e}", path.display())), } };+ timer.switch("read-graph"); push(ARCHIVE_KIND_GRAPH_META, graph.join("metadata.bin"), true)?; push(ARCHIVE_KIND_GRAPH_NODES, graph.join("nodes.bin"), true)?; push(ARCHIVE_KIND_GRAPH_EDGES, graph.join("edges.bin"), true)?;@@ -88,6 +105,7 @@ fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Val push(ARCHIVE_KIND_GRAPH_NAMES, graph.join("road_names.bin"), false)?; push(ARCHIVE_KIND_GRAPH_LANES, graph.join("lanes.bin"), false)?; push(ARCHIVE_KIND_GRAPH_ELEVATION, graph.join("elevation.bin"), false)?;+ timer.switch("read-poi"); push(ARCHIVE_KIND_POI_INDEX, poi.join("poi_index.bin"), true)?; push(ARCHIVE_KIND_POI_NAMES, poi.join("poi_names.bin"), true)?; push(ARCHIVE_KIND_POI_ATTRS, poi.join("poi_attrs.bin"), false)?;@@ -96,6 +114,7 @@ fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Val // Transit is optional like the other sidecars: omitted when no pack is // staged (a tiles+graph+POI archive still exercises every loader's // degrade path on device). Callers that need it pass --transit.+ timer.switch("read-transit"); let mut transit_prefix = Vec::new(); if let Some(t) = transit { let len = std::fs::metadata(t)@@ -114,7 +133,7 @@ fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Val // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit // and no partial output. Only the small files are read whole; the large graph payloads // validate by streaming their heads (lengths come from the metadata counts).- validate_sidecars(graph, poi, &staged)?;+ validate_sidecars(graph, poi, &staged, timer)?; // The tile header's own build-id bytes are read by the caller (it holds the tiles prefix); // placeholder filled in `main` after the tiles prefix is parsed. Ok(Validated { staged, transit_prefix, osm_id: [0u8; 8] })@@ -127,7 +146,15 @@ fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Val /// `intermediate.bin`) are checked by length against the metadata counts, plus a streaming /// magic spot-check is unnecessary: their first bytes are fixed strides the length check /// already covers, and the packed archive is re-validated by `ArchiveView` below.-fn validate_sidecars(graph: &Path, poi: &Path, staged: &[Staged]) -> Result<(), String> {+fn validate_sidecars(+ graph: &Path,+ poi: &Path,+ staged: &[Staged],+ timer: &mut PhaseTimer,+) -> Result<(), String> {+ // Repeat visits: `finish` merges these with the staging switches above, so+ // each directory's staging + validation report as one subphase.+ timer.switch("read-graph"); let g = |name: &str| read_file(&graph.join(name)); let p = |name: &str| read_file(&poi.join(name)); // Graph meta first: it carries the counts every other graph check is sized from.@@ -252,6 +279,7 @@ fn validate_sidecars(graph: &Path, poi: &Path, staged: &[Staged]) -> Result<(), } } // POI index/names/attrs/spatial/words: small, read whole and cross-check counts.+ timer.switch("read-poi"); let poi_index = p("poi_index.bin")?; if poi_index.len() as u64 % 14 != 0 { return Err("poi_index.bin is not whole 14-byte records".to_string());@@ -536,7 +564,7 @@ fn value(args: &[String], i: usize, name: &str) -> PathBuf { match args.get(i + 1) { Some(v) => PathBuf::from(v), None => {- eprintln!("mamaps_pack
Diff truncated.