Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / README.md
| 1 | # osm_ingest |
| 2 | |
| 3 | Host-side Rust tools that turn an OpenStreetMap `.osm.pbf` extract into the |
| 4 | Maps app's offline artifacts. Three binaries share one library: |
| 5 | |
| 6 | | Binary | Replaces | Emits | |
| 7 | |---|---|---| |
| 8 | | `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `intermediate.bin`, `road_names.bin` | |
| 9 | | `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin`, `poi_attrs.bin`, `poi_spatial.bin`, `poi_name_index.bin` | |
| 10 | | `osm_extract` | `osmium tags-filter \| osmium export \| normalize_*.py` | one `<layer>.geojsonseq` per baked vector layer | |
| 11 | |
| 12 | ## Why Rust (LANGUAGE RULE) |
| 13 | |
| 14 | - **Rust-first:** the same rule that made `gtfs_ingest` Rust rather than Python, |
| 15 | and the router Rust rather than C++ (`maps/src/main/cpp/` is gone). These two |
| 16 | files were the last hand-written C++ in the Maps pipeline. |
| 17 | - **No libosmium, so no WSL.** The C++ needed `g++` + `libosmium2-dev` + |
| 18 | `-lz -lexpat -lbz2`, which do not exist on Windows, so regenerating a pack |
| 19 | meant dropping into WSL. `.osm.pbf` is read natively here: a hand-rolled |
| 20 | protobuf decoder (`src/proto.rs`, mirroring the encoder in |
| 21 | `maps/src/main/rust/src/mvt.rs`) over a pure-Rust inflate. |
| 22 | - **Offline builds:** the crate is detached from the repo-root Cargo workspace |
| 23 | (the empty `[workspace]` in `Cargo.toml`), like `gtfs_ingest`, so `cargo build` |
| 24 | never pulls the aarch64-android toolchain or the app crates' lints. The single |
| 25 | dependency, `miniz_oxide`, is a **decode-only** inflate crate — we never |
| 26 | compress — following the `ruzstd` precedent in |
| 27 | `networklocation/src/main/rust/Cargo.toml`. It is already in the local registry |
| 28 | cache because the app's maps crate pulls it via `flate2`. |
| 29 | - **Deterministic**, which the C++ was not. See below. |
| 30 | |
| 31 | ## Usage |
| 32 | |
| 33 | ```sh |
| 34 | # Routing graph -> map_data/ (the directory publish_r2.sh uploads to R2) |
| 35 | cargo run --release --bin road_graph -- california-latest.osm.pbf --out map_data |
| 36 | |
| 37 | # POI layer side files + the geojsonseq the tiler consumes |
| 38 | cargo run --release --bin poi_extract -- california-latest.osm.pbf \ |
| 39 | --geojson pois.geojsonseq --names poi_names.bin --index poi_index.bin \ |
| 40 | --attrs poi_attrs.bin \ |
| 41 | --spatial poi_spatial.bin \ |
| 42 | --name-index poi_name_index.bin |
| 43 | |
| 44 | # One baked vector layer, with the bbox clip done inline (no osmium extract) |
| 45 | cargo run --release --bin osm_extract -- california-latest.osm.pbf \ |
| 46 | --layer safety --out safety.geojsonseq --bbox -122.6,37.2,-121.7,37.9 |
| 47 | ``` |
| 48 | |
| 49 | `road_graph` takes two flags beyond `--out`, both about build-time memory rather |
| 50 | than output: |
| 51 | |
| 52 | ```sh |
| 53 | # Chains confined to one OSM way: no segment array, no incidence index. |
| 54 | cargo run --release --bin road_graph -- planet.osm.pbf --within-way-chains |
| 55 | |
| 56 | # Write the pack in 3 source-partitioned rounds instead of one. |
| 57 | cargo run --release --bin road_graph -- planet.osm.pbf --rounds 3 |
| 58 | |
| 59 | # Keep the chain spill off the output disk. `chains.pts` is the only file the |
| 60 | # build reads randomly, so it wants cheap seeks; the output only needs sequential |
| 61 | # writes and can go wherever there is room. |
| 62 | cargo run --release --bin road_graph -- planet.osm.pbf --spill-dir /fast/scratch |
| 63 | ``` |
| 64 | |
| 65 | Neither changes the on-disk contract, and `--rounds` does not change the output |
| 66 | at all — a test asserts every byte is identical across `--rounds 1`, `4` and |
| 67 | `17`. See [Build-time memory](#build-time-memory). |
| 68 | |
| 69 | From Windows, `scripts/maps/build_graph.ps1` builds the full `.mamaps` archive |
| 70 | end to end (road graph, transit routes, tiling, header checks) in one command. |
| 71 | |
| 72 | ## `osm_extract` and the vector layers |
| 73 | |
| 74 | One 3-pass driver ([`src/extract.rs`](src/extract.rs)) for every baked layer, |
| 75 | with each layer's schema in its own module. Supported today: `safety` |
| 76 | ([`src/safety.rs`](src/safety.rs)). |
| 77 | |
| 78 | Three pieces are shared: |
| 79 | |
| 80 | * [`src/geojson.rs`](src/geojson.rs) — the writer. Reproduces |
| 81 | `json.dumps(..., separators=(",", ":"), ensure_ascii=False)`: no whitespace, |
| 82 | fixed key order, UTF-8 passthrough. |
| 83 | * [`src/bbox.rs`](src/bbox.rs) — the `osmium extract -b` equivalent, reproducing |
| 84 | osmium's `complete_ways` strategy (any vertex inside keeps the whole element). |
| 85 | Containment is compared in 1e-7 **integers**, not degrees, because |
| 86 | `-1_226_000_000 * 1e-7` lands a hair west of `-122.6` and would drop a node |
| 87 | sitting exactly on its own box edge. |
| 88 | * [`src/select.rs`](src/select.rs) — the `osmium tags-filter` equivalent, as a |
| 89 | cheap pre-filter. Tag lookup is a linear scan, so screening on three keys |
| 90 | before the classifier reads ten is worth doing at planet scale. |
| 91 | |
| 92 | ### Pass ordering |
| 93 | |
| 94 | A PBF stores nodes before the ways that reference them, so any layer needing way |
| 95 | or relation geometry has to traverse **relations, then ways, then nodes** — |
| 96 | relations decide which ways matter, ways decide which node coordinates matter, |
| 97 | nodes supply them. Only the passes a layer needs are run; `safety` is node-based, |
| 98 | so it runs one. |
| 99 | |
| 100 | When the way and relation layers land, their node coordinates must be stored the |
| 101 | way `poi_build.rs` does it — a sorted `Vec` of needed ids plus an index-aligned |
| 102 | coordinate array, looked up by `binary_search`, 16 bytes per *needed* node — and |
| 103 | **not** the way `graph_build.rs` does it. That module's bitset is sized from |
| 104 | `BITSET_SIZE = 20e9`, i.e. 2.5 GB keyed by raw node id, and peaks around 10 GB on |
| 105 | California. |
| 106 | |
| 107 | ### The port rules, pinned by tests in `src/safety.rs` |
| 108 | |
| 109 | The Python normalisers (`normalize_*.py`) were the contract of record during the |
| 110 | port and have since been deleted with the legacy `--engine legacy` scripts and |
| 111 | the differential harness. What remains are the two rules easiest to break, |
| 112 | pinned by tests in `src/safety.rs`: |
| 113 | |
| 114 | * `enforcement=maxspeed` is checked **before** the `man_made=surveillance` |
| 115 | branch. A camera tagged both ways is a speed camera, and swapping the order |
| 116 | silently reclassifies every enforcement camera. |
| 117 | * The ALPR heuristic is **asymmetric**: `surveillance:type` matches by substring |
| 118 | (real values include `ALPR;camera`), `camera:type` matches by exact equality |
| 119 | (it is an enumerated field, and a substring rule would corrupt it), and |
| 120 | `operator`/`manufacturer` match `flock` by substring. |
| 121 | |
| 122 | ## Output contracts |
| 123 | |
| 124 | Every layout below is read by code elsewhere in the repo. Changing one without |
| 125 | changing its reader produces a graph that loads as garbage, which is why |
| 126 | `metadata.bin` carries a magic and version. |
| 127 | |
| 128 | | File | Layout | Reader | |
| 129 | |---|---|---| |
| 130 | | `metadata.bin` | `u32 magic "MARG"`, `u32 version 5`, `u64 node_count`, `u64 edge_count`, `u64 escape_count` (32 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` | |
| 131 | | `nodes.bin` | `NodeRec[node_count + 1]`, **12 bytes**: `i32 lat_e7, i32 lon_e7, u32 edge_ptr`; Morton-sorted, trailing sentinel whose `edge_ptr == edge_count` | `graph.rs` — widened into `NodeMaster` by `node()` | |
| 132 | | `edges.bin` | `EdgeRec[edge_count]`, **11 bytes**: `i16 target_delta, u24 dist_mm, u8 type, u8 speed_limit, u32 name_offset`; then padding to an 8-byte boundary, `u32 escape_first[E.div_ceil(1024) + 1]`, and `(u32 edge_idx, u32 target, u32 dist_mm) × escape_count` ascending by `edge_idx` | `graph.rs` — widened into `Edge` by `edge(source, idx)`; `name_offset` reached only through `edge_name_offset()` | |
| 133 | | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) × (n + 1)` ascending by `edge_idx`, then the packed `u16` per-lane turn masks. **Sparse**: only lane-bearing edges appear | `graph.rs` `edge_lane_masks` | |
| 134 | | `intermediate.bin` | the delta-encoded polyline blob at **offset 0** — per storing edge, `i16 dlat, i16 dlon` per *interior* point — then a trailer: `u64 rank[E.div_ceil(512) + 1]`, `u8 present[E.div_ceil(8)]`, `u64 coarse[G.div_ceil(32) + 1]`, `u16 within[G + 1]`, `u64 G`. `off(g) = coarse[g / 32] + within[g]` where `g = rank(k)` | `graph.rs` `intermediate_range` / `decode_edge_coords` — **mandatory**, see below | |
| 135 | | `road_names.bin` | deduped NUL-terminated UTF-8 pool; a name offset is a byte offset | `graph.rs` | |
| 136 | | `poi_index.bin` | 14-byte records: `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type`, Morton-sorted | `PoiIndex.kt` | |
| 137 | | `poi_names.bin` | same pool convention as `road_names.bin` | `PoiIndex.kt` | |
| 138 | | `poi_attrs.bin` | attribute sidecar keyed by `poi_index.bin` record ordinal; layout in `src/poi_attrs.rs` | `PoiIndex.kt` | |
| 139 | | `poi_spatial.bin` | sparse CSR lat/lon grid over record ordinals, so a bbox query is cell-local; layout in `src/poi_side.rs` | `PoiIndex.kt` | |
| 140 | | `poi_name_index.bin` | one `(record, word)` entry per word of every name, sorted by word; layout in `src/poi_side.rs` | `PoiIndex.kt` | |
| 141 | |
| 142 | `GRAPH_VERSION` is **5**. Version 1 stored a 16-byte node record and a dense |
| 143 | `u64` offset per edge in both blob files; version 2 fixed that, and version 3 gave |
| 144 | `intermediate.bin` a presence bitmap and dropped both endpoints of every stored |
| 145 | polyline. See [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and |
| 146 | [Getting it under 30](#getting-it-under-30) for what each cost and what replaced |
| 147 | it. There is no dual-path reader — an older pack is rejected — so the app and the |
| 148 | pack have to be updated together, as they already did across the v0→v1 boundary. |
| 149 | |
| 150 | Versions 4 and 5 are the next step down, to ~25.8 GB; see |
| 151 | [Getting it under 25](#getting-it-under-25-what-the-census-says). Version 4 changes |
| 152 | **no layout at all**. It adds `edge_count` to `metadata.bin`, so that the reader |
| 153 | stops deriving it from `edges.bin`'s file size, and with it |
| 154 | [exact length validation](#every-files-length-is-checked) of every other file. |
| 155 | That has to land before any record narrows: the moment the stride changes, a |
| 156 | derived `edge_count` changes silently — and it is what sizes `intermediate.bin`'s |
| 157 | trailer, so the mis-parse would be of a *different file*. |
| 158 | |
| 159 | Version 5 is the narrowing itself. |
| 160 | |
| 161 | ### Every file's length is checked |
| 162 | |
| 163 | Every mandatory file's length is now an exact function of the two counts in |
| 164 | `metadata.bin`, and `Graph::load` checks each one: |
| 165 | |
| 166 | | File | Expected length | |
| 167 | |---|---| |
| 168 | | `metadata.bin` | ≥ 32 B, with the right magic and version | |
| 169 | | `nodes.bin` | exactly `(node_count + 1) × 12` | |
| 170 | | `edges.bin` | exactly `align_up(edge_count × 11, 8) + (E.div_ceil(1024) + 1) × 4 + escape_count × 12`, with the block index's last entry equal to `escape_count` and every row's `edge_idx < edge_count` | |
| 171 | | `lanes.bin` | exactly `4 + (n + 1) × 8 + blob`, from its own header, plus every `edge_idx < edge_count` | |
| 172 | | `intermediate.bin` | trailer sized from `edge_count` and `G`, with `coarse[G/32] + within[G] == ` the blob length | |
| 173 | |
| 174 | Exactly, not "at least": a file that is too long is as much a vintage mismatch as |
| 175 | one that is too short, and one comparison catches both. `nodes.bin`'s length used |
| 176 | not to be checked at all — `node()` documents that callers guarantee |
| 177 | `id <= node_count` and does no bounds test — so a stale or truncated file read |
| 178 | straight past the mapping. `road_names.bin` is the one exception: it is a byte pool |
| 179 | with no count of its own, and `road_name()` bounds each read against its size |
| 180 | instead. |
| 181 | |
| 182 | Together these catch what a matching version field cannot. The version lives in |
| 183 | `metadata.bin` while the layouts live in `nodes.bin` and `edges.bin`, so a pack |
| 184 | directory assembled from two builds of the *same* version is invisible to it and |
| 185 | obvious to the lengths. |
| 186 | |
| 187 | The POI Morton sort key is computed from the *stored* `lat_e7`/`lon_e7`, not from |
| 188 | the pre-rounding `f64` centroid the C++ used, so the order matches the key a |
| 189 | reader recomputes from the file. On California that removed 9 ordering |
| 190 | inversions the old tool produced. |
| 191 | |
| 192 | The POI type numbers live in `src/tags.rs` and are also tabulated in |
| 193 | `scripts/maps/README.md`. **Never renumber an existing type — only append.** |
| 194 | |
| 195 | ## Compaction and `intermediate.bin` |
| 196 | |
| 197 | `road_graph` collapses degree-2 chains: a run of nodes that each have exactly two |
| 198 | neighbours becomes a single edge whose polyline lives in `intermediate.bin`. This |
| 199 | is in `src/compact.rs`, and the encoder is `src/geom.rs`. |
| 200 | |
| 201 | Before compaction there was one edge per consecutive pair of way nodes, so every |
| 202 | geometry vertex was a routing node. Measured on California: |
| 203 | |
| 204 | | | uncompacted | compacted | |
| 205 | |---|---|---| |
| 206 | | nodes | 35,857,253 | 6,416,947 (5.59x fewer) | |
| 207 | | directed edges | 74,340,356 | 16,781,727 (4.43x fewer) | |
| 208 | | `nodes.bin` | 573.7 MB | 102.7 MB | |
| 209 | | `edges.bin` | 1040.8 MB | 234.9 MB | |
| 210 | | `lanes.bin` | 597.1 MB | 135.5 MB | |
| 211 | | `intermediate.bin` | — | 314.1 MB | |
| 212 | | **total** | **2.22 GB** | **0.79 GB (2.8x smaller)** | |
| 213 | |
| 214 | Both columns are **v1** layouts. See |
| 215 | [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and |
| 216 | [Getting it under 30](#getting-it-under-30) for what v2 and v3 do to the |
| 217 | `nodes.bin`, `lanes.bin` and `intermediate.bin` rows. |
| 218 | |
| 219 | Those nodes bought nothing: no route ever chose anything at them. What they did |
| 220 | buy was the road's shape, which is why removing them requires storing geometry. |
| 221 | |
| 222 | ### The file is mandatory |
| 223 | |
| 224 | `Graph::load` refuses a pack directory without it. Once an edge is a whole road |
| 225 | between junctions, its polyline is the only record of that road's shape; |
| 226 | `find_nearest_edge` would otherwise project a query onto a straight chord |
| 227 | spanning an entire street, so snapping *and* drawn geometry would be wrong rather |
| 228 | than merely coarse. It is also in `MainActivity.kt`'s download list, and adding |
| 229 | it there makes `InitialDownloader`'s `allFilesPresent` false for any install that |
| 230 | predates it, which re-triggers the download. |
| 231 | |
| 232 | ### Three encoding rules, all enforced by assertion |
| 233 | |
| 234 | All three come from `decode_edge_coords`: |
| 235 | |
| 236 | 1. **At most 256 points per edge**, endpoints included. The decode loop stops |
| 237 | there and its callers allocate exactly `[LatLon; 256]`, so a longer polyline |
| 238 | would be silently truncated. `compact.rs` splits a chain that would exceed the |
| 239 | budget, promoting the cut node back to a real node (4,983 splits on |
| 240 | California). The largest legal blob is therefore `4 × 254` = 1016 bytes. |
| 241 | 2. **Deltas are `i16`.** Consecutive points must be within 32,767 units |
| 242 | (~364 m of latitude) on each axis, and the reader uses `wrapping_add`, so an |
| 243 | overflow would corrupt silently rather than fail. Where a real gap is larger, |
| 244 | `geom.rs` inserts **collinear** points on the straight line between the pair: |
| 245 | the geometry is unchanged and each costs 4 bytes. |
| 246 | 3. **A chain must begin and end on its own nodes' coordinates.** Only the |
| 247 | interior is stored, so the reader rebuilds both ends out of `nodes.bin`. This |
| 248 | was always true by construction — both come from the same coordinate array — |
| 249 | but the reader now depends on it, so `assert_endpoints` checks it per stored |
| 250 | edge rather than letting a wrong polyline reach a phone. |
| 251 | |
| 252 | An edge whose polyline is just the chord between its own endpoints stores nothing |
| 253 | and is simply absent from the presence bitmap, which is also the escape hatch for |
| 254 | a single hop too long to delta-encode at all. |
| 255 | |
| 256 | ### `REVERSE_GEOMETRY_FLAG` |
| 257 | |
| 258 | Only one edge of a bidirectional pair stores the polyline. The other sets bit |
| 259 | `0x40` in its `type_` byte, and the reader finds the twin by scanning the |
| 260 | *target's* edge range for the first edge pointing back at the source. That halves |
| 261 | the blob, and imposes two obligations on the generator: |
| 262 | |
| 263 | * **Set it only when the twin is unambiguous.** With two parallel roads between |
| 264 | the same pair of nodes, the reader's "first edge back" could resolve to the |
| 265 | wrong one, so `twin_is_unique` checks there is exactly one, and both polylines |
| 266 | are stored when there is not. |
| 267 | * **`type_` is a bitfield, not an enum.** Bits 0-5 are the road class, bit 6 is |
| 268 | this flag. `geometry.rs::ROAD_TYPE_MASK` is the reader's half of that contract; |
| 269 | it used to be `0x7F`, which let the flag through into `is_mode_allowed`'s range |
| 270 | checks and so rejected every flagged edge for every travel mode — silently |
| 271 | deleting half the road network. |
| 272 | |
| 273 | ### What compaction may not collapse |
| 274 | |
| 275 | `compact.rs::classify` requires all of: exactly two incident segments to two |
| 276 | distinct neighbours; agreement on road type, speed limit, name and |
| 277 | one-way-ness; lane masks equal **per traversed direction**, compared by content |
| 278 | rather than by pool offset since two ways intern identical masks at different |
| 279 | offsets; one-way segments actually flowing through the node rather than into it; |
| 280 | and no transit stop code, because isolated-stop reconnection addresses stop nodes |
| 281 | directly. |
| 282 | |
| 283 | A ring road whose every node qualifies has no anchor to start from. Its |
| 284 | lowest-numbered node is kept, so the ring becomes one edge from that node to |
| 285 | itself. |
| 286 | |
| 287 | A one-way chain is emitted along its traffic flow, not along whichever end the |
| 288 | walk happened to start from. |
| 289 | |
| 290 | ## Getting a planet under 40 GB |
| 291 | |
| 292 | The output format the planet build inherited projected to **50.8 GB**, against a |
| 293 | 40 GB target, and two thirds of that was offset tables describing edges that had |
| 294 | nothing to describe. Version 2 is the clean break that fixes it — no dual-path |
| 295 | reader, no downloader change, since nothing had shipped from a v1 pack. |
| 296 | |
| 297 | | file | v1 | v2 | basis | |
| 298 | |---|---|---|---| |
| 299 | | `metadata.bin` | 16 B | 16 B | unchanged | |
| 300 | | `nodes.bin` | 6.90 GB | **5.18 GB** | 12 B × (N+1) | |
| 301 | | `edges.bin` | 15.04 GB | 15.04 GB | unchanged | |
| 302 | | `lanes.bin` | 8.60 GB | **0.04 GB** | sparse index | |
| 303 | | `intermediate.bin` | 20.02 GB | **13.86 GB** | two-level offsets | |
| 304 | | `road_names.bin` | 0.25 GB | 0.25 GB | unchanged | |
| 305 | | **total** | **50.8 GB** | **~34.4 GB** | 5.6 GB under target | |
| 306 | |
| 307 | Projected from the measured planet counts: 431,474,933 surviving nodes, |
| 308 | 1,074,282,569 directed edges, 552,689,139 chains. **Measured on California the same |
| 309 | change is −32.1%** (see [below](#measured-on-california-v1-vs-v2)), against the |
| 310 | −32.3% this table projects, which is the closest thing to a check on it short of |
| 311 | running the planet again. |
| 312 | |
| 313 | **`lanes.bin`: a sparse index.** `turn:lanes` is rare — about 2.9 M of a planet's |
| 314 | 1.07 G directed edges carry any — so a dense `u64` per edge meant 99.8% of an |
| 315 | 8.60 GB file described edges with no lanes at all. Only the lane-bearing edges are |
| 316 | listed now, as `(u32 edge_idx, u32 blob_byte_off)` pairs ascending by edge index, |
| 317 | and `edge_lane_masks` binary-searches instead of indexing. It is called once per |
| 318 | maneuver rather than once per edge, so ~22 probes is free. "This edge has no |
| 319 | lanes" is now spelled by absence from the index rather than by an empty range, and |
| 320 | it resolves to the same `None` the topology-inference fallback in `routing.rs` |
| 321 | already handles. |
| 322 | |
| 323 | **`intermediate.bin`: two-level offsets.** A per-edge blob was at most 1028 bytes — |
| 324 | 8 for the absolute first point plus 4 per delta, capped at 256 points by the |
| 325 | reader — so six of every eight offset bytes were always zero. v2 replaced the dense |
| 326 | `u64` with a `u64` per 32 edges plus a `u16` within the block, `off(k) = |
| 327 | coarse[k / 32] + within_block[k]`. The block size of 32 is what makes the narrow |
| 328 | half safe: a block spanned at most 32 × 1028 = 32,896 bytes, comfortably inside a |
| 329 | `u16`. That bound is `geom::MAX_POINTS` / `geom::fits` and the chain splitting in |
| 330 | the collapse pass; it is the invariant the whole scheme rests on, so the writer |
| 331 | asserts it and a test pins it at a chain of exactly 256 points. v3 keeps the two |
| 332 | levels but keys them on geometry edges and drops both endpoints, which tightens the |
| 333 | per-blob bound to 1016 bytes — see [Getting it under 30](#getting-it-under-30). |
| 334 | |
| 335 | **`nodes.bin`: `edge_ptr` as a `u32`.** 1.07 G edges leave 4× of headroom, so the |
| 336 | record is 12 bytes instead of 16. It is an on-disk `NodeRec` that `node()` widens |
| 337 | into the existing `NodeMaster`, whose `edge_ptr` stays a `u64`, so nothing outside |
| 338 | `graph.rs` sees the change. The generator gained a `cap_u32` guard on the edge |
| 339 | count for it — the same idiom already used for node, survivor and chain counts — |
| 340 | because this is the change that would let a wrapped edge count silently address |
| 341 | another node's edge range. |
| 342 | |
| 343 | `edges.bin` is left alone deliberately. Its 14 bytes are `u32 target`, |
| 344 | `u32 dist_mm`, `u32 name_offset`, `u8 type_`, `u8 speed_limit`: `dist_mm` holds a |
| 345 | whole collapsed road so it needs the range, `name_offset` addresses a 250 MB pool, |
| 346 | and `type_` is a bitfield with exactly one spare bit and a history of a masking |
| 347 | error deleting half the road network. |
| 348 | |
| 349 | ### Stop reconnection is about component *size*, not the largest component |
| 350 | |
| 351 | The other thing only a planet could show. `reconnect_isolated_stops` used to find |
| 352 | the largest connected component and hook every stop outside it to its nearest node |
| 353 | inside it. On a region that is right — the largest component is 98.2% of |
| 354 | California, 93.8% of Europe. On a planet it is Eurasia-plus-Africa at **57.7%**, |
| 355 | because continents are not road-connected, so every stop in the Americas, |
| 356 | Australia, Japan, the UK and Indonesia was classified as isolated and the code |
| 357 | tried to bridge an ocean to reach a road in France. It failed **1,173,347** times, |
| 358 | a quarter of all stops, paying for a widening search out to a million-node index |
| 359 | window before each failure. |
| 360 | |
| 361 | The question worth asking is *"is this stop attached to a real road network?"*, |
| 362 | not *"is it attached to the biggest one?"*. So the BFS keeps a size per component |
| 363 | instead of discarding all but the largest, a stop needs reconnecting only when its |
| 364 | own component is below `MIN_ROUTABLE_COMPONENT` (1000 nodes), and the target is the |
| 365 | nearest node in **any** component at or above that threshold. A stop alone on an |
| 366 | untagged node is a component of size 1 and is still connected; a stop on a small |
| 367 | island's road network is left alone, because it is already as reachable as that |
| 368 | island gets; a stop in North America connects to North America. |
| 369 | |
| 370 | That removes the pathology rather than its symptom: a qualifying node is now |
| 371 | metres away instead of an ocean away, so the widening search almost always |
| 372 | succeeds on its first 1000-node window. |
| 373 | |
| 374 | The threshold is capped at the largest component that actually exists, because a |
| 375 | graph with no component of 1000 nodes still has a road network — it is just a |
| 376 | small one — and requiring a size nothing reaches would reconnect nothing. That is |
| 377 | also what keeps the fixtures in `graph_build.rs`, whose whole graph is four nodes, |
| 378 | reconnecting against their own three-node road. |
| 379 | |
| 380 | `MIN_ROUTABLE_COMPONENT` wants a measured value rather than a guess, so every |
| 381 | build reports the three counts that make the choice auditable: stops left alone as |
| 382 | already-connected, stops reconnected, and stops that still found nothing. The last |
| 383 | one is the number that decides whether the threshold is right — on a planet it |
| 384 | should collapse from 1,173,347 toward zero. |
| 385 | |
| 386 | ### Measured on California, v1 vs v2 |
| 387 | |
| 388 | `california-latest.osm.pbf`, 1.26 GB, both collapse paths, same machine and same |
| 389 | input as the v1 numbers above. |
| 390 | |
| 391 | | | reference v1 | reference v2 | within-way v1 | within-way v2 | |
| 392 | |---|---|---|---|---| |
| 393 | | `metadata.bin` | 16 | 16 | 16 | 16 | |
| 394 | | `nodes.bin` | 102,693,792 | **77,020,344** | 113,583,040 | **85,187,280** | |
| 395 | | `edges.bin` | 234,999,884 | 234,999,828 | 252,469,686 | 252,469,630 | |
| 396 | | `lanes.bin` | 135,575,036 | **3,013,792** | 145,815,866 | **3,563,182** | |
| 397 | | `intermediate.bin` | 314,211,280 | **217,693,470** | 318,945,504 | **215,252,596** | |
| 398 | | `road_names.bin` | 5,481,848 | 5,481,848 | 5,481,848 | 5,481,848 | |
| 399 | | **total** | **792,961,856** | **538,209,298** | **836,295,960** | **561,954,552** | |
| 400 | | | | **−32.1%** | | **−32.8%** | |
| 401 | |
| 402 | Every byte of that is accounted for, which is what makes it a check rather than a |
| 403 | result: |
| 404 | |
| 405 | * `nodes.bin` is exactly `(6,418,361 + 1) × 12` against `× 16`. |
| 406 | * `lanes.bin`'s mask blob is **byte-identical** at 1,289,380 bytes; what went was |
| 407 | the 134,285,656-byte dense table, replaced by a 1,724,408-byte index over the |
| 408 | 215,550 edges (**1.28%**) that actually carry `turn:lanes`. |
| 409 | * `intermediate.bin` fell by 96,517,810 bytes, which is precisely the dense |
| 410 | `(E+1) × 8` table minus the new `coarse` + `within_block` pair. The polyline blob |
| 411 | is untouched. |
| 412 | * `edges.bin` lost 56 bytes = 4 edges × 14, and those four edges are the stop |
| 413 | change below, not a format change. |
| 414 | |
| 415 | **Stop reconnection, both paths identically:** 81,553 stops → **20,836 already on |
| 416 | a routable component, 60,717 reconnected, 0 found nothing**. The v1 rule |
| 417 | reconnected 60,719, so the reconnected count moved by two pairs — which is the |
| 418 | whole of the `edges.bin` delta. California's largest component is 98.24% of |
| 419 | 6,418,361 nodes across 76,081 components, so almost nothing sits in a mid-sized |
| 420 | non-largest component and the two rules were always going to agree here. That is |
| 421 | exactly why the rule had to be fixed against a planet instead. |
| 422 | |
| 423 | `route_diff` reference-vs-within reports **34,900** baseline vertices missing from |
| 424 | the candidate and a worst-case route delta of **−1.49 km** — both unchanged from |
| 425 | the v1-era measurements below, which is the evidence that the format change is |
| 426 | semantically inert. A true v1-vs-v2 `route_diff` is not possible by construction: |
| 427 | the reader accepts one version, which is the price of the clean break. |
| 428 | |
| 429 | **`--rounds 1` vs `3` vs `17` is byte-identical on all six files, on both collapse |
| 430 | paths.** That is the strongest check either new offset scheme gets: round |
| 431 | boundaries move which edges each pass collects, which coarse block it is filling, |
| 432 | which within-block offsets it appends, where `lanes.bin`'s sparse index resumes and |
| 433 | where `nodes.bin`'s running edge counter picks up — and none of it reaches the file. |
| 434 | |
| 435 | ## Getting it under 30 |
| 436 | |
| 437 | v2 left the pack at ~34.4 GB against a 40 GB target, and the next question was |
| 438 | whether 25 GB is reachable. Five candidate changes were priced against measured |
| 439 | Europe and planet counts; the three cheapest and least risky are all in |
| 440 | `intermediate.bin`, and version 3 is those three: |
| 441 | |
| 442 | | projected saving | change | |
| 443 | |---|---| |
| 444 | | −2.54 GB | drop the absolute first point — it is always the source node | |
| 445 | | −1.55 GB | a presence bitmap instead of a per-edge offset | |
| 446 | | −1.27 GB | drop the last point — it is always the target node | |
| 447 | |
| 448 | That takes `intermediate.bin` from 13.86 GB to **~8.50 GB** and the pack to |
| 449 | **~29.0 GB**: |
| 450 | |
| 451 | | file | v1 | v2 | v3 | basis | |
| 452 | |---|---|---|---|---| |
| 453 | | `metadata.bin` | 16 B | 16 B | 16 B | unchanged | |
| 454 | | `nodes.bin` | 6.90 GB | 5.18 GB | 5.18 GB | unchanged since v2 | |
| 455 | | `edges.bin` | 15.04 GB | 15.04 GB | 15.04 GB | unchanged | |
| 456 | | `lanes.bin` | 8.60 GB | 0.04 GB | 0.04 GB | unchanged since v2 | |
| 457 | | `intermediate.bin` | 20.02 GB | 13.86 GB | **8.50 GB** | bitmap + dropped endpoints | |
| 458 | | `road_names.bin` | 0.25 GB | 0.25 GB | 0.25 GB | unchanged | |
| 459 | | **total** | **50.8 GB** | **~34.4 GB** | **~29.0 GB** | **−15.7%** on v2, −42.9% on v1 | |
| 460 | |
| 461 | Projected from the same measured planet counts as the v2 table — 431,474,933 |
| 462 | surviving nodes, 1,074,282,569 directed edges — with `G`, the number of edges that |
| 463 | store a polyline, projected from Europe's measured 110,807,665 of 374,856,290 |
| 464 | (29.56%) at **~317.6 M**. Every row of the v3 column is arithmetic on those two |
| 465 | numbers: the blob loses `12 × G` = 3.81 GB, and the tables go from |
| 466 | `coarse` 0.27 GB + `within` 2.15 GB = **2.42 GB** to `rank` 17 MB + `present` |
| 467 | 134 MB + `coarse` 79 MB + `within` 635 MB = **0.87 GB**. |
| 468 | |
| 469 | The two dropped endpoints are pure redundancy removal: the test |
| 470 | `intermediate_bin_reproduces_the_collapsed_geometry` already asserted that a stored |
| 471 | polyline starts at its edge's source and ends at its target, so both were already |
| 472 | known to be recoverable from `nodes.bin`. The bitmap follows from the 70.4% of |
| 473 | edges that store no polyline at all, each of which still owned a `u16` and a |
| 474 | repeated coarse `u64` under v2. |
| 475 | |
| 476 | Two further changes were priced and **rejected for now**, and they are what the |
| 477 | remaining 3.5 GB to a 25.5 GB pack would have to come from: `dist_mm → u24` |
| 478 | centimetres (−1.07 GB) needs an escape hatch for chains over 167 km and moves every |
| 479 | route cost, and delta-coded `nodes.bin` coordinates (−2.4 GB) put a decode step on |
| 480 | the router's hottest read and must handle Morton quadrant boundaries. Neither is |
| 481 | worth it for a pack already 11 GB under the original target. |
| 482 | |
| 483 | **The California measurement checks the arithmetic, not the ratio.** Feeding |
| 484 | California's own counts — E = 16,785,702, G = 4,494,428 — through the same formula |
| 485 | predicts a 79,227,999-byte fall, and the file fell by exactly that (see |
| 486 | [below](#measured-on-california-v2-vs-v3)). The *percentage* differs from the |
| 487 | planet's projected −38.7%, at −36.4%, because California stores a polyline on only |
| 488 | 26.8% of its edges against Europe's 29.6% and its mean polyline is shorter: a lower |
| 489 | `G / E` means less endpoint saving per byte of blob. That is a property of the |
| 490 | region, not a disagreement with the model. |
| 491 | |
| 492 | **The layout, and why the tables come last.** |
| 493 | |
| 494 | ```text |
| 495 | [ blob ] |
| 496 | [ u64 rank[E.div_ceil(512) + 1] ] set bits before each 64-byte block, total appended |
| 497 | [ u8 present[E.div_ceil(8)] ] one bit per directed edge |
| 498 | [ u64 coarse[G.div_ceil(32) + 1] ] G = geometry edges = rank[last] |
| 499 | [ u16 within[G + 1] ] |
| 500 | [ u64 G ] fixed-size trailer |
| 501 | ``` |
| 502 | |
| 503 | `G` is not known until the final round has run, so a reserved prefix cannot be |
| 504 | sized — the same problem `lanes.bin` has. `LaneFile` solves it by streaming its |
| 505 | blob to scratch and copying it back, which is free for 13 MB but would be ~23 GB |
| 506 | of extra I/O for this blob. A trailer instead makes the whole file **append-only |
| 507 | with no scratch file at all**, which is strictly less I/O than v2, where |
| 508 | `BlobFile` copied a 2.4 GB prefix back. The four tables are held in memory while |
| 509 | the blob streams: 0.87 GB at planet scale, against v2's 2.42 GB *on disk*. |
| 510 | |
| 511 | The reader recovers everything from the last 8 bytes plus `edges.bin`'s file size, |
| 512 | and validates more than v2 did: the file must hold all four tables plus the |
| 513 | trailer, the `coarse`/`within` sentinel must equal the remaining blob region |
| 514 | exactly, and `rank`'s total must equal `G`. |
| 515 | |
| 516 | **The offsets are keyed on geometry edges, not edges.** `off(g) = coarse[g / 32] + |
| 517 | within[g]` where `g = rank(k)`, so an edge's polyline is found by testing its |
| 518 | presence bit and then ranking below it — one `u64` load plus at most 64 bytes of |
| 519 | `popcount`. This *tightens* the `u16` bound rather than loosening it: a per-edge |
| 520 | blob is now at most `4 × (256 − 2)` = 1016 bytes, a block of 32 spans at most |
| 521 | 32,512, and every entry in a block is a real blob where before most were |
| 522 | zero-length. |
| 523 | |
| 524 | **The encoding.** A stored polyline is `Q0 .. Q(m-1)` with `Q0` the source node's |
| 525 | coordinates and `Q(m-1)` the target's. Only the interior deltas are stored: `m − 2` |
| 526 | pairs of `i16`, omitting both the 8-byte absolute `Q0` and the final delta that |
| 527 | lands on `Q(m-1)`. So bytes = `4 × (m − 2)`, the saving is exactly 12 per stored |
| 528 | edge, and `m = byte_len / 4 + 2`. An empty blob decodes to `[source, target]` — the |
| 529 | chord — which is why "no interior" and "the chord" are now the same statement, and |
| 530 | why presence needs a bit rather than a length. Interpolation is unaffected: |
| 531 | `geom::interp_steps` still decides how many steps a hop takes and only the *final* |
| 532 | step is the one omitted. |
| 533 | |
| 534 | **The reader API.** `decode_edge_coords` now needs the edge's endpoints, so |
| 535 | `Graph::get_edge_coordinates_from(source, edge_idx, out)` is the real entry point |
| 536 | and `get_edge_coordinates(edge_idx, out)` is a wrapper that recovers the source via |
| 537 | `find_node_idx_for_edge`. All six `routing.rs` call sites pass the source they |
| 538 | already hold; that is not polish, because otherwise the wrapper's ~29-probe binary |
| 539 | search lands inside `find_nearest_edge`'s candidate loop, which runs over a |
| 540 | 1601-node window twice per route and up to 16 times per transit plan. As a bonus it |
| 541 | *removes* the `find_node_idx_for_edge` call the reverse-geometry path used to make |
| 542 | per reversed edge, purely to recover a value the caller already had. |
| 543 | |
| 544 | ### Measured on California, v2 vs v3 |
| 545 | |
| 546 | `california-latest.osm.pbf`, 1.26 GB, both collapse paths, same machine and input |
| 547 | as the tables above. Only `intermediate.bin` moves. |
| 548 | |
| 549 | | | reference v2 | reference v3 | within-way v2 | within-way v3 | |
| 550 | |---|---|---|---|---| |
| 551 | | `metadata.bin` | 16 | 16 | 16 | 16 | |
| 552 | | `nodes.bin` | 77,020,344 | 77,020,344 | 85,187,280 | 85,187,280 | |
| 553 | | `edges.bin` | 234,999,828 | 234,999,828 | 252,469,630 | 252,469,630 | |
| 554 | | `lanes.bin` | 3,013,792 | 3,013,792 | 3,563,182 | 3,563,182 | |
| 555 | | `intermediate.bin` | 217,693,470 | **138,465,471** | 215,252,596 | **134,529,908** | |
| 556 | | `road_names.bin` | 5,481,848 | 5,481,848 | 5,481,848 | 5,481,848 | |
| 557 | | **total** | **538,209,298** | **458,981,299** | **561,954,552** | **481,231,864** | |
| 558 | | | | **−14.7%** | | **−14.4%** | |
| 559 | |
| 560 | Against v1 that is **−42.1%** and **−42.5%**. |
| 561 | |
| 562 | Every byte of the `intermediate.bin` delta is accounted for, which is what makes it |
| 563 | a check rather than a result. The reference path has E = 16,785,702 directed edges |
| 564 | and G = 4,494,428 stored polylines: |
| 565 | |
| 566 | * the v2 file was a 179,925,624-byte blob behind 37,767,846 bytes of tables |
| 567 | (`coarse` 4,196,440 + `within` 33,571,406); |
| 568 | * dropping both endpoints takes 12 bytes off each of the 4,494,428 stored |
| 569 | polylines, i.e. **−53,933,136**, leaving a 125,992,488-byte blob; |
| 570 | * the trailer is 12,472,983 bytes — `rank` 262,288 + `present` 2,098,213 + |
| 571 | `coarse` 1,123,616 + `within` 8,988,858 + 8 — so the tables cost **−25,294,863**; |
| 572 | * 125,992,488 + 12,472,983 = **138,465,471**, exactly the file on disk. |
| 573 | |
| 574 | So the presence bitmap plus the narrower offset tables are 3.0× smaller than v2's |
| 575 | two-level pair, and the blob is 30% smaller for holding nothing but interiors. |
| 576 | |
| 577 | **`route_diff` is unchanged from the v2 baseline, to the digit.** `compare` reports |
| 578 | the same **999** same-snap-same-length, **966** alternative optimum, **8** snapped |
| 579 | elsewhere, and the same worst deltas of **−1,493,486 mm** and **−20,893** 10 ms |
| 580 | units. `geometry` reports the same **34,900** baseline vertices missing forward and |
| 581 | **29,703** reversed, and the same ±98,897,640 mm length delta, so the vertex |
| 582 | difference is still symmetric. That is the point of keeping `count == 0` for an |
| 583 | absent polyline in this change: every one of those numbers describes the *reference |
| 584 | vs within-way* difference, and none of them may move for a format change. They did |
| 585 | not. |
| 586 | |
| 587 | `geometry / reversed` also matches: 4,494,428 / 3,669,235 on the reference path and |
| 588 | 4,377,764 / 3,595,577 on within-way, and 8,163,663 of 16,785,702 edges resolve a |
| 589 | polyline either way. |
| 590 | |
| 591 | **`--rounds 1` vs `3` vs `17` is byte-identical on all six files, on both collapse |
| 592 | paths.** That is the strongest check the presence bitmap gets, because round |
| 593 | boundaries move which edges each pass collects, which presence bits each pass sets, |
| 594 | which coarse block it is filling and which within-block offsets it appends — and |
| 595 | none of it reaches the file. |
| 596 | |
| 597 | Europe and planet runs are out of scope for this change; the ~29 GB figure above |
| 598 | stays a projection. |
| 599 | |
| 600 | **A note the earlier revision of this file got wrong.** The p99 snap offset of |
| 601 | 2.2 km recorded below was once attributed to `find_nearest_edge` skipping edges |
| 602 | with no resolvable geometry. It does not skip them: it falls through to |
| 603 | "No geometry: snap to the straight node-to-node segment" and projects onto the |
| 604 | chord itself, as do the other six `get_edge_coordinates` call sites. So chord |
| 605 | recovery was never the missing piece, and nothing here changes snapping coverage. |
| 606 | |
| 607 | ## Getting it under 25: what the census says |
| 608 | |
| 609 | v3 projects a planet pack at ~29.0 GB. The next question was whether 25 GB is |
| 610 | reachable, and the answer had to come from measurement rather than from guessing |
| 611 | which field looked wasteful — so `road_graph` gained a `--stats` mode that reports |
| 612 | what a narrower record would cost, computed by **the encoder's own escape |
| 613 | predicate** rather than by an analysis script that could disagree with it by one. |
| 614 | |
| 615 | ``` |
| 616 | road_graph california-latest.osm.pbf --out DIR --stats |
| 617 | ``` |
| 618 | |
| 619 | Where it ended up, on the planet basis of E = 1,074,282,569 directed edges and |
| 620 | N = 431,474,933 nodes: |
| 621 | |
| 622 | | version | change | `edges.bin` | `nodes.bin` | pack | |
| 623 | |---|---|---|---|---| |
| 624 | | 3 | where this started | 15.04 GB | 5.18 GB | 29.0 GB | |
| 625 | | 4 | `edge_count` in metadata, length validation, no layout change | 15.04 GB | 5.18 GB | 29.0 GB | |
| 626 | | 5 | `i16` target delta + `u24 dist_mm`, one merged escape table | **11.86 GB** | 5.18 GB | **25.8 GB** | |
| 627 | | 6 | `name_offset` sparse, 7-byte record | **9.33 GB** | 5.18 GB | **23.3 GB** | |
| 628 | | ~~7~~ | ~~fused node block header~~ — correct, 10% slower, reverted | 9.33 GB | ~~3.99 GB~~ | ~~22.1 GB~~ | |
| 629 | |
| 630 | `intermediate.bin` (8.50 GB), `lanes.bin` (0.04 GB) and `road_names.bin` (0.25 GB) are |
| 631 | untouched throughout. Every step is **exact** — no quantisation anywhere — so the pass |
| 632 | condition at each one is byte-identical routing output, not "within tolerance". |
| 633 | |
| 634 | Measured on California, reference path: 458,981,307 bytes → **369,839,208**, a 19.4% |
| 635 | reduction with the per-element dump identical at every step. |
| 636 | |
| 637 | ### The measurement spike came first |
| 638 | |
| 639 | Nothing shipped until `--stats` had run, because the whole design rested on numbers |
| 640 | nobody had. Measured on California, reference path (E = 16,785,702, N = 6,418,361): |
| 641 | |
| 642 | | | | |
| 643 | |---|---| |
| 644 | | `edges.bin` share of the pack | **52%** | |
| 645 | | `\|target − source\|` fits an `i16` | 99.699% (**50,591** escapes) | |
| 646 | | `dist_mm` at or above `0xFFFFFF` (16.78 km) | **166** edges, 0.001% | |
| 647 | | named edges | 37.72% — so 62.28% of `name_offset` is a sentinel | |
| 648 | | `speed_limit` zero | 91.76% | |
| 649 | | max out-degree | **24** | |
| 650 | | degree-0 nodes | **1,480** (0.023%) | |
| 651 | | name pool | 5,481,848 B in 323,443 names | |
| 652 | |
| 653 | Three of `edges.bin`'s five fields are therefore mostly redundant, and `dist_mm` |
| 654 | should be a `u24` in **millimetres** rather than centimetres: only 0.001% of edges |
| 655 | exceed the ceiling, so the escape table is ~85 KB planet-wide and the field stays |
| 656 | *exact* rather than quantising 1.07 G edges to save a table. |
| 657 | |
| 658 | ### `c` is the number that transfers, not the escape rate |
| 659 | |
| 660 | An escape rate measured on one extract says nothing about a planet 22× larger. What |
| 661 | should transfer is the constant in |
| 662 | |
| 663 | ``` |
| 664 | P(|target − source| > n) ≈ c · n^(−1/2) |
| 665 | ``` |
| 666 | |
| 667 | because a level-*k* quadrant boundary produces a delta of order `N / 4^k` and is |
| 668 | crossed with probability proportional to `2^k`; substituting `n = N / 4^k` gives |
| 669 | `P = (L·√N / W) / √n`, and `L·√N / W` is the ratio of edge length to node spacing — |
| 670 | a local, physical quantity that does not depend on `N`. `--stats` prints `c` at every |
| 671 | power of two so the shape of the curve is visible, not just one point on it. |
| 672 | |
| 673 | **Measured on both California and Europe, and it holds.** Europe is 20.9× the edge |
| 674 | count and 21.6× the node count: |
| 675 | |
| 676 | | | California | Europe | ratio | |
| 677 | |---|---|---|---| |
| 678 | | directed edges | 16,785,702 | 350,290,432 | 20.9× | |
| 679 | | nodes | 6,418,361 | 138,635,441 | 21.6× | |
| 680 | | `i16` escape rate | 0.3014% | 0.3132% | **1.04×** | |
| 681 | | `c` at n = 32,767 | 0.5456 | 0.5670 | **1.04×** | |
| 682 | | `u24 dist_mm` escape rate | 0.000989% | 0.000892% | 0.90× | |
| 683 | | named edges | 37.72% | 31.15% | 0.83× | |
| 684 | | max out-degree | 24 | **77** | 3.2× | |
| 685 | | degree-0 nodes | 0.0231% | 0.0270% | 1.17× | |
| 686 | | max `dist_mm` | 61.5 km | **2,979 km** | 48× | |
| 687 | |
| 688 | `c` moves by 4% across a 21× change in scale, well inside the 1.5× the design needed, |
| 689 | so the planet escape rate is predictable and the escape table is ~40 MB rather than |
| 690 | anything that matters. Two other columns are worth more than they look: |
| 691 | |
| 692 | * **The named fraction *falls* with scale** (37.7% → 31.1%), so making `name_offset` |
| 693 | sparse saves more on a planet than California suggests, not less. |
| 694 | * **Max out-degree triples** (24 → 77). Any future per-node `u8 degree` field would |
| 695 | still fit, but not by the margin California implied — which is why one is not |
| 696 | worth adding without a writer pre-pass that widens the field if it overflows. |
| 697 | |
| 698 | ### The single most useful thing the census found |
| 699 | |
| 700 | Europe has an edge **2,979 km long**. California's longest is 61.5 km. |
| 701 | |
| 702 | That number kills the option v3 considered and this work rejected: `dist_mm` as a |
| 703 | `u24` counting **centimetres**, which needs no escape table because 2^24 cm is |
| 704 | 167.77 km. It would have been silently, catastrophically wrong on Europe — the value |
| 705 | wraps — and it quantises all 1.07 G edges to buy that. Millimetres plus a shared |
| 706 | escape table keeps every distance *exact* and costs 3,126 rows on Europe: 37 KB. |
| 707 | |
| 708 | It also vindicates merging the two escape tables. The `dist_mm` escape rate is the |
| 709 | least transferable number in the whole census, and merging makes it irrelevant to |
| 710 | the design: a hundredfold miss rides along in the table `target` already needed. |
| 711 | |
| 712 | ### Hilbert was tried, and loses |
| 713 | |
| 714 | Z-order's known flaw is the discontinuity at every quadrant boundary, which is |
| 715 | exactly the mechanism above, so Hilbert — which has no long-range jumps at all — |
| 716 | looked like a free win. It is not. Both curves, same extract, same predicate: |
| 717 | |
| 718 | | `\|target − source\|` > | Morton | Hilbert | |
| 719 | |---|---|---| |
| 720 | | 1,024 | 2.2254% | 2.1553% | |
| 721 | | 16,384 | 0.4711% | 0.4648% | |
| 722 | | **32,767** | **0.30139%** | **0.30756%** | |
| 723 | | 262,144 | 0.0713% | 0.0892% | |
| 724 | |
| 725 | Hilbert wins below ~16 k and loses above it: it *concentrates* the distribution |
| 726 | rather than shortening it, trading mid-range deltas for far ones, and the crossover |
| 727 | falls almost exactly on the `i16` boundary. So the quadrant discontinuities are not |
| 728 | what generates the 0.3% tail — mapping a 2-D neighbourhood onto a 1-D index costs |
| 729 | about that much however it is done — and the escape table is unavoidable either way. |
| 730 | Morton stays, and `spatial.rs` now pins the discontinuity in a test so the next |
| 731 | person reads the measurement instead of repeating it. |
| 732 | |
| 733 | ### Delta-coded coordinates stay rejected |
| 734 | |
| 735 | The other candidate v3 named. Longitude deltas along the Morton order fit an `i16` |
| 736 | only 91.4% of the time, and `find_nearest_edge` binary-searches the coordinate array |
| 737 | by spatial key, so it needs O(1) random access — which delta coding destroys. |
| 738 | |
| 739 | ### Version 4 is the de-risking step |
| 740 | |
| 741 | No byte of any data file moves. What lands is the machinery every later phase needs: |
| 742 | `edge_count` in `metadata.bin`, [exact length validation](#every-files-length-is-checked) |
| 743 | of every file, compile-time record-size assertions, `Graph::edge_range` as the only |
| 744 | way to ask for a node's edge range, the `EdgeRec`/`Edge` widening that keeps a |
| 745 | layout change inside `graph.rs`, and `route_diff dump` — a per-element equivalence |
| 746 | dump over **all** E edges and N+1 node records, which is what later phases are |
| 747 | verified against instead of the ~35 K vertices 999 sampled routes happen to touch. |
| 748 | |
| 749 | `route_diff` also gained a `bench` mode, so the phases that are gated on latency |
| 750 | rather than correctness have a baseline to be gated against. It reports routes/sec, |
| 751 | per-route p50/p90/p99 and peak RSS, separating the first pass from the warm ones, and |
| 752 | `--cold` evicts the pack from the page cache first with `posix_fadvise` — which, |
| 753 | unlike `/proc/sys/vm/drop_caches`, needs no root. Every pass also reports a checksum |
| 754 | over what it routed, so a format change that broke routing shows up as a broken |
| 755 | checksum rather than as a speedup. |
| 756 | |
| 757 | Version 4's own gate: every data file byte-identical to the v3 pack on both collapse |
| 758 | paths, `metadata.bin` 16 B → 24 B, and `route_diff report` byte-identical to what |
| 759 | the *v3 binary* produced from the *v3 pack* — a direct reader-equivalence check |
| 760 | across the change rather than a comparison against itself. |
| 761 | |
| 762 | ### Version 5: the 11-byte record |
| 763 | |
| 764 | ```text |
| 765 | [ EdgeRec[E] ] 11 B: i16 target_delta, u24 dist_mm, |
| 766 | u8 type_, u8 speed_limit, u32 name_offset |
| 767 | [ pad to an 8-byte boundary ] |
| 768 | [ u32 escape_first[E.div_ceil(1024) + 1] ] |
| 769 | [ { u32 edge_idx, u32 target, u32 dist_mm } × escape_count ] ascending by edge_idx |
| 770 | ``` |
| 771 | |
| 772 | `target` becomes a signed delta from the edge's own source and `dist_mm` a `u24`, |
| 773 | so 14 bytes become 11 — **3.22 GB** of a planet, less the escape table. Every value |
| 774 | stays exact. |
| 775 | |
| 776 | **One escape table, not two.** `target_delta == i16::MIN` *or* `dist_mm == 0xFFFFFF` |
| 777 | means both fields come from the escape row. Two sentinels with two tables would cost |
| 778 | two branches in the A* relaxation, two metadata fields and two sets of off-by-one |
| 779 | risk, to keep a 39 MB table apart from an 85 KB one. Merging costs ~13 MB and |
| 780 | removes half the code — and it makes the `dist_mm` escape rate, the least |
| 781 | transferable number in the census, irrelevant to the design: collapsed chains in |
| 782 | Siberia will be far longer than California's, and a hundredfold miss just rides |
| 783 | along in the same table. |
| 784 | |
| 785 | **A block index, not a binary search.** The inline sentinel already *is* the |
| 786 | presence bit — it is in a register that was just loaded — so a v3-style presence |
| 787 | bitmap would spend 134 MB duplicating it. All that is missing is edge index → row, |
| 788 | and `u32 escape_first[E/1024 + 1]` is 4.2 MB: one load from a largely |
| 789 | cache-resident array, then a scan of the ~3 rows a block holds, usually one cache |
| 790 | line. A binary search over 3.24 M rows would be 12–15 misses. `lanes.bin` does |
| 791 | binary-search its sparse index and its doc comment justifies that by being "called |
| 792 | once per maneuver rather than per edge"; `target` is read on every relaxation, so |
| 793 | that precedent does not transfer. |
| 794 | |
| 795 | **Field order is load-bearing.** The four fields the A* relaxation reads sit in |
| 796 | bytes 0..7, so one 8-byte load covers all of them, and `name_offset` is last. The |
| 797 | `u24` is assembled from three bytes rather than loaded as a masked `u32`, so no read |
| 798 | can run past the array — and the array is padded to 8 bytes anyway, which keeps the |
| 799 | block index naturally aligned whatever `E` is. |
| 800 | |
| 801 | Shrinking the record is a locality *win*, not a cost: adjacency records per 64-byte |
| 802 | line goes 4.6 → 5.8, so the relaxation should get slightly faster rather than |
| 803 | slower. |
| 804 | |
| 805 | **Measured on California:** `edges.bin` 234,999,828 → 185,316,836 bytes on the |
| 806 | reference path (−21.1%), with 50,711 escape rows (0.302% of 16,785,702 edges); the |
| 807 | whole pack 458,981,307 → 409,298,323 (−10.8%). The per-element dump is identical — |
| 808 | **0 of 16,785,702 edges and 0 of 6,418,362 node records differ**, and the same on the |
| 809 | within-way path's 18,033,545 edges — `report` is still byte-identical to the v3 |
| 810 | binary's, and `compare` and `geometry` do not move a digit. |
| 811 | |
| 812 | | file | v3/v4 | v5 | basis | |
| 813 | |---|---|---|---| |
| 814 | | `metadata.bin` | 24 B | 32 B | `escape_count` | |
| 815 | | `edges.bin` | 15.04 GB | **11.86 GB** | 11 B × E + 4.2 MB index + 40 MB rows | |
| 816 | | everything else | | unchanged | | |
| 817 | | **planet total** | **~29.0 GB** | **~25.8 GB** | | |
| 818 | |
| 819 | **Seven synthetic tests cover what California cannot contain**: deltas at 0, ±1, |
| 820 | ±32766, ±32767, ±32768, −32769 and +40000; `dist_mm` at 0, 1, `0xFFFFFE`, |
| 821 | `0xFFFFFF`, `0x1000000` and `u32::MAX`; an edge that fails both tests at once |
| 822 | (one row, not two); escapes at edge 0 and edge E−1; a pack with no escapes at all, |
| 823 | where the padding is the only thing keeping a wide load in bounds; and escape rows |
| 824 | on both sides of every block boundary at 1023/1024/1025/2047/2048/2049. The |
| 825 | encoder and the decoder are exercised as a pair, directly, because putting two nodes |
| 826 | exactly 32,768 apart in Morton order would mean choosing coordinates for the 32,767 |
| 827 | nodes in between. |
| 828 | |
| 829 | **`--rounds 1` vs `3` vs `17` stays byte-identical on all six files, on both collapse |
| 830 | paths.** That is the strongest check the escape table gets: round boundaries move |
| 831 | which edges each pass collects, which of them escape, and where the block index's |
| 832 | prefix counts land — and none of it reaches the file. |
| 833 | |
| 834 | ### Version 6: `name_offset` becomes sparse |
| 835 | |
| 836 | ```text |
| 837 | [ EdgeRec[E] ] 7 B: i16 target_delta, u24 dist_mm, |
| 838 | u8 type_, u8 speed_limit |
| 839 | [ pad ][ u32 escape_first[..] ][ EscapeRow[escape_count] ][ pad ] |
| 840 | [ u64 name rank[E.div_ceil(512) + 1] ][ u8 name present[E.div_ceil(8)] ] |
| 841 | [ u32 name_off[named_edges] ] |
| 842 | ``` |
| 843 | |
| 844 | Two thirds of edges have no name — **62.28%** of California's, **68.85%** of |
| 845 | Europe's — so a dense `u32` per edge spent four bytes on a sentinel more often than |
| 846 | on an offset. A presence bitmap plus a rank index makes absence free and costs the |
| 847 | named third four bytes each: **−2.53 GB** of a planet. |
| 848 | |
| 849 | **It is a presence bitmap over the existing byte offset, not a dense name id.** |
| 850 | Adding an id space would get a further 0.41 GB, but it means changing |
| 851 | `NamePool::intern`'s return type, and `poi_build.rs` is a second consumer that has to |
| 852 | keep byte offsets for `PoiIndex.kt`. Recoverable later without touching |
| 853 | `poi_build.rs` if that 0.41 GB is ever wanted. |
| 854 | |
| 855 | **The rank/select pair is now one type, used twice.** `intermediate.bin` has had a |
| 856 | presence bitmap and rank index since v3, and this is the same question asked of a |
| 857 | different field, so `EdgeBitmap` in the reader and `PresenceBitmap` in the writer |
| 858 | replace what would have been two transcriptions of the same eight lines. The block |
| 859 | size stays 64 bytes — 512 edges, one cache line — so a rank is one `u64` load plus at |
| 860 | most eight `popcount`s. |
| 861 | |
| 862 | **Why this and not sparse `speed_limit`.** `speed_limit` is zero on 91.76% of edges |
| 863 | and making it sparse would save 0.84 GB, but it is read in the A* relaxation, up to |
| 864 | 25 M expansions × degree per route, from a record already in L1. A rank probe there |
| 865 | is not worth 0.84 GB. Names are read when an *instruction* is emitted — once per |
| 866 | maneuver, not once per edge — which is what makes three loads instead of one |
| 867 | affordable. |
| 868 | |
| 869 | **The prerequisite was deleting a dead store.** The A* relaxation used to copy |
| 870 | `name_offset` into the scratchpad on every improving edge, into an `Entry` field |
| 871 | nothing ever read; the same was true of `last_type`. Until those went, `name_offset` |
| 872 | was on the hot path and no sparse form was affordable. Removing them also took |
| 873 | `Entry` from 24 bytes to 20, in the structure the router touches most. |
| 874 | |
| 875 | **Measured on California:** `edges.bin` 185,316,836 → 145,857,713 bytes on the |
| 876 | reference path, so the whole pack is 458,981,307 → 369,839,208 — **−19.4% against |
| 877 | v3**. 6,330,795 of 16,785,702 edges are named (37.72%). The per-element dump is |
| 878 | identical again — **0 of 16,785,702 edges and 0 of 6,418,362 node records differ, |
| 879 | including `name_offset` for every edge**, which is the phase where that dump earns |
| 880 | its keep. |
| 881 | |
| 882 | The 145,857,713 breaks down exactly as the reader computes it: 117,499,920 of padded |
| 883 | records, 65,576 of escape block index, 608,532 of escape rows, 4 of padding, |
| 884 | 2,360,501 of name bitmap and rank, and 25,323,180 of name offsets. |
| 885 | |
| 886 | | file | v3 | v5 | v6 | basis | |
| 887 | |---|---|---|---|---| |
| 888 | | `metadata.bin` | 16 B | 32 B | 40 B | `named_edges` | |
| 889 | | `edges.bin` | 15.04 GB | 11.86 GB | **9.33 GB** | 7 B × E + 0.15 GB bitmap + 1.62 GB offsets | |
| 890 | | everything else | | | unchanged | | |
| 891 | | **planet total** | **~29.0 GB** | **~25.8 GB** | **~23.3 GB** | | |
| 892 | |
| 893 | That planet column uses California's 37.72% named fraction. At Europe's 31.15% the |
| 894 | offsets are 1.34 GB rather than 1.62 GB, so the real figure should come in nearer |
| 895 | **23.0 GB**. |
| 896 | |
| 897 | **Four synthetic tests cover the sparse table's boundaries**: a name at edge 0 and at |
| 898 | edge E−1; names either side of the 512-edge rank-block boundary and either side of |
| 899 | 1024, with a distinct offset per named edge so a rank off by one reads a visibly |
| 900 | wrong value; a pack where no edge is named; and one where every edge is. |
| 901 | |
| 902 | ### Version 7 was built, measured and abandoned |
| 903 | |
| 904 | The remaining idea was to split `nodes.bin` into coordinates plus a fused per-block |
| 905 | edge-extent header: |
| 906 | |
| 907 | ```text |
| 908 | [ { i32 lat_e7, i32 lon_e7 } x (N + 1) ] 8 B |
| 909 | [ { u32 edge_base, u8 degree[16] } x (N + 1).div_ceil(16) ] 20 B per 16 nodes |
| 910 | ``` |
| 911 | |
| 912 | 9.25 bytes a node instead of 12, so **−1.19 GB** and a planet at ~22.1 GB. Because |
| 913 | `degree[v] == edge_ptr(v + 1) − edge_ptr(v)`, `edge_range(v)` needs only `v`'s own |
| 914 | block: no `v + 1` lookup, no block-boundary case, and one cache miss where the dense |
| 915 | layout needed two. |
| 916 | |
| 917 | It was implemented in full — degree-width pre-pass, `u8`/`u16` widths, sentinel |
| 918 | integrity check, all of it — and it is **correct**: the per-element dump is identical |
| 919 | across all 16,785,702 edges and 6,418,362 node records, `report` stays byte-identical |
| 920 | to the v3 binary's, and `nodes.bin` came out at 59,369,856 bytes against v6's |
| 921 | 77,020,344 (−22.9%), the whole pack at 352,188,721 (−23.3% against v3). |
| 922 | |
| 923 | It is also **slower**, and the phase was gated on that: |
| 924 | |
| 925 | | | v6 | v7 | | gate | |
| 926 | |---|---|---|---|---| |
| 927 | | warm routes/s | 20.2 | 18.1 | −10.4% | ≥97% ✗ | |
| 928 | | cold routes/s | 19.2 | 17.7 | −7.8% | ≥97% ✗ | |
| 929 | | warm p50 | 0.953 ms | 1.043 ms | +9.4% | ✗ | |
| 930 | | cold p99 | 651.2 ms | 710.8 ms | +9.2% | ≥97% ✗ | |
| 931 | | peak RSS | 484 MB | 466 MB | −3.7% | ✓ | |
| 932 | |
| 933 | Three times over the 3% tolerance, so it is reverted. |
| 934 | |
| 935 | **The interesting part is why, because the design's cost model was wrong.** The |
| 936 | reasoning was about *cache misses*: one fused header is one miss where a separate |
| 937 | base array plus a degree array would be two, and the dense layout read two records. |
| 938 | That reasoning is sound and the miss count really did improve. What it missed is that |
| 939 | a within-block prefix sum is a **serial dependency chain of up to fifteen adds**, and |
| 940 | `edge_range` is the router's hottest read — once per A* pop, and 1,600 times per |
| 941 | `find_nearest_edge` window scan. On a pack that fits in RAM, where nothing misses, |
| 942 | that arithmetic is the whole cost and there is no miss saved to pay for it. |
| 943 | |
| 944 | Measured on California, which is the *favourable* case: the pack is 370 MB on a 94 GB |
| 945 | box, so even a `posix_fadvise`-evicted run is reading from local disk in seconds. The |
| 946 | case v7 was designed for — a planet-sized pack where each node read is a major fault — |
| 947 | would have to overcome a 10% arithmetic penalty before it broke even, and nothing here |
| 948 | suggests it would. |
| 949 | |
| 950 | A variant storing `u16 prefix[16]` instead of degrees would make `edge_range` two byte |
| 951 | loads and no loop, at 10.25 bytes a node rather than 9.25 — about **−0.76 GB** instead |
| 952 | of −1.19 GB, and it reintroduces the block-boundary case for one node in sixteen. That |
| 953 | is the shape worth trying if the last gigabyte is ever wanted. It was not tried here, |
| 954 | because the target was already met at v6 and the measurement above is the answer to |
| 955 | the question that was actually asked. |
| 956 | |
| 957 | ## Build-time memory |
| 958 | |
| 959 | The output has fitted a planet for a while; the build did not. California peaked |
| 960 | at **4.97 GB of RSS** for a 1.26 GB PBF, which scales to roughly 310 GB on an |
| 961 | 80 GB planet file — and the structural breakdown agreed, putting the pass-3 |
| 962 | working set at about 217 GB. The gap was 2.3x on a 94 GB machine, so this was a |
| 963 | restructure rather than a diet, following the same route `gtfs_ingest` took: not |
| 964 | spill machinery, but a streaming, incrementally-finalised build. |
| 965 | |
| 966 | Four changes do the work. |
| 967 | |
| 968 | **Rank/select over the bitset that already existed.** `Bitset` marks exactly the |
| 969 | graph's nodes, keyed by raw OSM id. A cumulative popcount per 512-bit block — |
| 970 | sized to the largest id actually seen, not to `BITSET_SIZE` — makes |
| 971 | `dense(osm_id)` an O(1) rank. The node array is then *implicitly ordered by OSM |
| 972 | id*, which deletes the sorted `(osm_id, local_id)` table the edge pass used to |
| 973 | binary-search, deletes the per-node `osm_id` because it is the index, and deletes |
| 974 | the per-node spatial key because only the survivors ever need a Morton sort. |
| 975 | What is left is `coords`, at 8 bytes a node. |
| 976 | |
| 977 | This is also where dangling references become dangerous rather than merely |
| 978 | untidy. Pass 1 marks every ref of every routable way, including refs to nodes no |
| 979 | blob in the file defines — an extract clipped at a boundary is full of them — and |
| 980 | under rank addressing each of those owns a slot. A slot that never receives |
| 981 | coordinates reads as `(0, 0)`, which corrupts distances, spatial keys and |
| 982 | polylines while leaving every count plausible. Hence the `present` bitset, set |
| 983 | during the coordinate scatter, and hence the pass order: **coordinates before |
| 984 | anything that reads the node array**. |
| 985 | |
| 986 | **Never cache ways; re-read the PBF.** `blob_kinds` already lets a later pass |
| 987 | skip whole blobs. Way blobs are a small minority of a planet file, so re-reading |
| 988 | them is far cheaper than the ~32 GB way-and-ref cache it replaces. The build logs |
| 989 | what fraction of blobs the ways pass actually read, because that number is what |
| 990 | justifies the strategy. |
| 991 | |
| 992 | **Never materialise segments** (`--within-way-chains`). Restricting chains to a |
| 993 | single OSM way means every segment in a chain shares its way's type, speed, name, |
| 994 | one-way-ness and lanes *by construction*, so the attribute-agreement half of |
| 995 | `compact.rs::classify` becomes free. All that remains is a global per-node |
| 996 | degree, which is one byte a node. That deletes the segment array **and** the |
| 997 | incidence CSR over it — 114 GB of the 217. |
| 998 | |
| 999 | **Spill the chains and write in source-partitioned rounds.** Chains go to |
| 1000 | `chains.hdr` (fixed-size records, so the count is the file size over the stride |
| 1001 | and any stage can seek to chain *k*) and `chains.pts` (coordinates, not node ids, |
| 1002 | so `coords` is freed the moment the spill is written). The edge index, the |
| 1003 | component scan and every write round are then sequential scans over those files. |
| 1004 | |
| 1005 | ### What within-way chains cost |
| 1006 | |
| 1007 | An accepted quality regression, and a real one: a node where two different ways |
| 1008 | meet end-to-end with matching tags is collapsed by `compact.rs` and kept here. |
| 1009 | OSM splits long roads constantly, at every tag change and at the 2000-node way |
| 1010 | ceiling, so this is not a rare case. `graph_build.rs`'s |
| 1011 | `within_way_chains_keep_the_node_where_two_ways_meet` states it as a test rather |
| 1012 | than an estimate. |
| 1013 | |
| 1014 | Two things soften it. The 256-point split budget already forces cuts on long |
| 1015 | dense roads anyway, and more surviving nodes strictly *improves* snapping — the |
| 1016 | p99 snap offset fell from 3.7 km to 2.2 km when compaction landed, for the same |
| 1017 | reason in reverse. Nothing about the drawn shape of a road changes: the extra node |
| 1018 | was already a vertex in `intermediate.bin`. |
| 1019 | |
| 1020 | Two correctness simplifications come free with it, both of which were bugs that |
| 1021 | had to be fixed once already. The walk advances through a finite ref list, so it |
| 1022 | cannot loop: there is no per-segment "used" flag and no anchorless-cycle phase, and |
| 1023 | a ring way closes on its own first node. And within one way every segment runs |
| 1024 | along ref order, so a one-way chain is already oriented along its traffic and |
| 1025 | there is no reorientation step to hand the forward and backward lane masks to the |
| 1026 | wrong end. |
| 1027 | |
| 1028 | If the regression turns out to be unacceptable at scale, the recovery path needs |
| 1029 | no new memory: run `compact.rs`'s logic over the **chain** stream instead of the |
| 1030 | segment stream. Chains are a few hundred million records rather than billions of |
| 1031 | segments, they already carry every attribute `classify` compares, and a chain is |
| 1032 | structurally a `Seg` with a point range. |
| 1033 | |
| 1034 | ### Why the writer uses rounds and not computed offsets |
| 1035 | |
| 1036 | Computing each edge's index and writing it into place is sound for `edges.bin` — |
| 1037 | fixed 14-byte records, pre-sized file — and wrong for the two blob files. The |
| 1038 | reader derives a polyline's length from `off(k + 1) - off(k)` and a lane run's |
| 1039 | length from the next index entry, so `intermediate.bin` and `lanes.bin` are forced |
| 1040 | into edge-index order with monotonic offsets, and writing a blob at a computed |
| 1041 | offset would mean knowing every earlier blob's length first: a per-edge length |
| 1042 | array, a prefix sum and a second encode pass. |
| 1043 | |
| 1044 | Partitioning by source instead makes every write an append. Each round takes a |
| 1045 | contiguous range of final node ids, scans the spill for the edges whose *source* |
| 1046 | falls in that range, sorts that buffer by `(source, target, chain)`, and writes |
| 1047 | both blobs, both of `intermediate.bin`'s offset halves, `edges.bin` and `nodes.bin` |
| 1048 | forwards. Offsets come out monotonic by construction, the offset halves become |
| 1049 | append-only scratch files copied into their reserved prefixes at the end, |
| 1050 | `nodes.bin`'s running edge counter works because the rounds ascend, and the |
| 1051 | `(source, target)` grouping the reader and `twin_is_unique` depend on is restored |
| 1052 | within each round. |
| 1053 | |
| 1054 | `lanes.bin` is the one file that cannot reserve a prefix, because its index is |
| 1055 | sparse and `n` is not known until the last round has run. Its blob streams to a |
| 1056 | scratch file while the index accumulates in memory — 23 MB at planet scale — and |
| 1057 | the header plus index are written in front of the blob at the end. |
| 1058 | |
| 1059 | Each round's edge count is checked against `edge_ptr` *before* anything is |
| 1060 | written, which catches both an edge landing in the wrong round and an edge whose |
| 1061 | source is not a surviving node. |
| 1062 | |
| 1063 | `--rounds` defaults to 1, so small inputs and the test suite are untouched. |
| 1064 | |
| 1065 | `--spill-dir` puts the spill somewhere other than the output directory. Worth |
| 1066 | separating, because `chains.pts` is the only file the build reads *randomly* — |
| 1067 | once per edge that stores a polyline — while the output only ever needs |
| 1068 | sequential writes. On the first California run the spill sat on a slow mount and |
| 1069 | that single random read per edge cost more wall clock than every other stage put |
| 1070 | together: 47 minutes at 21% CPU, with 17.8 M voluntary context switches against |
| 1071 | 16.8 M edges. Two reorderings removed most of those reads outright — a chain of |
| 1072 | two points cannot have stored geometry, and an edge that defers to its twin never |
| 1073 | needs the polyline — and the flag moves the rest onto a disk whose seeks are |
| 1074 | cheap. |
| 1075 | |
| 1076 | ### Measured on California |
| 1077 | |
| 1078 | `california-latest.osm.pbf`, 1.26 GB, 23010 data blobs, 35,864,766 marked nodes. |
| 1079 | Both paths built from the same input on the same machine, spill on a local disk: |
| 1080 | |
| 1081 | | | reference (`compact.rs`) | `--within-way-chains` | |
| 1082 | |---|---|---| |
| 1083 | | nodes kept | 6,418,361 | 7,098,939 (+10.6%) | |
| 1084 | | directed edges | 16,785,706 | 18,033,549 (+7.4%) | |
| 1085 | | chains | 8,687,974 | 9,368,552 (+7.8%) | |
| 1086 | | split for the 256-point limit | 4,985 | 4,480 | |
| 1087 | | largest component | 98.24% | 98.32% | |
| 1088 | | `intermediate.bin` | 314,211,280 B | 318,945,504 B (+1.5%) | |
| 1089 | | total road length | 1,950,166 km | −0.005% | |
| 1090 | | **peak RSS** | **4.49 GB** | **2.79 GB (−38%)** | |
| 1091 | | wall clock | 1:33 | 1:26 | |
| 1092 | |
| 1093 | So the cross-way regression the plan could only guess at is **about a tenth of the |
| 1094 | node count**, bought for 38% less peak memory and the deletion of the segment |
| 1095 | array and its incidence index. The ways pass read **2145 of 23010 blobs (9.3%)**, |
| 1096 | which is the measurement that justifies re-reading them rather than caching. |
| 1097 | |
| 1098 | Both `intermediate.bin` figures are **v1** sizes, measured before the two-level |
| 1099 | offset table. The node and edge counts, the split count and the peak RSS are |
| 1100 | unaffected by the format change. |
| 1101 | |
| 1102 | Note that ~2.5 GB of either figure is the `BITSET_SIZE` node mask, which is a |
| 1103 | fixed cost independent of region size, so neither number scales linearly. |
| 1104 | |
| 1105 | `route_diff geometry` reports a vertex-set difference of ~0.1% in **both** |
| 1106 | directions — each build appears to be "missing" vertices the other has, 34,900 one |
| 1107 | way and 29,703 the other, with the total length delta exactly ±98,897,640 mm. That |
| 1108 | symmetry is the tell: within-way chains keep strictly more nodes, so they cannot |
| 1109 | lose a real vertex. What moves is the *interpolated* filler `geom::encode` inserts |
| 1110 | when a gap exceeds ~364 m — chopping a polyline at a different node slides that |
| 1111 | filler along the same straight line. `route_diff` counts those points as vertices, |
| 1112 | so its vertex check has a false-failure mode whenever the chopping changes; the |
| 1113 | length tolerance, which is the check that would catch real loss, passes both ways. |
| 1114 | |
| 1115 | Both vertex counts were **re-measured unchanged under v2**, which is the evidence |
| 1116 | that the offset-format change is semantically inert: a different way of addressing |
| 1117 | the same polyline blob cannot move a vertex, and it did not. |
| 1118 | |
| 1119 | `route_diff compare`, re-run under v2 over the same 2000 pairs: 999 identical, |
| 1120 | **966 taking an alternative optimum of a different length**, 8 snapping more than a |
| 1121 | metre elsewhere, none gained or lost routability, worst case **−1.49 km** on a long |
| 1122 | route. **This is still not explained.** The plausible cause is that more surviving |
| 1123 | nodes mean more turn penalties, which moves the optimum. The figure reproduces the |
| 1124 | v1-era measurement to the metre, but `routing.rs` is *still* being modified |
| 1125 | concurrently, so this is a second measurement against a tree that is still not |
| 1126 | quiet rather than the clean re-run that would settle it. |
| 1127 | |
| 1128 | ### Measured on Europe |
| 1129 | |
| 1130 | `europe-latest.osm.pbf`, 33.2 GB, 534,883 blobs, 793,460,857 marked nodes. The |
| 1131 | continent gate matters because it is the first run where `coords`, `degree`, |
| 1132 | `edge_ptr` and `targets` all pass a gigabyte, and where the `u32` ceilings come |
| 1133 | within about 2x. |
| 1134 | |
| 1135 | | | reference | `--within-way-chains` | + streamed spill, `--rounds 8` | |
| 1136 | |---|---|---|---| |
| 1137 | | nodes kept | 138,635,441 | 151,447,545 (+9.2%) | same | |
| 1138 | | directed edges | 350,312,326 | 374,856,290 (+7.0%) | same | |
| 1139 | | chains | 178,171,772 | 190,983,876 | same | |
| 1140 | | `intermediate.bin` | 6.85 GB | 6.99 GB | same | |
| 1141 | | **peak RSS** | **61.85 GiB** | **31.81 GiB** | **14.30 GiB** | |
| 1142 | | wall clock | 39:11 | 35:17 | 41:15 | |
| 1143 | |
| 1144 | Three things to take from that. |
| 1145 | |
| 1146 | **The reference path is out at planet scale, measured rather than argued.** 61.85 GiB |
| 1147 | for a continent, on a 94 GB machine, with a planet 2.65x larger. |
| 1148 | |
| 1149 | **The cross-way regression is stable across two scales**: +10.6% nodes on |
| 1150 | California, +9.2% on Europe. It does not grow with the input. |
| 1151 | |
| 1152 | **The last two thirds of the memory win came from two changes the fixtures could |
| 1153 | never have shown.** At `--rounds 1` the write buffer held every edge — |
| 1154 | 374,856,290 x 48 B, 18 GB — and the chain pass accumulated the whole chain set |
| 1155 | before writing the spill, another 11.7 GB. Neither is visible on a 9-node fixture. |
| 1156 | The rounds writer already existed for the first; the second needed the spill write |
| 1157 | moved into the pass sink, which is where it should have been. |
| 1158 | |
| 1159 | All six output files are **byte-identical** between the `--rounds 1` accumulated |
| 1160 | build and the `--rounds 8` streamed one, on a 375 M-edge graph. That is the |
| 1161 | strongest check the rounds writer gets: round boundaries move which edges each pass |
| 1162 | collects, which offsets it appends and where `nodes.bin`'s running counter resumes, |
| 1163 | and none of it reaches the file. |
| 1164 | |
| 1165 | The cost of eight rounds is eight sequential passes over a 16 GB spill, which is |
| 1166 | the 17% of extra wall clock. |
| 1167 | |
| 1168 | A planet is run at **`--rounds 3`**, not 8. The write buffer is |
| 1169 | `edges / rounds × 48 B`, so three rounds move it from 6.4 GB to 17.2 GB and peak |
| 1170 | RSS from ~24 GB to roughly 30-35 GB — still comfortable in 94 GB — in exchange for |
| 1171 | three passes over the 24 GB header spill instead of eight. The header spill is on |
| 1172 | the slower mount, so that should be the larger effect. |
| 1173 | |
| 1174 | ### Measuring it |
| 1175 | |
| 1176 | `road_graph` prints its own peak RSS from `/proc/self/status` at the end of every |
| 1177 | run, so every build is a measurement rather than something to be caught with |
| 1178 | `top`. `VmHWM` is a high-water mark, so it survives the frees that a sample |
| 1179 | between two phases would miss; it does not include page cache or dirty pages, |
| 1180 | which is a further reason the rounds writer is preferable to computed-offset |
| 1181 | writes. Other platforms report nothing rather than a guess. |
| 1182 | |
| 1183 | Also worth watching, in roughly this order: the cross-way regression on a real |
| 1184 | extract; the dangling-ref ratio, which the build logs as marked ids with no |
| 1185 | coordinates; the fraction of blobs the ways pass skips; and `unique_names` / |
| 1186 | `name_bytes`, which decides whether `names.rs` needs `gtfs_ingest`'s `StringPool` |
| 1187 | treatment. |
| 1188 | |
| 1189 | Two rules hold everywhere. Every large array must be allocated at its final size: |
| 1190 | one `push`-driven doubling on a 12 GB array transiently costs 36 GB. And `u32` |
| 1191 | ceilings are only ~2.5x away at planet scale for node, survivor and chain counts, |
| 1192 | so each is checked rather than left to truncate silently into a valid-looking |
| 1193 | wrong record — as is `NamePool`'s cursor, since a `name_offset` is a `u32` on |
| 1194 | disk and a wrapped pool means permanently wrong street names. |
| 1195 | |
| 1196 | ## Determinism |
| 1197 | |
| 1198 | Every output is a pure function of the input file. This is a real change: the C++ |
| 1199 | generator filled its node array with `idx.fetch_add(1)` from concurrent workers |
| 1200 | and interned way names in thread-scheduling order, so two runs of the C++ on the |
| 1201 | same extract produced different node ordering, different `name_offset` values and |
| 1202 | therefore different `road_names.bin`, `edges.bin` and `nodes.bin`. |
| 1203 | |
| 1204 | The mechanism is in `src/par.rs` and `pbf::run_pass`: work is split into fixed |
| 1205 | contiguous chunks (of blobs, ways or nodes), chunks are claimed dynamically so a |
| 1206 | heavy chunk cannot stall a core, but each chunk's results are stored at its own |
| 1207 | index and merged **in index order**. Name interning then happens single-threaded |
| 1208 | during that merge. The chunk size is a constant, not a function of the core |
| 1209 | count, so the output does not vary between machines either. |
| 1210 | |
| 1211 | Verified on the full California extract: two runs produce byte-identical |
| 1212 | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `intermediate.bin`, |
| 1213 | `road_names.bin`, `poi_index.bin`, `poi_names.bin` and geojsonseq. |
| 1214 | |
| 1215 | ## How the reader works |
| 1216 | |
| 1217 | A `.osm.pbf` is a flat sequence of `[u32 BE header_len][BlobHeader][Blob]`. |
| 1218 | `pbf::scan_blobs` walks that framing once reading only headers, recording each |
| 1219 | `OSMData` blob's `(offset, len)`. Threads then each open their own `File`, seek, |
| 1220 | read and inflate their own blobs — no channels, no shared queue, no throttling |
| 1221 | condvar, which is how the C++ `ThreadPool`/`MoveTask`/`wait_finished` machinery |
| 1222 | (and the data race its comments describe) disappears. |
| 1223 | |
| 1224 | Every blob is self-checked: `miniz_oxide` validates the zlib header and the |
| 1225 | Adler-32 trailer, and the inflated length is compared against the blob's declared |
| 1226 | `raw_size`. Across California's 23,007 blobs that is strong evidence the reader |
| 1227 | is correct. Compressions that would need a C library (lzma, bzip2, lz4, zstd) |
| 1228 | are reported as a clear error rather than silently skipped, because a skipped |
| 1229 | blob would yield a quietly incomplete graph. |
| 1230 | |
| 1231 | Because a PBF stores all nodes, then all ways, then all relations, the first pass |
| 1232 | records which entity kinds each blob held; later passes skip blobs outright. |
| 1233 | `road_graph` needs two passes (ways must be known before we know which nodes |
| 1234 | matter) and `poi_extract` needs three (relations -> ways -> nodes). |
| 1235 | |
| 1236 | ## Testing |
| 1237 | |
| 1238 | `cargo test` runs 206 in-crate tests, following the `gtfs_ingest` pattern. The |
| 1239 | fixture in `src/testpbf.rs` hand-encodes a complete `.osm.pbf` — including real |
| 1240 | zlib framing built from stored DEFLATE blocks and a real Adler-32 — so the |
| 1241 | decoder is tested against bytes produced independently of it. |
| 1242 | |
| 1243 | - **protobuf**: uvarint at every 7-bit boundary, 10-byte negative `int64`, |
| 1244 | zigzag against the spec's vectors, packed deltas, skipping unknown fields of |
| 1245 | every wire type, and truncated input rejected. |
| 1246 | - **`latlng_to_spatial`** compared against a transcription of |
| 1247 | `graph.rs::latlng_to_spatial` for a table of coordinates. If these drift the |
| 1248 | device's spatial binary search silently returns the wrong nodes. |
| 1249 | - **`accurate_dist_mm`** against known city-pair great-circle distances, and |
| 1250 | across the antimeridian and pole to pole (where a naive `i32` coordinate |
| 1251 | subtraction overflows). |
| 1252 | - **tags**: `get_hw_id`, `parse_maxspeed` (`mph` ×1.60934, `knots` ×1.852, |
| 1253 | non-numeric -> 0), `turn:lanes` (`|` lanes, `;` indications, unknown -> |
| 1254 | `LANE_NONE`, count pad/truncate), and POI `classify` precedence including the |
| 1255 | rule that bare `railway`/`public_transport` values are *not* POIs. |
| 1256 | - **whole pipeline**: the fixture through `road_graph`, asserting the exact |
| 1257 | `metadata.bin` bytes, the `nodes.bin` sentinel, `edges.bin % 14 == 0`, Morton |
| 1258 | ordering, the full decoded edge set, the exact `road_names.bin`, and |
| 1259 | `lanes.bin`'s sparse index resolved by the same binary search the device uses — |
| 1260 | plus the same for `poi_extract`, and a two-runs-are-identical check for both. |
| 1261 | - **the v3 layouts at their boundaries**: a chain of exactly 256 points, which is |
| 1262 | the largest legal per-edge blob (1016 bytes) and so the worst case for the |
| 1263 | within-block `u16`; a graph whose *geometry* edges span three coarse blocks, where |
| 1264 | `g % 32 == 0` and `31` both fall inside it rather than under the sentinel; a graph |
| 1265 | where every edge stores a polyline and one where none does; on-disk rank/select |
| 1266 | over the presence bitmap, exercised standalone at byte and 512-bit block |
| 1267 | boundaries against a brute-force popcount, and past a single rank block; the |
| 1268 | writer's endpoint assertions firing on a mismatched chain; a graph with no |
| 1269 | `turn:lanes` at all, whose lane index is nothing but its own sentinel; and |
| 1270 | `cap_u32` refusing an edge count past the `u32` ceiling `nodes.bin` depends on. |
| 1271 | - **`--rounds` changes no byte**: the strongest check on the presence bitmap and |
| 1272 | both offset levels, run across `1`, `4` and `17` on two fixtures and both collapse |
| 1273 | paths. If any table were round-dependent it would say so. |
| 1274 | - **ring centroid**: that the repeated ring vertex is the one with the smallest |
| 1275 | `(lon, lat)`, so the centroid does not move when the ring's start rotates. |
| 1276 | Getting this wrong put small buildings metres off the old tool's output. |
| 1277 | |
| 1278 | ## Cross-checked against the C++ it replaces |
| 1279 | |
| 1280 | The C++ cannot be a byte-for-byte oracle (it was nondeterministic), so the port |
| 1281 | was validated *structurally*. Both toolchains were run over the same San Luis |
| 1282 | Obispo extract — the C++ built in WSL against libosmium 2.20 — and compared on |
| 1283 | invariants that do not depend on its thread-scheduling-dependent ordering: |
| 1284 | |
| 1285 | | Invariant | Result | |
| 1286 | |---|---| |
| 1287 | | `metadata.bin` magic / version / `node_count` | identical (88,666 nodes) | |
| 1288 | | `edge_count` | identical (181,481) | |
| 1289 | | `lanes.bin` length | identical (1,453,984 B) | |
| 1290 | | `road_names.bin` string set | identical (1,125 names) | |
| 1291 | | Node coordinates | every one matches; 7,164 differ by exactly one 1e-7 unit (1.1 cm) — see below | |
| 1292 | | Edge `(type, speed_limit, name)` groups + `dist_mm` | identical groups, every distance within 12 mm | |
| 1293 | | Out-degree sequence | identical | |
| 1294 | | POIs the C++ found | all 1,413 present, identical `name` + `type` | |
| 1295 | | Node/closed-way POI coordinates | all within one 1e-7 unit | |
| 1296 | | Relation POI centroids | 4 of 15 over 1 m, worst 3.1 m | |
| 1297 | |
| 1298 | Two deliberate differences: |
| 1299 | |
| 1300 | - **Coordinates are 1.1 cm more accurate.** The C++ recovered `lat_e7` as |
| 1301 | `(int32_t)(location.lat() * 1e7)` — truncating a double that libosmium had |
| 1302 | already divided by 1e7 — so ~8% of coordinates came out one unit low. This |
| 1303 | keeps the PBF's exact integer, which also shifts `dist_mm` by a few mm. |
| 1304 | - **Three extra POIs.** libosmium's assembler cannot close a ring whose member |
| 1305 | ways were cut off by the bbox, so it silently dropped three boundary relations |
| 1306 | (Los Padres National Forest, Santa Lucia Wilderness, Cuesta Ridge). The centroid |
| 1307 | approximation here still places them. Gaining a named POI is the better failure |
| 1308 | mode, and on an unclipped extract the question does not arise. |
| 1309 | |
| 1310 | ## Known limitations |
| 1311 | |
| 1312 | - **Relation POI centroids are approximated.** libosmium assembled true polygon |
| 1313 | rings (`MultipolygonManager` + `Assembler`); porting a ring assembler is a |
| 1314 | large piece of work on its own. Here a relation's outer ring is approximated by |
| 1315 | the deduplicated node ids of its `outer`-role member ways. That is exact when |
| 1316 | the ring is a single closed way; when it is split across several, the measured |
| 1317 | error was under 3.1 m across the sample above. POIs render as points at z12–z16, |
| 1318 | so this is not visible, but `poi_index.bin` is not byte-identical to the C++ for |
| 1319 | relation-derived POIs. Node- and closed-way-derived POIs match exactly. |
| 1320 | - **Closed-way areas** use `first ref == last ref` where libosmium compared end |
| 1321 | *locations*. Equivalent for real OSM data and it avoids needing a location |
| 1322 | index during the way pass. |
| 1323 | - **Memory.** `road_graph` holds a 2.5 GB node-id bitset (sized from the C++'s |
| 1324 | `BITSET_SIZE = 20e9`, so node ids at or above it are skipped exactly as |
| 1325 | before) plus the node and edge arrays: roughly 10 GB peak on California. Same |
| 1326 | ballpark as the C++, and it will not run on a small machine. |