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

Modern-Apps.git / scripts / maps / osm_ingest / README.md

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