Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / build_graph.ps1
build_graph.ps1658 lines · 34.0 KiBRaw
| 1 | # build_graph.ps1 -- build one .mamaps archive from one extract, end to end. |
| 2 | # |
| 3 | # The single full builder: OSM extract (+ coastline, world-transit feeds, DEM) |
| 4 | # in, final .mamaps out. One command does the whole pipeline: |
| 5 | # |
| 6 | # [1] check every input exists + the free-space preflight |
| 7 | # [2] cargo-build the host tools (road_graph, poi_extract, transit_shapes, |
| 8 | # mamaps_build, mamaps_dump, mamaps_pack) |
| 9 | # [3] build the road graph into a TEMP dir (never the final output) |
| 10 | # [4] derive the transit-routes layer from inputs/world.transit itself |
| 11 | # (transit_shapes --pack; the raw GTFS feeds are not needed) |
| 12 | # [5] run mamaps_build with pbf + coastline + temp graph + routes + dem into a |
| 13 | # TEMP tiles-only archive ($tmp/tiles.mamaps) -- NO sidecar footer yet |
| 14 | # [6] extract the POI sidecars from the pbf into a TEMP dir, then mamaps_pack |
| 15 | # the graph + POI + transit sidecar sections onto the temp tiles archive |
| 16 | # to produce the FINAL $Out (this is what adds the MAMA8 sidecar footer |
| 17 | # the app's router, departure boards and POI tags read) |
| 18 | # [7] header check via mamaps_dump on the FINAL $Out (rings_validated, 16 KiB |
| 19 | # prefix budget, build_id printed) + TIME/PER-ZOOM/PEAK-MEMORY summary, |
| 20 | # then delete every intermediate (the temp dir is always removed on success). |
| 21 | # |
| 22 | # Nothing here is optional content except under -NoTransit: every input is |
| 23 | # mandatory and every build is all 12 layers at z0-14. -Threads/-Verify are |
| 24 | # operational (how), not content options -- there is no flag that skips |
| 25 | # the coastline, the graph, the DEM, a layer, or a zoom. -NoTransit is the |
| 26 | # one content exception: it skips every GTFS feed (empty transit-routes + |
| 27 | # no --transit sidecar, as if 0 feeds). |
| 28 | # |
| 29 | # Spill backends: by default the feature spill, tile chunks and ways spill |
| 30 | # stage as temp files beside the output. `MAPS_ANON_SPILL=1` stages them in |
| 31 | # pagefile-backed anonymous memory instead — same bytes, no `.tmp` files, |
| 32 | # nothing stranded on kill. The pagefile cap is then the bound, not free disk |
| 33 | # (system-managed pagefile is what a world build wants); without it the preflight |
| 34 | # below warns against a larger multiple. |
| 35 | # |
| 36 | # This folds in the old measure_build.ps1 (live progress + cost report) and the |
| 37 | # old harden_mamaps.sh (header checks; its full 1/3/32-thread matrix lives on |
| 38 | # as the -Verify spot-check, off by default because it doubles build time). |
| 39 | # |
| 40 | # Usage: |
| 41 | # .\build_graph.ps1 [-Region california|na|world|caonly|naonly] [-NoTransit] [-Verify] [-Threads N] |
| 42 | # |
| 43 | # -Region filters roads/POIs/buildings to the region's bbox. Everything else |
| 44 | # (water, earth, boundaries, landuse, transit, traffic, DEM) is always |
| 45 | # included regardless. The input is ALWAYS the planet -- except caonly, which |
| 46 | # takes inputs/california.osm.pbf directly with NO coordinate filtering, and |
| 47 | # naonly, which takes inputs/north-america.osm.pbf directly the same way |
| 48 | # (downstream tools get --region world): a california build is |
| 49 | # a world build with only CA roads/POIs/buildings, so borders, coastlines |
| 50 | # and country names still render everywhere. |
| 51 | # |
| 52 | # Inputs are fixed (no file-location options): |
| 53 | # inputs/planet.osm.pbf -> inputs/california.mamaps | inputs/na.mamaps | inputs/world.mamaps |
| 54 | # inputs/california.osm.pbf -> inputs/caonly.mamaps (only with -Region caonly) |
| 55 | # inputs/north-america.osm.pbf -> inputs/naonly.mamaps (only with -Region naonly) |
| 56 | # plus inputs/coastline.shp, inputs/world.mdem. |
| 57 | # inputs/world.transit is required |
| 58 | # unless -NoTransit is passed, which skips GTFS entirely (empty routes + |
| 59 | # no --transit sidecar, as if 0 feeds). |
| 60 | # inputs/reviews_archive.tsv is required: its per-place rating, review count |
| 61 | # and summary are always merged into the POI attribute sidecar by OSM element |
| 62 | # (see analysis/osm_reviews/summarize_reviews.py). |
| 63 | # |
| 64 | # Requires: cargo (https://rustup.rs). A state-sized extract needs roughly |
| 65 | # 10 GB of RAM; any build wants ~6x the .pbf in free disk (checked up front), |
| 66 | # or ~2x under MAPS_ANON_SPILL=1 (archive + sidecars only — the spills live |
| 67 | # in the pagefile, so the pagefile cap is the bound instead). |
| 68 | #[CmdletBinding()] |
| 69 | param( |
| 70 | # Which region to build: california filters roads/POIs/buildings to the |
| 71 | # California bbox, na to the North America bbox, world builds everything. |
| 72 | # Everything else (water, earth, boundaries, landuse, transit, traffic, |
| 73 | # DEM) is always included. |
| 74 | [ValidateSet("california", "na", "world", "caonly", "naonly")] |
| 75 | [string] $Region = "world", |
| 76 | # Skip every GTFS feed: no transit_shapes run, an empty transit-routes |
| 77 | # file for mamaps_build, and no --transit sidecar on the pack -- the |
| 78 | # archive builds as if 0 feeds existed. |
| 79 | [switch] $NoTransit, |
| 80 | # Worker threads (via MAPS_THREADS). 0 = the tools' default (max). |
| 81 | [int] $Threads = 0, |
| 82 | # Determinism spot-check: rebuild at 1 thread into temp and require a |
| 83 | # byte-identical sha256. Off by default; it doubles the build. |
| 84 | [switch] $Verify |
| 85 | ) |
| 86 | |
| 87 | $ErrorActionPreference = "Stop" |
| 88 | |
| 89 | # --- cohesive timing ---------------------------------------------------- |
| 90 | # Two nested gapless chains plus machine lines from the tools. |
| 91 | # |
| 92 | # Outer chain (this script): $TotalSw runs from here to the final report; |
| 93 | # $PhaseSw is restarted at each phase boundary and its elapsed is booked to |
| 94 | # the phase just finished, so TOTAL WALL always equals the sum of the phase |
| 95 | # rows (within ms). No step owns its own Stopwatch anymore. |
| 96 | # |
| 97 | # Inner chain (PS1-owned subphases): $SubSw mirrors the same stop==start |
| 98 | # contract one level down. Switch-Phase first closes the open subphase into |
| 99 | # the old phase, so a subphase never spans a phase boundary. Used for phases |
| 100 | # with no Rust timer (tools' per-crate cargo builds, verify's steps) and for |
| 101 | # PS1-side work inside a Rust-timed phase (transit's manifest resolution). |
| 102 | # |
| 103 | # Rust-timed phases (graph, transit, tiles, poi, pack) report their own |
| 104 | # subphases as `TIMING {"phase":...,"wall_s":...,"subphases":[...]}` lines on |
| 105 | # stdout (see timing.rs, one copy per crate). Each binary's stdout is Tee'd |
| 106 | # to a per-phase log; the report parses those lines back out. Per-zoom |
| 107 | # `TIMING {"zoom":...}` machine rows ride the same channel. |
| 108 | # |
| 109 | # Closure rule, applied uniformly per phase at report time: |
| 110 | # other = phase_wall - sum(named subphases), clamped at zero. |
| 111 | # PS1 phase walls are ground truth; Rust subphases are the measured detail; |
| 112 | # `other` absorbs spawn/pipe overhead (and the microseconds of boundary skew |
| 113 | # between the two clocks), so subphases always sum to the phase wall. |
| 114 | # |
| 115 | # To time a new step: one Switch-Phase/Switch-Subphase call at its boundary |
| 116 | # (Rust side: one timer.switch), and it appears in TIME + timing.json. |
| 117 | $script:PhaseTimes = [ordered]@{} |
| 118 | $script:SubTimes = [ordered]@{} # "phase/sub" -> seconds, PS1-owned subphases only |
| 119 | $script:TotalSw = [System.Diagnostics.Stopwatch]::StartNew() |
| 120 | $script:PhaseSw = [System.Diagnostics.Stopwatch]::StartNew() |
| 121 | $script:SubSw = [System.Diagnostics.Stopwatch]::StartNew() |
| 122 | $script:PhaseCurrent = "preflight" |
| 123 | $script:SubCurrent = "other" |
| 124 | function Switch-Subphase([string] $Next) { |
| 125 | # Read first, restart second: the boundary instant belongs to neither |
| 126 | # subphase twice and to no gap. Bookkeeping happens after the restart so |
| 127 | # it never leaks into either subphase. |
| 128 | $elapsed = $script:SubSw.Elapsed.TotalSeconds |
| 129 | $script:SubSw.Restart() |
| 130 | $key = "$($script:PhaseCurrent)/$($script:SubCurrent)" |
| 131 | if ($script:SubTimes.Contains($key)) { $script:SubTimes[$key] += $elapsed } else { $script:SubTimes[$key] = $elapsed } |
| 132 | $script:SubCurrent = $Next |
| 133 | } |
| 134 | function Switch-Phase([string] $Next) { |
| 135 | # Close the open subphase into the OLD phase first, so no subphase ever |
| 136 | # spans a phase boundary; then the phase switch itself, as before. |
| 137 | Switch-Subphase "other" | Out-Null |
| 138 | $elapsed = $script:PhaseSw.Elapsed.TotalSeconds |
| 139 | $script:PhaseSw.Restart() |
| 140 | if ($script:PhaseTimes.Contains($script:PhaseCurrent)) { $script:PhaseTimes[$script:PhaseCurrent] += $elapsed } else { $script:PhaseTimes[$script:PhaseCurrent] = $elapsed } |
| 141 | $script:PhaseCurrent = $Next |
| 142 | } |
| 143 | function Stop-Phases() { |
| 144 | Switch-Subphase "other" | Out-Null |
| 145 | $elapsed = $script:PhaseSw.Elapsed.TotalSeconds |
| 146 | $script:PhaseSw.Stop() |
| 147 | $script:TotalSw.Stop() |
| 148 | $script:SubSw.Stop() |
| 149 | if ($script:PhaseTimes.Contains($script:PhaseCurrent)) { $script:PhaseTimes[$script:PhaseCurrent] += $elapsed } else { $script:PhaseTimes[$script:PhaseCurrent] = $elapsed } |
| 150 | } |
| 151 | # Parse one phase log's `TIMING {...}` machine lines. Returns |
| 152 | # @{ wall = <phase wall_s>; subs = [ordered]@{ name = seconds } } for the |
| 153 | # last "phase" line found ($null when the tool never emitted one, e.g. a |
| 154 | # skipped -NoTransit step), plus any per-zoom rows in @{ zooms = @() }. |
| 155 | function Read-TimingLog([string] $Path) { |
| 156 | $phase = $null |
| 157 | $zooms = @() |
| 158 | if (-not (Test-Path $Path)) { return @{ phase = $phase; zooms = $zooms } } |
| 159 | foreach ($line in (Get-Content $Path)) { |
| 160 | if ($line -notmatch '^TIMING (.*)$') { continue } |
| 161 | try { $o = $Matches[1] | ConvertFrom-Json } catch { continue } |
| 162 | $names = @($o.PSObject.Properties.Name) |
| 163 | if ($names -contains 'phase') { |
| 164 | $subs = [ordered]@{} |
| 165 | foreach ($s in $o.subphases) { |
| 166 | if ($subs.Contains($s.name)) { $subs[$s.name] += [double]$s.s } else { $subs[$s.name] = [double]$s.s } |
| 167 | } |
| 168 | $phase = @{ wall = [double]$o.wall_s; subs = $subs } |
| 169 | } elseif ($names -contains 'zoom') { |
| 170 | $zooms += [pscustomobject]@{ |
| 171 | zoom = [int]$o.zoom; tiles = [long]$o.tiles; features = [long]$o.features |
| 172 | points = [long]$o.points; dropped = [long]$o.dropped; bytes = [long]$o.bytes |
| 173 | map_ms = [long]$o.map_ms; merge_ms = [long]$o.merge_ms |
| 174 | encode_ms = [long]$o.encode_ms; append_ms = [long]$o.append_ms |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | return @{ phase = $phase; zooms = $zooms } |
| 179 | } |
| 180 | |
| 181 | # Fixed inputs -- no file-location options. ALWAYS the planet: a california |
| 182 | # build keeps only CA roads/POIs/buildings but renders borders, coastlines |
| 183 | # and country names everywhere, so it needs the whole world as input. |
| 184 | # `na` is the same with the North America bbox. `caonly`/`naonly` are the |
| 185 | # exception: their extracts ARE the region, so they build unfiltered. |
| 186 | $Pbf = Join-Path $PSScriptRoot "inputs/planet.osm.pbf" |
| 187 | if ($Region -eq "california") { |
| 188 | $Out = Join-Path $PSScriptRoot "inputs/california.mamaps" |
| 189 | } elseif ($Region -eq "na") { |
| 190 | $Out = Join-Path $PSScriptRoot "inputs/na.mamaps" |
| 191 | } elseif ($Region -eq "caonly") { |
| 192 | # No coordinate filtering: the extract IS California, so downstream tools |
| 193 | # build it as world. |
| 194 | $Pbf = Join-Path $PSScriptRoot "inputs/california.osm.pbf" |
| 195 | $Out = Join-Path $PSScriptRoot "inputs/caonly.mamaps" |
| 196 | } elseif ($Region -eq "naonly") { |
| 197 | # No coordinate filtering: the extract IS North America, so downstream |
| 198 | # tools build it as world. Distinct from na.mamaps, which filters the |
| 199 | # planet to the NA bbox. |
| 200 | $Pbf = Join-Path $PSScriptRoot "inputs/north-america.osm.pbf" |
| 201 | $Out = Join-Path $PSScriptRoot "inputs/naonly.mamaps" |
| 202 | } else { |
| 203 | $Out = Join-Path $PSScriptRoot "inputs/world.mamaps" |
| 204 | } |
| 205 | # What --region the tools see. caonly/naonly build unfiltered (world) from |
| 206 | # their extracts; every other region passes through. |
| 207 | $BuildRegion = if ($Region -eq "caonly" -or $Region -eq "naonly") { "world" } else { $Region } |
| 208 | $Coastline = Join-Path $PSScriptRoot "inputs/coastline.shp" |
| 209 | $WorldTransit = Join-Path $PSScriptRoot "inputs/world.transit" |
| 210 | $Dem = Join-Path $PSScriptRoot "inputs/world.mdem" |
| 211 | $Reviews = Join-Path $PSScriptRoot "inputs/reviews_archive.tsv" |
| 212 | function Find-Built([string] $crate, [string] $name) { |
| 213 | # The tool crates are root-workspace members (no [workspace] table), so |
| 214 | # `cargo build` links into the WORKSPACE target dir (repo root |
| 215 | # target/release), not the per-crate one. The per-crate target/ dirs are |
| 216 | # fossils from when the crates were detached: cargo never refreshes them, |
| 217 | # so resolving there silently runs an ancient binary (this exact failure |
| 218 | # shipped a pre-fix tiler into a full archive build on 2026-10-19). |
| 219 | # Prefer the workspace binary; fall back to the per-crate path only when |
| 220 | # the workspace one is absent. |
| 221 | $wsBuilt = Join-Path $PSScriptRoot "../../target/release/$name.exe" |
| 222 | if (Test-Path $wsBuilt) { |
| 223 | $wsItem = Get-Item $wsBuilt |
| 224 | $crateItem = $null |
| 225 | $cratePath = Join-Path $PSScriptRoot "$crate\target\release\$name.exe" |
| 226 | if (Test-Path $cratePath) { $crateItem = Get-Item $cratePath } |
| 227 | if ($null -eq $crateItem -or $wsItem.LastWriteTime -ge $crateItem.LastWriteTime) { |
| 228 | return $wsItem.FullName |
| 229 | } |
| 230 | Write-Warning "$name.exe: per-crate copy ($($crateItem.LastWriteTime)) is newer than workspace copy ($($wsItem.LastWriteTime)); using per-crate copy" |
| 231 | } |
| 232 | $built = Join-Path $PSScriptRoot "$crate\target\release\$name.exe" |
| 233 | if (-not (Test-Path $built)) { |
| 234 | throw "no $name.exe after building $crate -- this is a builder bug, not your input" |
| 235 | } |
| 236 | return (Resolve-Path $built).Path |
| 237 | } |
| 238 | |
| 239 | # Adaptive, because these span a 128-byte header and a 30 GB spill; a fixed |
| 240 | # unit makes one end of that unreadable. |
| 241 | function Size([double] $b) { |
| 242 | if ($b -ge 1GB) { return "{0,9:N2} GB" -f ($b / 1GB) } |
| 243 | if ($b -ge 1MB) { return "{0,9:N1} MB" -f ($b / 1MB) } |
| 244 | if ($b -ge 1KB) { return "{0,9:N1} KB" -f ($b / 1KB) } |
| 245 | return "{0,9:N0} B " -f $b |
| 246 | } |
| 247 | |
| 248 | # --- inputs ------------------------------------------------------------- |
| 249 | # -NoTransit drops the GTFS inputs entirely (no world.transit, no manifest). |
| 250 | $pairs = @(@($Pbf, "pbf"), @($Coastline, "coastline"), @($Dem, "dem"), @($Reviews, "reviews")) |
| 251 | if (-not $NoTransit) { $pairs += ,@($WorldTransit, "world.transit") } |
| 252 | foreach ($pair in $pairs) { |
| 253 | if (-not (Test-Path $pair[0])) { throw "$($pair[1]) not found: $($pair[0])" } |
| 254 | } |
| 255 | $Pbf = (Resolve-Path $Pbf).Path |
| 256 | $Coastline = (Resolve-Path $Coastline).Path |
| 257 | $Dem = (Resolve-Path $Dem).Path |
| 258 | $Out = [System.IO.Path]::GetFullPath($Out) |
| 259 | $Reviews = (Resolve-Path $Reviews).Path |
| 260 | if (-not $NoTransit) { |
| 261 | $WorldTransit = (Resolve-Path $WorldTransit).Path |
| 262 | } else { |
| 263 | $WorldTransit = $null |
| 264 | } |
| 265 | |
| 266 | # Two things are on disk at once at the deepest zoom: one zoom's tile chunks |
| 267 | # (file backend only) and the archive being assembled — plus the feature spill |
| 268 | # on the file path. On north-america that was about 29 + 23 + 17 GB against a |
| 269 | # 14 GB .pbf, so six times the source is the rule of thumb. Under |
| 270 | # MAPS_ANON_SPILL=1 the spills live in the pagefile, leaving the archive plus |
| 271 | # sidecars (~2x), and running out an hour into z14, after stage A has already |
| 272 | # been paid for, is the failure this warning exists to flag. |
| 273 | # |
| 274 | # It is a warning, not a hard stop: the multiples are north-america-derived |
| 275 | # upper estimates, and a build may well fit in less. Proceeding on a smaller disk |
| 276 | # is allowed -- you accept the risk of a late z14 out-of-space. |
| 277 | $pbfBytes = (Get-Item $Pbf).Length |
| 278 | $anon = ($env:MAPS_ANON_SPILL -eq "1") -or ($env:MAPS_ANON_SPILL -ieq "true") -or ($env:MAPS_ANON_SPILL -ieq "yes") |
| 279 | $wanted = if ($anon) { $pbfBytes * 2 } else { $pbfBytes * 6 } |
| 280 | $root = [System.IO.Path]::GetPathRoot($Out) |
| 281 | $free = (New-Object System.IO.DriveInfo $root).AvailableFreeSpace |
| 282 | if ($free -lt $wanted) { |
| 283 | $what = if ($anon) { "(archive + sidecars; spills are in the pagefile - check its cap too)" } else { "(feature spill + one zoom's tile chunks + the archive)" } |
| 284 | Write-Warning (("{0} has {1:N1} GB free; this build may want up to about {2:N1} GB " -f ` |
| 285 | $root, ($free / 1GB), ($wanted / 1GB)) + |
| 286 | "$what. Proceeding anyway -- " + |
| 287 | "a large planet run could still hit an out-of-space at z14.") |
| 288 | } |
| 289 | |
| 290 | $tmp = "$Out.buildtmp" |
| 291 | if (Test-Path $tmp) { Remove-Item $tmp -Recurse -Force } |
| 292 | New-Item -ItemType Directory -Force -Path $tmp | Out-Null |
| 293 | $graphDir = Join-Path $tmp "graph" |
| 294 | $routes = Join-Path $tmp "transit-routes.geojsonseq" |
| 295 | $log = Join-Path $tmp "build.log" |
| 296 | # mamaps_build now emits a TILES-ONLY archive here; mamaps_pack folds the |
| 297 | # graph/POI/transit sidecars onto it to produce the final $Out. |
| 298 | $tilesTmp = Join-Path $tmp "tiles.mamaps" |
| 299 | $poiDir = Join-Path $tmp "poi" |
| 300 | if (Test-Path $Out) { Remove-Item $Out -Force } |
| 301 | |
| 302 | if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { |
| 303 | throw "cargo not found. Install Rust from https://rustup.rs" |
| 304 | } |
| 305 | |
| 306 | # Canonical thread behaviour: no inherited pool settings. MAPS_THREADS is the |
| 307 | # one knob both crates honour (see tile_build's par docs); RAYON_NUM_THREADS |
| 308 | # is adopted only when it is unset, so it is cleared rather than left to |
| 309 | # silently shrink a build someone asked for at full width. |
| 310 | if ($Threads -gt 0) { $env:MAPS_THREADS = "$Threads" } else { Remove-Item Env:MAPS_THREADS -ErrorAction SilentlyContinue } |
| 311 | Remove-Item Env:RAYON_NUM_THREADS -ErrorAction SilentlyContinue |
| 312 | Remove-Item Env:MAPS_PREFETCH_LANES -ErrorAction SilentlyContinue |
| 313 | |
| 314 | # --- [1/7] build the host tools ------------------------------------------ |
| 315 | # One crate builds all three PBF consumers now: road_graph, poi_extract and |
| 316 | # mamaps_build share osm_ingest, one pool, and one blob scan via the graph's |
| 317 | # sidecar. transit_shapes stays separate (it reads GTFS, not the PBF). |
| 318 | $null = Switch-Phase "tools" |
| 319 | Write-Host "[1/7] Building the host tools ($Region)" |
| 320 | # PS1-owned subphases: no Rust timer covers cargo itself, so each crate build |
| 321 | # is one subphase named for the binary it produces. |
| 322 | $crates = @(@("osm_ingest", "road_graph"), @("osm_ingest", "road_overlay"), @("osm_ingest", "poi_extract"), @("mamaps_build", "mamaps_build")) |
| 323 | if (-not $NoTransit) { $crates += ,@("gtfs_ingest", "transit_shapes") } |
| 324 | foreach ($crate in $crates) { |
| 325 | Switch-Subphase $crate[1] | Out-Null |
| 326 | cargo build --release --manifest-path (Join-Path $PSScriptRoot "$($crate[0])\Cargo.toml") --bin $($crate[1]) |
| 327 | if ($LASTEXITCODE -ne 0) { throw "cargo build $($crate[0])/$($crate[1]) failed with exit code $LASTEXITCODE" } |
| 328 | } |
| 329 | foreach ($bin in @("mamaps_dump", "mamaps_pack")) { |
| 330 | Switch-Subphase $bin | Out-Null |
| 331 | cargo build --release --manifest-path (Join-Path $PSScriptRoot "tile_build\Cargo.toml") --bin $bin |
| 332 | if ($LASTEXITCODE -ne 0) { throw "cargo build tile_build/$bin failed with exit code $LASTEXITCODE" } |
| 333 | } |
| 334 | $roadGraph = Find-Built "osm_ingest" "road_graph" |
| 335 | $roadOverlay = Find-Built "osm_ingest" "road_overlay" |
| 336 | $poiExtract = Find-Built "osm_ingest" "poi_extract" |
| 337 | if (-not $NoTransit) { $shapes = Find-Built "gtfs_ingest" "transit_shapes" } else { $shapes = $null } |
| 338 | $build = Find-Built "mamaps_build" "mamaps_build" |
| 339 | $dump = Find-Built "tile_build" "mamaps_dump" |
| 340 | $pack = Find-Built "tile_build" "mamaps_pack" |
| 341 | |
| 342 | # --- [2/7] road graph into temp ------------------------------------------ |
| 343 | # The region filter lives here too: a california graph keeps only ways |
| 344 | # touching the state bbox, so the traffic/junction layers and the pack agree |
| 345 | # with the tiles. mamaps_build re-validates the dir before stage A — an empty |
| 346 | # or stale graph used to cost 43 minutes of stage A before failing. |
| 347 | $null = Switch-Phase "graph" |
| 348 | Write-Host "[2/7] Building the routing graph ($Region) -> $graphDir" |
| 349 | # caonly/naonly pass world: the extract IS the region, so no bbox filtering. |
| 350 | # Stdout is Tee'd to the phase log so the report can parse the TIMING line |
| 351 | # back out; bars stay live because Tee-Object does not redirect. |
| 352 | $graphLog = Join-Path $tmp "graph.log" |
| 353 | # Planet-scale inputs OOM the single-round write buffer (~48 B/edge x 1.08 B |
| 354 | # edges); --rounds 3 partitions the write into source-id ranges so peak RSS |
| 355 | # stays in the ~30 GB band (see osm_ingest README "Build-time memory"). Gated |
| 356 | # on input size so state extracts keep single-round behavior. |
| 357 | $graphRounds = @() |
| 358 | if ($pbfBytes -gt 10GB) { $graphRounds = @("--rounds", "3") } |
| 359 | & $roadGraph $Pbf --out $graphDir --region $BuildRegion @graphRounds | Tee-Object -FilePath $graphLog |
| 360 | if ($LASTEXITCODE -ne 0) { throw "road_graph failed with exit code $LASTEXITCODE" } |
| 361 | # Fail HERE, not 43 minutes into stage A: the world build died on a missing |
| 362 | # metadata.bin after paying the whole of stage A first. |
| 363 | if (-not (Test-Path (Join-Path $graphDir "metadata.bin"))) { |
| 364 | throw "graph build produced no metadata.bin at $graphDir -- refusing to run stage A against an empty graph" |
| 365 | } |
| 366 | # Highway overlay: the arterial subgraph long routes search on device. |
| 367 | # mamaps_pack stages graphDir/overlay.bin as an optional section. |
| 368 | & $roadOverlay --graph $graphDir | Tee-Object -FilePath $graphLog -Append |
| 369 | if ($LASTEXITCODE -ne 0) { throw "road_overlay failed with exit code $LASTEXITCODE" } |
| 370 | |
| 371 | # --- [3/7] transit routes from the world transit pack --------------------- |
| 372 | # -NoTransit skips every feed: an empty routes file, as if 0 feeds existed. |
| 373 | # The lines come out of inputs/world.transit itself (every route's fitted shape, |
| 374 | # colour and type), so the ~80 GB of raw feeds it was built from are not needed. |
| 375 | $null = Switch-Phase "transit" |
| 376 | $transitLog = Join-Path $tmp "transit.log" |
| 377 | if ($NoTransit) { |
| 378 | Write-Host "[3/7] NoTransit: skipping all GTFS feeds (empty transit-routes)" |
| 379 | [System.IO.File]::WriteAllText($routes, "") |
| 380 | } else { |
| 381 | Write-Host "[3/7] Deriving transit routes from $WorldTransit" |
| 382 | & $shapes $routes --pack $WorldTransit | Tee-Object -FilePath $transitLog |
| 383 | if ($LASTEXITCODE -ne 0) { throw "transit_shapes failed with exit code $LASTEXITCODE" } |
| 384 | } |
| 385 | |
| 386 | # --- [4/7] the tiles-only archive (temp) ---------------------------------- |
| 387 | # Started before the build, so the first spike cannot be missed. Under |
| 388 | # MAPS_ANON_SPILL the feature spill has no file: the sampler then tracks only |
| 389 | # the process high-water (commit charge is visible in the OS, not in a path). |
| 390 | $null = Switch-Phase "tiles" |
| 391 | $spill = [System.IO.Path]::ChangeExtension($tilesTmp, "features.tmp") |
| 392 | $sampler = Start-Job -ArgumentList "mamaps_build", $spill, $anon -ScriptBlock { |
| 393 | param($name, $spill, $anon) |
| 394 | $peakWs = 0L; $peakSpill = 0L |
| 395 | while ($true) { |
| 396 | $p = Get-Process -Name $name -ErrorAction SilentlyContinue |
| 397 | if ($p) { |
| 398 | $peakWs = [Math]::Max($peakWs, ($p | Measure-Object PeakWorkingSet64 -Maximum).Maximum) |
| 399 | } |
| 400 | if (-not $anon -and (Test-Path $spill)) { |
| 401 | $len = (Get-Item $spill -ErrorAction SilentlyContinue).Length |
| 402 | if ($len -gt $peakSpill) { $peakSpill = $len } |
| 403 | } |
| 404 | [pscustomobject]@{ Ws = $peakWs; Spill = $peakSpill } |
| 405 | Start-Sleep -Milliseconds 250 |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | Write-Host "[4/7] Building $(Split-Path $tilesTmp -Leaf) (tiles only) z0..z14$(if ($Threads -gt 0) { ", $Threads thread(s)" })" |
| 410 | Write-Host "" |
| 411 | # Tee-Object keeps the bars live on the console AND captures stdout to the log, |
| 412 | # which the summary below parses. No redirect: the bars need the console to redraw on. |
| 413 | # No Stopwatch here: the phase chain above already covers this step, from this |
| 414 | # boundary to the next Switch-Phase. (The old $sw made TOTAL WALL tiles-only.) |
| 415 | & $build --input $Pbf --out $tilesTmp ` |
| 416 | --coastline $Coastline ` |
| 417 | --graph $graphDir ` |
| 418 | --transit-routes $routes ` |
| 419 | --dem $Dem ` |
| 420 | --region $BuildRegion | Tee-Object -FilePath $log |
| 421 | $exit = $LASTEXITCODE |
| 422 | |
| 423 | Start-Sleep -Milliseconds 400 |
| 424 | $s = Receive-Job $sampler |
| 425 | Stop-Job $sampler; Remove-Job $sampler -Force |
| 426 | $peakWs = ($s | Measure-Object Ws -Maximum).Maximum |
| 427 | $peakSpill = ($s | Measure-Object Spill -Maximum).Maximum |
| 428 | |
| 429 | # Sampler teardown (job stop + 400 ms settle above) is booked to tiles so the |
| 430 | # POI clock starts exactly when [5/7] prints. |
| 431 | $null = Switch-Phase "poi" |
| 432 | Write-Host "" |
| 433 | if ($exit -ne 0) { |
| 434 | Stop-Phases |
| 435 | $failedSecs = $script:TotalSw.Elapsed.TotalSeconds |
| 436 | Write-Host ("FAILED, exit {0}, after {1:N1} s (temp kept at {2})" -f $exit, $failedSecs, $tmp) |
| 437 | exit $exit |
| 438 | } |
| 439 | |
| 440 | # --- [5/7] POI sidecars --------------------------------------------------- |
| 441 | # The offline POI / restaurant tags come from here: poi_extract bakes the five |
| 442 | # poi_*.bin side files the packer folds in. --index fixes the dir; --attrs, |
| 443 | # --spatial and --name-index default to their poi_*.bin names beside it, which |
| 444 | # is exactly the set mamaps_pack --poi expects. The --geojson output is the |
| 445 | # baked-vector feed and is not consumed by the pack, but poi_extract requires it. |
| 446 | Write-Host "[5/7] Extracting POI sidecars ($Region) -> $poiDir" |
| 447 | New-Item -ItemType Directory -Force -Path $poiDir | Out-Null |
| 448 | $poiLog = Join-Path $tmp "poi.log" |
| 449 | $poiArgs = @( |
| 450 | $Pbf, |
| 451 | "--geojson", (Join-Path $poiDir "poi.geojsonseq"), |
| 452 | "--names", (Join-Path $poiDir "poi_names.bin"), |
| 453 | "--index", (Join-Path $poiDir "poi_index.bin"), |
| 454 | "--region", $BuildRegion, |
| 455 | "--reviews", $Reviews |
| 456 | ) |
| 457 | Write-Host " merging review data from $Reviews" |
| 458 | & $poiExtract @poiArgs | Tee-Object -FilePath $poiLog |
| 459 | if ($LASTEXITCODE -ne 0) { throw "poi_extract failed with exit code $LASTEXITCODE" } |
| 460 | |
| 461 | # --- [6/7] pack the sidecars onto the tiles archive -> FINAL $Out ---------- |
| 462 | # mamaps_build emits tiles only (no MAMA8 footer); the graph / transit / POI |
| 463 | # sections the app's router, departure boards and POI tags need are appended |
| 464 | # here. This is the step that turns a tiles-only archive into a complete pack. |
| 465 | $null = Switch-Phase "pack" |
| 466 | Write-Host "[6/7] Packing graph + POI + transit sidecars -> $(Split-Path $Out -Leaf)" |
| 467 | $packLog = Join-Path $tmp "pack.log" |
| 468 | if ($NoTransit) { |
| 469 | & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --out $Out | Tee-Object -FilePath $packLog |
| 470 | } else { |
| 471 | & $pack --tiles $tilesTmp --graph $graphDir --poi $poiDir --transit $WorldTransit --out $Out | Tee-Object -FilePath $packLog |
| 472 | } |
| 473 | if ($LASTEXITCODE -ne 0) { throw "mamaps_pack failed with exit code $LASTEXITCODE" } |
| 474 | |
| 475 | # --- [7/7] header check + report ------------------------------------------ |
| 476 | # The binary prints its own per-zoom table (`z0 ...`, `z1 ...`) plus the |
| 477 | # `classified ...` and `wrote ... build_id ...` lines. Parsed here rather than |
| 478 | # re-derived. |
| 479 | $null = Switch-Phase "verify" |
| 480 | # PS1-owned subphases: header dump, hash, and (under -Verify) the rebuild. |
| 481 | Switch-Subphase "header" | Out-Null |
| 482 | $logLines = Get-Content $log |
| 483 | $zooms = @() |
| 484 | foreach ($line in $logLines) { |
| 485 | # Per-zoom row: `z` + zoom, tiles, features, points, dropped, bytes, map/merge/enc/app seconds. |
| 486 | if ($line -match '^z(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)') { |
| 487 | $zooms += [pscustomobject]@{ |
| 488 | zoom = [int]$Matches[1]; tiles = [long]$Matches[2]; features = [long]$Matches[3] |
| 489 | points = [long]$Matches[4]; dropped = [long]$Matches[5]; bytes = [long]$Matches[6] |
| 490 | map_ms = [long]([double]$Matches[7] * 1000); merge_ms = [long]([double]$Matches[8] * 1000) |
| 491 | encode_ms = [long]([double]$Matches[9] * 1000); append_ms = [long]([double]$Matches[10] * 1000) |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | if ($zooms.Count -eq 0) { throw "no per-zoom rows parsed from $log -- the build printed no zN table" } |
| 496 | |
| 497 | $h = @{} |
| 498 | foreach ($line in (& $dump $Out --mode header)) { |
| 499 | $f = $line -split "`t" |
| 500 | if ($f.Count -ge 2) { $h[$f[0]] = $f[1] } |
| 501 | } |
| 502 | # The renderer skips its repair pass on the strength of this claim. |
| 503 | if ($h["rings_validated"] -ne "true") { throw "rings_validated is '$($h["rings_validated"])' -- the archive is unshippable" } |
| 504 | # Header plus dictionary plus root index inside 16 KiB, so a cold open is one |
| 505 | # range request and not two. |
| 506 | $prefix = [long]$h["prefix_bytes"] |
| 507 | if ($prefix -gt 16384) { throw "prefix is $prefix bytes of 16384 -- a cold open costs two requests" } |
| 508 | Write-Host "[7/7] Header ok: rings_validated true, prefix $prefix/16384 B, build_id $($h["build_id"])" |
| 509 | |
| 510 | Switch-Subphase "hash" | Out-Null |
| 511 | $sha = (Get-FileHash $Out -Algorithm SHA256).Hash |
| 512 | if ($Verify) { |
| 513 | # harden_mamaps.sh's full 1/3/32-thread matrix, folded in cheaply: one |
| 514 | # single-threaded rebuild must be byte-identical. A differing hash means an |
| 515 | # emit path whose order comes from a pool (e.g. a HashMap iterated on emit). |
| 516 | Write-Host "Verifying determinism: rebuilding at 1 thread + repacking" |
| 517 | Switch-Subphase "rebuild" | Out-Null |
| 518 | $verifyTiles = Join-Path $tmp "verify-tiles.mamaps" |
| 519 | $verifyOut = Join-Path $tmp "verify.mamaps" |
| 520 | $env:RAYON_NUM_THREADS = "1" |
| 521 | Remove-Item Env:MAPS_THREADS -ErrorAction SilentlyContinue |
| 522 | & $build --input $Pbf --out $verifyTiles ` |
| 523 | --coastline $Coastline ` |
| 524 | --graph $graphDir ` |
| 525 | --transit-routes $routes ` |
| 526 | --dem $Dem ` |
| 527 | --region $BuildRegion | Tee-Object -FilePath (Join-Path $tmp "verify.log") | Out-Null |
| 528 | if ($LASTEXITCODE -ne 0) { throw "verify rebuild failed with exit code $LASTEXITCODE" } |
| 529 | if ($NoTransit) { |
| 530 | & $pack --tiles $verifyTiles --graph $graphDir --poi $poiDir --out $verifyOut |
| 531 | } else { |
| 532 | & $pack --tiles $verifyTiles --graph $graphDir --poi $poiDir --transit $WorldTransit --out $verifyOut |
| 533 | } |
| 534 | if ($LASTEXITCODE -ne 0) { throw "verify pack failed with exit code $LASTEXITCODE" } |
| 535 | $vsha = (Get-FileHash $verifyOut -Algorithm SHA256).Hash |
| 536 | if ($vsha -ne $sha) { throw "determinism FAIL: 1-thread rebuild differs ($vsha vs $sha)" } |
| 537 | Write-Host " ok: 1-thread rebuild is byte-identical" |
| 538 | if ($Threads -gt 0) { $env:MAPS_THREADS = "$Threads" } |
| 539 | Remove-Item Env:RAYON_NUM_THREADS -ErrorAction SilentlyContinue |
| 540 | } |
| 541 | |
| 542 | $archive = (Get-Item $Out).Length |
| 543 | # Stop the chain: this instant ends "verify" and freezes TOTAL WALL. From |
| 544 | # here on the report only reads $script:PhaseTimes -- no more timing. |
| 545 | Stop-Phases |
| 546 | $total = $script:TotalSw.Elapsed.TotalSeconds |
| 547 | |
| 548 | # --- merge phase walls with Rust subphases -------------------------------- |
| 549 | # $rustSubs["phase"] = [ordered]@{ sub = seconds } from the last TIMING line |
| 550 | # in each phase log. The `other` row per phase is PS1 wall minus the named |
| 551 | # subphases (clamped at zero): it absorbs spawn/pipe overhead and the |
| 552 | # microseconds of skew between the two clocks, so rows always sum to the wall. |
| 553 | $rustSubs = @{} |
| 554 | foreach ($pair in @(@("graph", $graphLog), @("transit", $transitLog), @("tiles", $log), @("poi", $poiLog), @("pack", $packLog))) { |
| 555 | $parsed = Read-TimingLog $pair[1] |
| 556 | if ($null -ne $parsed.phase) { $rustSubs[$pair[0]] = $parsed.phase.subs } |
| 557 | if ($pair[0] -eq "tiles" -and $parsed.zooms.Count -gt 0) { $zooms = $parsed.zooms } |
| 558 | } |
| 559 | function Get-PhaseSubs([string] $phase) { |
| 560 | # Merged view: Rust subphases in emission order, PS1-owned subphases |
| 561 | # (tools builds, verify steps) in capture order, |
| 562 | # then the closing `other` bucket. Every row sums to the phase wall. |
| 563 | $merged = [ordered]@{} |
| 564 | if ($rustSubs.Contains($phase)) { |
| 565 | foreach ($k in $rustSubs[$phase].Keys) { $merged[$k] = $rustSubs[$phase][$k] } |
| 566 | } |
| 567 | foreach ($k in $script:SubTimes.Keys) { |
| 568 | if ($k.StartsWith("$phase/")) { |
| 569 | $sub = $k.Substring($phase.Length + 1) |
| 570 | if ($merged.Contains($sub)) { $merged[$sub] += $script:SubTimes[$k] } else { $merged[$sub] = $script:SubTimes[$k] } |
| 571 | } |
| 572 | } |
| 573 | $wall = $script:PhaseTimes[$phase] |
| 574 | if ($null -eq $wall) { $wall = 0.0 } |
| 575 | $named = 0.0 |
| 576 | foreach ($v in $merged.Values) { $named += $v } |
| 577 | $merged["other"] = [Math]::Max(0.0, $wall - $named) |
| 578 | return @{ wall = $wall; subs = $merged } |
| 579 | } |
| 580 | $phaseOrder = @("preflight", "tools", "graph", "transit", "tiles", "poi", "pack", "verify") |
| 581 | $phaseViews = [ordered]@{} |
| 582 | foreach ($name in $phaseOrder) { $phaseViews[$name] = Get-PhaseSubs $name } |
| 583 | |
| 584 | Write-Host "" |
| 585 | Write-Host "======================== RESULT ========================" |
| 586 | Write-Host "" |
| 587 | Write-Host "TIME" |
| 588 | foreach ($name in $phaseOrder) { |
| 589 | $view = $phaseViews[$name] |
| 590 | Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}%" -f $name, $view.wall, (100.0 * $view.wall / $total)) |
| 591 | foreach ($k in $view.subs.Keys) { |
| 592 | $t = $view.subs[$k] |
| 593 | if ($t -lt 0.05 -and $k -ne "other") { continue } |
| 594 | Write-Host (" {0,-24} {1,8:N1} s {2,5:N1}%" -f " $k", $t, (100.0 * $t / $total)) |
| 595 | } |
| 596 | } |
| 597 | Write-Host (" {0,-24} {1,8:N1} s" -f "TOTAL WALL", $total) |
| 598 | Write-Host "" |
| 599 | Write-Host "PER ZOOM" |
| 600 | Write-Host (" {0,-5}{1,12}{2,14}{3,16}{4,10}{5,9}{6,9}{7,9}" -f ` |
| 601 | "zoom", "tiles", "features", "body bytes", "map_s", "merge_s", "enc_s", "app_s") |
| 602 | foreach ($z in $zooms) { |
| 603 | Write-Host (" z{0,-4}{1,12:N0}{2,14:N0}{3,16:N0}{4,10:N1}{5,9:N1}{6,9:N1}{7,9:N1}" -f ` |
| 604 | $z.zoom, $z.tiles, $z.features, $z.bytes, |
| 605 | ($z.map_ms / 1000.0), ($z.merge_ms / 1000.0), ($z.encode_ms / 1000.0), ($z.append_ms / 1000.0)) |
| 606 | } |
| 607 | Write-Host "" |
| 608 | Write-Host "PEAK MEMORY" |
| 609 | Write-Host (" {0,-24} {1} kernel high-water, cannot be missed" -f "resident", (Size $peakWs)) |
| 610 | if ($anon) { |
| 611 | Write-Host (" {0,-24} {1} anon spill: no file; commit charge is in the pagefile" -f "feature spill, peak", "n/a") |
| 612 | } else { |
| 613 | Write-Host (" {0,-24} {1} scratch, deleted" -f "feature spill, peak", (Size $peakSpill)) |
| 614 | } |
| 615 | Write-Host "" |
| 616 | Write-Host (" archive {0} {1}" -f (Size $archive), $Out) |
| 617 | Write-Host (" build id {0,14}" -f $h["build_id"]) |
| 618 | Write-Host (" sha256 {0}" -f $sha) |
| 619 | |
| 620 | # timing.json beside the archive, before $tmp (and the phase logs) are |
| 621 | # deleted: the machine-readable twin of the TIME table above. Schema: |
| 622 | # { build_id, sha256, archive_bytes, total_wall_s, peak_rss_bytes, |
| 623 | # peak_spill_bytes, phases: [{ name, wall_s, subphases: [{name, s}] }], |
| 624 | # per_zoom: [{ zoom, tiles, features, points, dropped, bytes, |
| 625 | # map_s, merge_s, encode_s, append_s }] }. |
| 626 | $timingJson = [ordered]@{ |
| 627 | build_id = $h["build_id"]; sha256 = $sha; archive_bytes = $archive |
| 628 | total_wall_s = [Math]::Round($total, 3) |
| 629 | peak_rss_bytes = $peakWs; peak_spill_bytes = $peakSpill |
| 630 | region = $Region |
| 631 | phases = @() |
| 632 | per_zoom = @() |
| 633 | } |
| 634 | foreach ($name in $phaseOrder) { |
| 635 | $view = $phaseViews[$name] |
| 636 | $subs = @() |
| 637 | foreach ($k in $view.subs.Keys) { |
| 638 | $subs += [ordered]@{ name = $k; s = [Math]::Round($view.subs[$k], 3) } |
| 639 | } |
| 640 | $timingJson.phases += [ordered]@{ name = $name; wall_s = [Math]::Round($view.wall, 3); subphases = $subs } |
| 641 | } |
| 642 | foreach ($z in ($zooms | Sort-Object zoom)) { |
| 643 | $timingJson.per_zoom += [ordered]@{ |
| 644 | zoom = $z.zoom; tiles = $z.tiles; features = $z.features |
| 645 | points = $z.points; dropped = $z.dropped; bytes = $z.bytes |
| 646 | map_s = [Math]::Round($z.map_ms / 1000.0, 1); merge_s = [Math]::Round($z.merge_ms / 1000.0, 1) |
| 647 | encode_s = [Math]::Round($z.encode_ms / 1000.0, 1); append_s = [Math]::Round($z.append_ms / 1000.0, 1) |
| 648 | } |
| 649 | } |
| 650 | $timingPath = [System.IO.Path]::ChangeExtension($Out, "timing.json") |
| 651 | ($timingJson | ConvertTo-Json -Depth 6).Replace("`r`n", "`n") | Set-Content -Path $timingPath -NoNewline |
| 652 | Write-Host (" timing {0}" -f $timingPath) |
| 653 | |
| 654 | # Temp is always removed on success now (no -Keep): the graph/POI/routes/tiles |
| 655 | # intermediates are reproducible from the inputs, and anon spills vanish with |
| 656 | # the process. A failed build keeps $tmp as evidence (see the FAILED branch). |
| 657 | Remove-Item $tmp -Recurse -Force |
| 658 | Write-Host "" |