Skip to content

fix(src-osm): rebuild way geometry in read_pbf_roads (supersedes #483) - #499

Merged
imagodata merged 2 commits into
mainfrom
fix/read-pbf-roads
Oct 1, 2026
Merged

imagodata merged 2 commits into
mainfrom
fix/read-pbf-roads

Conversation

@imagodata

Copy link
Copy Markdown
Owner

Supersedes #483 (fixes #482).

Why fix instead of remove

#483 deletes read_pbf_roads on the premise that no consumer is left ("MILOU migrated to GDAL in imagodata/milou#1136"). That migration was merged into MILOU's beta-erwan branch only. MILOU's active branch (dev_simon) still calls the function in three places:

MILOU call site Call
src/milou/io/ingest_osm_surface.py read_pbf_roads(pbf, tags=("surface",), target_crs=None) → expects id, surface
scripts/ingest_osm_road_network.py read_pbf_roads(pbf, target_crs="EPSG:31370", ...) → LineStrings for corridor edges and complex crossings
scripts/bench_osm_corridor.py read_pbf_roads(pbf, target_crs="EPSG:31370")

Deleting the function turns those call sites into an ImportError. MILOU then cannot rebuild its OSM surface artefact, which blocks the klinker surface-mapping fix and the motorway centerlines used by the Cat.2 drilling work. The function was broken, not unused, so this PR fixes it.

The defect

DuckDB spatial's ST_ReadOSM is a raw reader. Its columns are kind, id, tags, refs, lat, lon, ref_roles, ref_types (checked on duckdb 1.5.2 / spatial dc1996b), and it has no way geometry. The old query selected ST_AsWKB(geom), so every real call raised OSM_PBF_READ_FAILED. The only test used a fake connection that echoed the broken SQL back.

What changed (plugins/gispulse-src-osm/gispulse_src_osm/pbf.py)

Way geometry is rebuilt from node coordinates in three steps:

  1. Highway ways. Temp table of kind='way' rows that carry highway, keeping only the requested tags (stored internally as t0..tn).
  2. Referenced nodes. Temp table of only the nodes those ways reference, using a semi-join on unnest(refs). Each node is projected once with ST_Transform(ST_Point(lon, lat), 'EPSG:4326', <target>, always_xy := true).
  3. Lines. One (way_id, x, y) row per resolved ref, sorted ORDER BY way_id ASC, ord ASC, then assembled into LineStrings with a vectorised shapely.linestrings(coords, indices=...).

Behaviour:

  • Output contract unchanged. Columns are id (int64), highway, one string-dtype column per requested tag (NA when the tag is absent, same dtype when the result is empty), and LineString geometry, sorted by id. target_crs=None keeps EPSG:4326 in lon/lat order. The default target is still EPSG:31370. A non-string CRS (int, pyproj object) is also accepted.
  • always_xy. Without it, EPSG:4326 is read as (lat, lon) and the whole layer lands near (6.5e6, −3.4e6). A test catches this: it fails when always_xy is removed.
  • Dropped ways are counted, never silent.
    • gdf.attrs["diagnostics"] holds ways_total, ways_kept, ways_dropped_incomplete (< 2 resolved nodes), ways_dropped_degenerate (zero length) and ways_partially_resolved. The counts add up to ways_total.
    • gdf.attrs["partially_resolved_ids"] lists the partial ways. In those, a straight segment bridges the missing nodes.
    • A warning is logged when any way is dropped or partial.
  • New error codes.
    • OSM_PBF_DUPLICATE_IDS for non-deduplicated extracts, which would otherwise mix node positions.
    • OSM_PBF_OUT_OF_MEMORY (DuckDB OOM or MemoryError), whose recovery hint points to the DuckDB limit env vars.
    • OSM_PBF_SPATIAL_UNAVAILABLE when INSTALL/LOAD spatial or the DuckDB limits fail.
    • OSM_PBF_CRS_INVALID for an unknown target CRS.
  • Hardening.
    • Temp tables are qualified temp.main.*, so a caller's table with the same name is never dropped.
    • Every ORDER BY / sort is explicit ASC, so a caller connection's default_order has no effect.
    • Cleanup never masks the original error. This includes restoring disabled_optimizers, which is best-effort and logs a warning if it fails.
    • The connection is closed if INSTALL/LOAD spatial fails.
    • Tags named id or geometry are rejected.

connection_factory (the test hook) must now return a real DuckDB connection with spatial loaded. MILOU's tests monkeypatch read_pbf_roads as a whole, so they do not depend on the old fake-connection protocol.

Memory

Measured with /usr/bin/time -v (peak RSS of the whole Python process, ~200 MB of which is imports), 24 threads:

Extract PBF Highway ways Time Peak RSS Under GISPULSE_DUCKDB_MEMORY_LIMIT=1GB
Brussels region (openstreetmap.fr, polygon-clipped) 34 MB 108 940 (13 dropped, 125 partial) 1.4 s 0.46 GB ok
Luxembourg (Geofabrik) 48 MB 140 633 1.4 s 0.57 GB ok
Flanders (openstreetmap.fr) 534 MB 1 021 464 (104 dropped, 1 degenerate, 733 partial) 6.8 s 1.37 GB ok (also at 512 MB)
Belgium (Geofabrik, 2026-06-07) 686 MB 1 477 150 (0 dropped) 9.9 s 2.0 GB ok

Two traps found along the way are fixed and documented in the code:

  • Hash join built on the wrong side. DuckDB's build_side_probe_side optimizer flips the node semi-join, so the hash table is built over every node of the file instead of over the referenced ids. That cost 3.2 GB instead of 0.8 GB on Flanders. The optimizer is disabled for that one statement, and the previous disabled_optimizers value is restored afterwards. DuckDB versions without this optimizer simply skip it.
  • Ordered list aggregates. list(... ORDER BY ord) or list(ST_Point(...)) inside a GROUP BY cannot spill to disk, and ran out of memory under a 400 MB limit on Luxembourg. A sort, which can spill, followed by numpy/shapely assembly avoids both that and the deprecated -> lambda syntax.

Verification

  • Cross-check against GDAL's OSM driver on Luxembourg. All 140 144 highway lines GDAL produces are matched with identical geometry, both in EPSG:4326 (1e-6°) and EPSG:31370 (1 cm). The 489 extra ways are closed highway ways, which GDAL puts in its multipolygons layer.

  • Tests. tests/unit/test_src_osm.py now runs against real DuckDB ST_ReadOSM on a synthetic PBF. tests/unit/_synthetic_pbf.py hand-encodes OSMHeader + DenseNodes + Ways, with no osmium and no real OSM extract committed. The tests cover:

    • node order, including a 200k-ref case that fails if the ord sort is removed;
    • incomplete, partial and degenerate ways, and the diagnostics;
    • the tag filter and the MILOU column contract;
    • projection and axis order, and target_crs=None;
    • empty result, duplicate ids, OOM, invalid CRS and tags;
    • a caller connection that is left clean;
    • ways written out of id order;
    • duplicate way ids and duplicate node ids, with cleanup checked after the error.

    Mutation-checked: removing always_xy, the ord sort, the ways ORDER BY id, or the cleanup on error each makes a test fail. 29 tests pass.

  • Two adversarial reviews. All findings fixed or answered. The second review also:

    • ran MILOU's real load_pbf_surface_tags against this branch: columns id, highway, surface, geometry, osm_id like "4015956", 90 588 surface tags on Belgium;
    • checked DuckDB 1.0.0, 1.1, 1.2, 1.3, 1.4 and 1.5 on a real PBF (identical output).
  • ruff check / ruff format --check are clean.

  • Full local suite: 7 272 passed, 8 failed. The failures are in test_run_control, test_run_events and test_step_kinds, and are unrelated to this diff, which touches neither src/ nor those tests. In isolation, 5 still fail with steps.0.type: 'external' is not one of [...] (the external step kind is not registered in this local venv); the other 3 only failed under load.

Known limits

  • Closed ways cut by an extract boundary. If only the repeated node of such a way survives ([a, …missing…, a]), it counts as ways_dropped_degenerate. GDAL keeps such a way as a zero-length line.
  • Ways dropped for geometry lose their tags. A consumer reading only tags, like MILOU's surface lookup, also loses the tags of ways dropped for geometry reasons. That is 0 ways on the Geofabrik Belgium extract and about 100 on a polygon-clipped regional extract. A geometry=False mode could be a follow-up.
  • Memory limit vs process RSS. GISPULSE_DUCKDB_MEMORY_LIMIT bounds DuckDB's own buffer pool. ST_ReadOSM read buffers and the numpy/shapely assembly add on top: Belgium peaks at about 2 GB RSS whatever the limit.

CI on main was already red before this PR (release: 2.4.0 (#498) and the previous runs); this PR does not touch that.

Not closing #483 — leaving that to its author / maintainers.

🤖 Generated with Claude Code

sducournau and others added 2 commits October 1, 2026 11:15
…ing it

DuckDB spatial's ST_ReadOSM is a raw reader (kind, id, tags, refs, lat,
lon, ...) with no way geometry, so the old `ST_AsWKB(geom)` query failed
on every real call. #483 proposes deleting the function, but MILOU
(dev_simon) still calls it from ingest_osm_surface, ingest_osm_road_network
and bench_osm_corridor.

Rebuild LineStrings from node coordinates instead:
- temp table of highway ways with the requested tags only;
- temp table of the referenced nodes only, each projected once with
  ST_Transform(..., always_xy := true) (EPSG:4326 is otherwise read as
  lat/lon and the layer lands near (6.5e6, -3.4e6));
- (way_id, x, y) rows sorted by way and node position (spillable sort),
  assembled with shapely.linestrings(indices=...).

Ways with < 2 resolved nodes or zero length are dropped and counted in
gdf.attrs["diagnostics"] with a warning; partial ways are listed in
gdf.attrs["partially_resolved_ids"]. Duplicate ids, OOM, missing spatial
extension and invalid CRS get dedicated error codes. Output columns are
unchanged: id, highway, requested tags (string dtype), LineString geometry.

DuckDB's build_side_probe_side optimizer is disabled for the node
semi-join only (it hashed every node of the file: 3.2 GB -> 0.8 GB on
Flanders) and restored afterwards. Belgium (686 MB, 1.48 M ways): ~10 s,
2.0 GB peak RSS, also completes with GISPULSE_DUCKDB_MEMORY_LIMIT=1GB.
Geometry matches GDAL's OSM driver on Luxembourg, Brussels and Flanders.

Tests run real ST_ReadOSM on a hand-encoded synthetic PBF
(tests/unit/_synthetic_pbf.py); no real OSM extract is committed.

Supersedes #483. Fixes #482.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: sducournau <simon@imago.dev>
…f_roads

Catch duckdb.Error instead of Exception around the disabled_optimizers
toggle and the spatial-availability test fixture, index LineString coords
directly, and replace the noqa'd lambda in the synthetic PBF writer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: sducournau <simon@imago.dev>
@imagodata
imagodata merged commit 320f89f into main Oct 1, 2026
8 of 10 checks passed
@imagodata
imagodata deleted the fix/read-pbf-roads branch October 1, 2026 09:26
@imagodata imagodata mentioned this pull request Oct 1, 2026
imagodata pushed a commit that referenced this pull request Oct 1, 2026
Bump gispulse to 2.5.0 (pyproject, QGIS plugin metadata, uv.lock, which
had stayed at 2.3.0). Promote the changelog for #496 (PICC/UrbIS/GRB road
layers, counted pagination core, GRB face classification), #501 (GRB
road-crossings level evidence) and #499 (read_pbf_roads), mirrored into
docs-site FR and EN.

The PICC, UrbIS and GRB plugins import the counted pagination core that
first ships in 2.5.0, so their dependency floor is raised to
gispulse>=2.5.0 and their READMEs no longer point at integration/v2.4.

Capability count unchanged (144): the new GRB functions, including
build_grb_road_crossings, are not registered capabilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: sducournau <simon@imago.dev>
imagodata added a commit that referenced this pull request Oct 1, 2026
Bump gispulse to 2.5.0 (pyproject, QGIS plugin metadata, uv.lock, which
had stayed at 2.3.0). Promote the changelog for #496 (PICC/UrbIS/GRB road
layers, counted pagination core, GRB face classification), #501 (GRB
road-crossings level evidence) and #499 (read_pbf_roads), mirrored into
docs-site FR and EN.

The PICC, UrbIS and GRB plugins import the counted pagination core that
first ships in 2.5.0, so their dependency floor is raised to
gispulse>=2.5.0 and their READMEs no longer point at integration/v2.4.

Capability count unchanged (144): the new GRB functions, including
build_grb_road_crossings, are not registered capabilities.

Signed-off-by: sducournau <simon@imago.dev>
Co-authored-by: sducournau <simon@imago.dev>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

gispulse-src-osm: read_pbf_roads SQL references non-existent ST_ReadOSM column 'geom' (never worked)

1 participant