feat: surface / way type / SAC breakdown data source (map-matching) for #51 and #49 #62

Closed
maximus wants to merge 0 commits from feat/51-surface-mapmatch into deploy
Member

Data source for the surface / way-type / SAC breakdown that #51 (Komoot-style trail view) and #49 (colour track and profile by surface) need. Backend + typed client only; the UI is built separately in #51.

What it does

  • Map-matching, server side: GET /trail/{id}/surface (PocketBase, Go) reads the trail's stored GPX track and map-matches it with Valhalla trace_attributes (pedestrian costing, max_hiking_difficulty: 6, map_snap). Imported, recorded and routed tracks all go through the same path.
    • The track is thinned to one point per 10 m. Tracks over 200 km get wider spacing, so no track needs more than 20,000 points.
    • It is sent in chunks of at most 2,000 points / 50 km, well inside Valhalla's trace limits. Consecutive chunks share their boundary point.
  • Aggregation: each interval between two sampled points is split over the Valhalla edges it was matched to, in proportion to the matched length on each edge. Trimmed first and last edges (source/target_percent_along) are handled. Positions are track distances (cumulative haversine over the GPX points, the same measure the elevation profile uses), so hover and colouring line up with the profile.
    • An interval that ends on an unmatched point is unknown.
    • A chunk Valhalla cannot match (HTTP 400, e.g. outside the loaded tiles) is unknown.
    • Any other Valhalla error is transient: the endpoint answers 503 and nothing is cached.
  • Normalised vocabularies, raw value kept on every segment:
    • surface: paved (paved_smooth/paved/paved_rough) · gravel (compacted/gravel) · unpaved (dirt/path/impassable) · unknown
    • way: road (motorway…tertiary) · street (residential/unclassified/service/living_street…) · track · cycleway · path (footway/path/pedestrian/bridleway/sidewalk) · trail (path-like with SAC T2–T3) · alpine (path-like with SAC T4–T6) · steps · ferry · unknown
    • sac: T1…T6 · none (matched, no grade) · unknown
  • Cache: new sidecar collection trail_surface, one record per trail, keyed by a geometry hash and an algorithm version.
    • The breakdown is computed lazily on first view and not on save, so a bulk import does not flood Valhalla.
    • A changed track (different hash) or a new Version triggers a recompute on the next view.
    • Deleting the trail cascades to its record.
    • no_match results are cached for 7 days, then retried in case the tiles grow.
    • Concurrent first views of the same trail share one computation (singleflight). At most 2 computations run at once. A computation runs detached from the request (3 min timeout), so a closed tab does not waste it.
  • Security: the endpoint applies the trails view rule via CanAccessRecord, exactly like GET /remote/trail/{id}: owner, public, shared with the requester, or ?share=<link token>. Every refusal, an unknown id included, is the same 404, so the endpoint does not reveal whether a private trail exists. Refused requests never reach Valhalla. trail_surface has no API rules (superusers only), so the cache cannot be listed through the collection API. Responses are Cache-Control: private, no-cache.
  • Web: a SvelteKit proxy GET /api/v1/trail/{id}/surface (forwards only share), types and a store. No UI and no changes to valhalla_store.

Data contract

GET /api/v1/trail/{id}/surface[?share=<token>] returns 200:

{
  "trail": "abcdefghijklmno",
  "status": "ok",                 // or "unavailable" (then segments/summary are [])
  "reason": "no_match",           // only when unavailable: no_geometry | no_match | not_configured
  "source": "valhalla_trace_attributes",
  "version": 1,
  "geometryHash": "<sha256 hex>",
  "computedAt": "2026-11-05T17:00:00Z",
  "trackDistance": 3158.1,        // metres
  "matchedDistance": 3158.1,      // metres matched to the network
  "segments": [                   // ordered by kind (surface, way, sac), then start
    {"kind": "surface", "type": "unpaved", "raw": "path", "start": 0, "end": 3158.1, "distance": 3158.1},
    {"kind": "way", "type": "path",  "raw": "path", "start": 0, "end": 2134.7, "distance": 2134.7},
    {"kind": "way", "type": "trail", "raw": "path", "start": 2134.7, "end": 3158.1, "distance": 1023.4},
    {"kind": "sac", "type": "T1", "raw": "hiking", "start": 0, "end": 2134.7, "distance": 2134.7},
    {"kind": "sac", "type": "T2", "raw": "mountain_hiking", "start": 2134.7, "end": 3158.1, "distance": 1023.4}
  ],
  "summary": [                    // per kind, longest type first
    {"kind": "surface", "type": "unpaved", "distance": 3158.1, "share": 1},
    {"kind": "way", "type": "path", "distance": 2134.7, "share": 0.6759}
    // ...
  ]
}

Per kind, the segments are contiguous, cover 0..trackDistance, and neighbouring segments differ in type or raw. Two adjacent segments can share a type with different raw values; merge them by type for colouring if you want. Distances are rounded to 0.1 m. The endpoint answers 404 when the requester may not view the trail and 503 when Valhalla is temporarily unavailable.

For the #51 component, everything is in web/src/lib/models/trail_surface.ts and web/src/lib/stores/trail_surface_store.ts:

  • trail_surface_get(trailId, {share?, fetch?, signal?}) → TrailSurface | null. It returns null whenever there is nothing to render (404, 503, unavailable, network error), so the component can just render nothing.
  • trail_surface_segments(data, kind) gives {kind, type, raw, start, end, distance}[]. Its subset {type, distance} is what the component takes.
  • trail_surface_summary(data, kind) gives {kind, type, distance, share}[].
  • trail_surface_kind_has_data(data, kind): false when a kind is only unknown, or for sac only none/unknown.
  • trail_surface_segment_at(data, kind, metres): the segment under the cursor, for profile hover.

The first view of a trail waits for the map-matching. On the recorded fixtures (3–5 km) that is one request; long tracks take a few chunk requests. Load the breakdown client-side after the page renders.

⚠️ Deploy window needed: DB migration + first fork change in db/

  • This is the first divergence of the fork's db/ from upstream. Live runs flomp/wanderer-db:v0.21.2 (upstream). Shipping this means:
    1. Build the db image from deploy with image.yml (component: db).
    2. Switch homelab-flux apps/wanderer/wanderer.yaml from flomp/wanderer-db:v0.21.2 to git.mirus-tech.com/public/wanderer-db:deploy-<sha8>@sha256:….
    3. Add VALHALLA_URL=http://valhalla:8002 to the db container. Without it the endpoint answers unavailable/not_configured.
  • Migration 1793896331_created_trail_surface.go runs automatically on start (Automigrate) and creates the empty trail_surface collection. Down: it drops the collection. Back up pb_data before the switch. Rolling back to the upstream image leaves a harmless unused collection.
  • Valhalla's tiles cover only Provence-Alpes-Côte d'Azur. Trails elsewhere get unavailable/no_match (retried after 7 days).

Tests

  • db/services/trailsurface: normalisation tables, and aggregation against recorded trace_attributes fixtures (Valhalla 3.8.3, PACA tiles, recorded 2026-11-05, no live calls in tests):
    • roads and tracks around Sospel
    • SAC-graded paths at the Madone de Fenestre with GPS noise
    • an off-network point that Valhalla marks unmatched
    • trimmed-edge splitting, invalid answers, sampling, chunk limits/overlap, chunk-level no-match vs transient errors, geometry hash, response parsing, and the request body sent to Valhalla
  • db/trail_surface_access_test.go (real schema from migrations):
    • view-rule matrix: anonymous/other user/wrong or empty token/unknown id → 404; owner/shared/link token/public → 200. Refused requests never call Valhalla. Checked by mutation: with the access check disabled the test fails.
    • the collection has no API rules
    • cache hit, recompute on a track change, transient 503 not cached, cascade delete, no track / no Valhalla
    • the migration: fields, unique trail index, down migration
  • web: vitest for the store (URL/share forwarding, null on 404/503/unavailable/network error, abort rethrown, kind helpers, segment lookup).

Open questions

  • Costing is pedestrian for every trail. Bike tracks on roads closed to pedestrians may match worse; switching to bicycle by category is possible later.
  • Should the way vocabulary fold SAC in (trail/alpine), or keep way and SAC strictly separate? Both are available now.
  • Should we warm the cache on trail create/update? It is lazy today, on purpose.
  • BRouter's messages table is not used. Map-matching is the single source of truth, as agreed.

Refs #51, #49

🤖 Generated with Claude Code

Data source for the surface / way-type / SAC breakdown that #51 (Komoot-style trail view) and #49 (colour track and profile by surface) need. Backend + typed client only; the UI is built separately in #51. ## What it does - **Map-matching, server side:** `GET /trail/{id}/surface` (PocketBase, Go) reads the trail's stored GPX track and map-matches it with Valhalla `trace_attributes` (pedestrian costing, `max_hiking_difficulty: 6`, `map_snap`). Imported, recorded and routed tracks all go through the same path. - The track is thinned to one point per 10 m. Tracks over 200 km get wider spacing, so no track needs more than 20,000 points. - It is sent in chunks of at most 2,000 points / 50 km, well inside Valhalla's trace limits. Consecutive chunks share their boundary point. - **Aggregation:** each interval between two sampled points is split over the Valhalla edges it was matched to, in proportion to the matched length on each edge. Trimmed first and last edges (`source/target_percent_along`) are handled. Positions are **track distances** (cumulative haversine over the GPX points, the same measure the elevation profile uses), so hover and colouring line up with the profile. - An interval that ends on an unmatched point is `unknown`. - A chunk Valhalla cannot match (HTTP 400, e.g. outside the loaded tiles) is `unknown`. - Any other Valhalla error is transient: the endpoint answers 503 and nothing is cached. - **Normalised vocabularies, raw value kept** on every segment: - `surface`: `paved` (paved_smooth/paved/paved_rough) · `gravel` (compacted/gravel) · `unpaved` (dirt/path/impassable) · `unknown` - `way`: `road` (motorway…tertiary) · `street` (residential/unclassified/service/living_street…) · `track` · `cycleway` · `path` (footway/path/pedestrian/bridleway/sidewalk) · `trail` (path-like with SAC T2–T3) · `alpine` (path-like with SAC T4–T6) · `steps` · `ferry` · `unknown` - `sac`: `T1`…`T6` · `none` (matched, no grade) · `unknown` - **Cache:** new sidecar collection `trail_surface`, one record per trail, keyed by a geometry hash and an algorithm version. - The breakdown is computed lazily on first view and not on save, so a bulk import does not flood Valhalla. - A changed track (different hash) or a new `Version` triggers a recompute on the next view. - Deleting the trail cascades to its record. - `no_match` results are cached for 7 days, then retried in case the tiles grow. - Concurrent first views of the same trail share one computation (singleflight). At most 2 computations run at once. A computation runs detached from the request (3 min timeout), so a closed tab does not waste it. - **Security:** the endpoint applies the trails **view rule** via `CanAccessRecord`, exactly like `GET /remote/trail/{id}`: owner, public, shared with the requester, or `?share=<link token>`. Every refusal, an unknown id included, is the same 404, so the endpoint does not reveal whether a private trail exists. Refused requests never reach Valhalla. `trail_surface` has **no API rules** (superusers only), so the cache cannot be listed through the collection API. Responses are `Cache-Control: private, no-cache`. - **Web:** a SvelteKit proxy `GET /api/v1/trail/{id}/surface` (forwards only `share`), types and a store. No UI and no changes to `valhalla_store`. ## Data contract `GET /api/v1/trail/{id}/surface[?share=<token>]` returns 200: ```jsonc { "trail": "abcdefghijklmno", "status": "ok", // or "unavailable" (then segments/summary are []) "reason": "no_match", // only when unavailable: no_geometry | no_match | not_configured "source": "valhalla_trace_attributes", "version": 1, "geometryHash": "<sha256 hex>", "computedAt": "2026-11-05T17:00:00Z", "trackDistance": 3158.1, // metres "matchedDistance": 3158.1, // metres matched to the network "segments": [ // ordered by kind (surface, way, sac), then start {"kind": "surface", "type": "unpaved", "raw": "path", "start": 0, "end": 3158.1, "distance": 3158.1}, {"kind": "way", "type": "path", "raw": "path", "start": 0, "end": 2134.7, "distance": 2134.7}, {"kind": "way", "type": "trail", "raw": "path", "start": 2134.7, "end": 3158.1, "distance": 1023.4}, {"kind": "sac", "type": "T1", "raw": "hiking", "start": 0, "end": 2134.7, "distance": 2134.7}, {"kind": "sac", "type": "T2", "raw": "mountain_hiking", "start": 2134.7, "end": 3158.1, "distance": 1023.4} ], "summary": [ // per kind, longest type first {"kind": "surface", "type": "unpaved", "distance": 3158.1, "share": 1}, {"kind": "way", "type": "path", "distance": 2134.7, "share": 0.6759} // ... ] } ``` Per kind, the segments are contiguous, cover `0..trackDistance`, and neighbouring segments differ in `type` or `raw`. Two adjacent segments can share a `type` with different `raw` values; merge them by type for colouring if you want. Distances are rounded to 0.1 m. The endpoint answers 404 when the requester may not view the trail and 503 when Valhalla is temporarily unavailable. **For the #51 component**, everything is in `web/src/lib/models/trail_surface.ts` and `web/src/lib/stores/trail_surface_store.ts`: - `trail_surface_get(trailId, {share?, fetch?, signal?}) → TrailSurface | null`. It returns `null` whenever there is nothing to render (404, 503, unavailable, network error), so the component can just render nothing. - `trail_surface_segments(data, kind)` gives `{kind, type, raw, start, end, distance}[]`. Its subset `{type, distance}` is what the component takes. - `trail_surface_summary(data, kind)` gives `{kind, type, distance, share}[]`. - `trail_surface_kind_has_data(data, kind)`: false when a kind is only `unknown`, or for `sac` only `none`/`unknown`. - `trail_surface_segment_at(data, kind, metres)`: the segment under the cursor, for profile hover. The first view of a trail waits for the map-matching. On the recorded fixtures (3–5 km) that is one request; long tracks take a few chunk requests. Load the breakdown client-side after the page renders. ## ⚠️ Deploy window needed: DB migration + first fork change in `db/` - **This is the first divergence of the fork's `db/` from upstream.** Live runs `flomp/wanderer-db:v0.21.2` (upstream). Shipping this means: 1. Build the db image from `deploy` with `image.yml` (`component: db`). 2. Switch homelab-flux `apps/wanderer/wanderer.yaml` from `flomp/wanderer-db:v0.21.2` to `git.mirus-tech.com/public/wanderer-db:deploy-<sha8>@sha256:…`. 3. **Add `VALHALLA_URL=http://valhalla:8002` to the db container.** Without it the endpoint answers `unavailable/not_configured`. - Migration `1793896331_created_trail_surface.go` runs automatically on start (Automigrate) and creates the empty `trail_surface` collection. Down: it drops the collection. **Back up pb_data before the switch.** Rolling back to the upstream image leaves a harmless unused collection. - Valhalla's tiles cover only Provence-Alpes-Côte d'Azur. Trails elsewhere get `unavailable/no_match` (retried after 7 days). ## Tests - `db/services/trailsurface`: normalisation tables, and aggregation against **recorded `trace_attributes` fixtures** (Valhalla 3.8.3, PACA tiles, recorded 2026-11-05, no live calls in tests): - roads and tracks around Sospel - SAC-graded paths at the Madone de Fenestre with GPS noise - an off-network point that Valhalla marks unmatched - trimmed-edge splitting, invalid answers, sampling, chunk limits/overlap, chunk-level no-match vs transient errors, geometry hash, response parsing, and the request body sent to Valhalla - `db/trail_surface_access_test.go` (real schema from migrations): - view-rule matrix: anonymous/other user/wrong or empty token/unknown id → 404; owner/shared/link token/public → 200. Refused requests never call Valhalla. Checked by mutation: with the access check disabled the test fails. - the collection has no API rules - cache hit, recompute on a track change, transient 503 not cached, cascade delete, no track / no Valhalla - the migration: fields, unique trail index, down migration - `web`: vitest for the store (URL/share forwarding, null on 404/503/unavailable/network error, abort rethrown, kind helpers, segment lookup). ## Open questions - Costing is `pedestrian` for every trail. Bike tracks on roads closed to pedestrians may match worse; switching to `bicycle` by category is possible later. - Should the way vocabulary fold SAC in (`trail`/`alpine`), or keep way and SAC strictly separate? Both are available now. - Should we warm the cache on trail create/update? It is lazy today, on purpose. - BRouter's `messages` table is not used. Map-matching is the single source of truth, as agreed. Refs #51, #49 🤖 Generated with [Claude Code](https://claude.com/claude-code)
GET /trail/{id}/surface map-matches the stored GPX track with Valhalla
trace_attributes (thinned to 10 m, chunks of <=2000 points / 50 km) and
aggregates the matched edges into contiguous per-kind segments in track
distances, with normalised types (surface, way, sac) and the raw values.

Results are cached in the new superuser-only trail_surface collection
(one record per trail, keyed by geometry hash and algorithm version) and
computed lazily on first view. Access follows the trails view rule; every
refusal is a 404. Valhalla is read from VALHALLA_URL.

Refs #51, #49

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP
feat(web): typed client for the trail surface breakdown
All checks were successful
CI / web (push) Successful in 58s
CI / go (push) Successful in 13m27s
e42ffb5258
Adds the GET /api/v1/trail/{id}/surface proxy (forwards only the share
token), the TrailSurface types and trail_surface_get plus helpers that
split segments and totals by kind and find the segment at a distance,
for the #51 trail view and #49 track colouring.

Refs #51, #49

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP
Author
Member

Shipped via batch PR #64 (deploy 0d0d85a4), which merged this branch head unchanged; web part live since 2026-11-05 ~19:30 CET in wanderer-web:deploy-676a7c62 (homelab-flux #843). Forgejo does not mark stacked PRs as merged, so I am closing this by hand.

🤖 Generated with Claude Code

The db part (migration + /trail/{id}/surface route) goes live with the db image switch (homelab-flux #837).

Shipped via batch PR #64 (`deploy` 0d0d85a4), which merged this branch head unchanged; web part live since 2026-11-05 ~19:30 CET in `wanderer-web:deploy-676a7c62` (homelab-flux #843). Forgejo does not mark stacked PRs as merged, so I am closing this by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code) The db part (migration + `/trail/{id}/surface` route) goes live with the db image switch (homelab-flux #837).
maximus closed this pull request 2026-11-05 19:10:45 +00:00
All checks were successful
CI / web (push) Successful in 58s
Required
Details
CI / go (push) Successful in 13m27s
Required
Details

Pull request closed

Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
public/wanderer!62
No description provided.