Skip to content

feat(map): tropospheric ducting overlay (Open-Meteo, worldwide, off by default) - #2436

Merged
efiten merged 48 commits into
Kpa-clawbot:masterfrom
zfouts:feat/tropo-ducting
Nov 27, 2026
Merged

efiten merged 48 commits into
Kpa-clawbot:masterfrom
zfouts:feat/tropo-ducting

Conversation

@zfouts

@zfouts zfouts commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an optional tropospheric ducting overlay to the maps. It shows where the lower atmosphere is able to bend or trap radio signals beyond line of sight, and where the model finds a trapping layer that may carry LoRa at the site's frequency (a model estimate, not a yes/no).

Mesh operators regularly see unexpectedly long links: packets heard hundreds of kilometres away, often over water or on still, clear nights. Tropospheric ducting is one possible cause; others are misresolved hops (hash prefix collisions), high sites and line of sight over water, and the overlay cannot tell which applied. What it adds is the atmospheric side: whether conditions favoured unusual bending at that place and time. It lets operators:

  • explain long-distance receptions while they happen;
  • avoid treating a temporary duct as a real, stable link (for example, when planning repeaters);
  • see when conditions are likely in the next 48 hours.

There is no free ducting map that can be embedded: the well-known forecasts are published as images, with no API or reuse terms. So CoreScope computes ducting itself from open weather-model data, and draws it the way established ducting forecast maps do: a field of colour bands over the region, clear where conditions are normal and rising from purple through blue, cyan, green, yellow, orange and red to pink as the refractivity gradient of the lowest 1.5 km strengthens.

The feature is off by default. When it is off, nothing changes: no outbound requests, no new UI, and /api/ducting returns 404.

Rebased onto master (c8349976) now that #2434 has merged. The branch carries only the ducting work: the 44 commits listed under Commits. Every hash below is the rebased one; older hashes in the history sections refer to earlier heads. It is a draft so CI can run; there is no separate issue.

Master merged in for v3.19.0 (3145dc90, master at 7beed94a). It conflicted only in CHANGELOG.md (the entry moved under a new [Unreleased] / Added) and in a test-all.sh suite line. Re-tested: go vet and go test in cmd/server, test-all.sh and lint, 0 errors.

Earlier merge (10e5220f, master at 007ba78a, with #2442 and #2450): no conflicts. Re-tested on that merge: go vet and go test in cmd/server, test-all.sh, lint (0 errors), the CSS variable check and the ducting unit suite (102/102).

Earlier merge (d9300b34, master at 6ab97f52, with #2451–#2454): no conflicts, so the hashes below still hold. Re-tested on that merge: go vet and go test across all modules, test-all.sh (all suites passed); E2E against local servers: ducting 34/34 (fake Open-Meteo), map providers 24/24, providers harness 16/16, map teardown races 19/19, and master's new node analytics Heard-by suite.

Data source

Open-Meteo serves weather-model data at pressure levels: temperature, relative humidity and geopotential height. The free API is for non-commercial use, and the data is CC BY 4.0. The overlay credits it in the map attribution.

Running your own Open-Meteo is recommended, not required. The public API works out of the box for a non-commercial site, and the call budget keeps one instance inside the free limits, by coarsening the grid or refreshing less often when it has to. A self-hosted instance has no call limits, so CoreScope switches the budget and pacing off: the grid, the refresh interval and the number of replicas are no longer limited by API calls. The cost is running that instance, which downloads and stores the model data itself. Self-hosting is required only for commercial use, because of Open-Meteo's terms.

model Open-Meteo model Coverage Levels used (lowest ~3 km)
gfs NOAA GFS (gfs_global) Worldwide 13: every 25 hPa, 1000–700 hPa Default
icon DWD ICON (icon_global) Worldwide 8: 1000/975/950/925/900/850/800/700 hPa Option
rrfs-conus NOAA RRFS (ncep_rrfs_conus) US only every 25 hPa Explicit opt-in. The server logs a warning naming its coverage, and cells outside it are skipped

Models left out:

  • ECMWF IFS has no 975 hPa level, which is too coarse near the ground.
  • HRRR is discontinued at the end of November 2026; RRFS is its successor.

The default works anywhere in the world; a regional model is never used unless the operator names it.

How it works

Calculation (cmd/server/ducting_calc.go)

For each grid cell and forecast hour:

  1. Water vapour pressure: e = RH/100 · 6.1121 · exp(17.502·t / (240.97 + t)) hPa, with t in °C.
  2. Radio refractivity, ITU-R P.453: N = 77.6/T · (P + 4810·e/T), with P and e in hPa and T in K.
  3. Modified refractivity: M = N + 0.157·h, with h in metres above ground. The surface point comes from the 2 m values, and pressure levels below the ground are dropped.
  4. Trapping layers (M decreasing with height) in the lowest 3 km. For the strongest one: type (surface-based or elevated), base, top, strength ΔM, and the lowest frequency it can trap, f_min = 120000 / (d · √ΔM) MHz (the waveguide cutoff λ_max ≈ 0.0025 · d · √ΔM).
  5. Each cell and hour gets a class: no data, normal, super-refraction (dN/dh ≤ −79 N/km), elevated duct, or surface-based duct.
  6. Map field value n: the mean refractivity gradient over the lowest 1.5 km above ground, (N(1500 m) − N(2 m)) / 1.5 km, with N(1500 m) interpolated between the bracketing levels (ITU-R P.453 style). The map is coloured by n rather than by the steepest gradient between two adjacent levels: averaged over the layer that matters for propagation, it is far less noisy, where a single thin layer (often the 2 m surface step over land) dominates the steepest-gradient value. The duct analysis (steps 4–5, the LoRa answer) is unchanged.

Server

  • Config: a new ducting section. Only enabled is required:
    "ducting": { "enabled": true }
    Optional keys: model, area, marginDeg (default 5°), gridStepDeg (default 0.5°, allowed 0.25–2), maxPoints (default 450), refreshMinutes (default 360, matching GFS runs), forecastHours (default 48) and baseUrl. They are documented in docs/deployment.md.
  • Grid: by default the forecast covers the whole bounding box of the mesh's visible nodes heard in the last 14 days (same visibility rule as /api/nodes; with 5 or more nodes, nodes farther than 500 km, or 4 times the median distance, from the nodes' median position are left out, the farthest first and at most 10% of them, or one in a mesh of fewer than 20), grown by marginDeg (5°) on every side, filled edge to edge, so the map's normal view is covered rather than patches around nodes. The longitude span is the smallest one containing every node, and a box across the antimeridian is split in two. Alternatively an operator can set an area box.
    • When there are more cells than maxPoints, the step doubles (0.5, 1, 2, 4, up to 8°) until they fit. The default 450 keeps a city-sized mesh plus its margin at 0.5° (21 × 21 = 441 cells).
    • A mesh spread so widely that even 8° cells cannot fill its box (several continents) falls back to the regions around its nodes, and the server logs that once per refresh.
  • Staying inside the free tier. Open-Meteo counts a request with more than 10 variables as several calls; GFS needs 42 variables, so each point costs 4.2 calls.
    • The server estimates its daily usage and coarsens the grid to stay under 8,000 calls a day. The free limit is 10,000.
    • Hard caps of 4,500 calls an hour and 9,500 a day apply on top.
    • Requests go in batches of 50 points. Against the public API they are paced at 400 calls a minute.
    • With a self-hosted Open-Meteo (baseUrl not api.open-meteo.com) the daily budget and the hourly and daily caps do not apply, since that instance has no limits, and requests are not paced. The startup log says "(self-hosted: no call budget)".
  • Failures:
    • retries back off 5, 10, 20… minutes, up to the refresh interval;
    • after an HTTP 429 or a spent budget, the next try is at least 60 minutes later;
    • the last good forecast keeps being served, and an expired one is reported as such.
    • Error text never includes the request URL.
  • Storage: an in-memory snapshot only, served read-only at GET /api/ducting. Nothing is written to any database, so the read-only DB invariant (bug(db): vacuumOnStartup fails with SQLITE_BUSY when ingestor + server share DB (auto_vacuum migration #919 broken in single-container topology) #1283) is unchanged.
  • Client config: /api/config/client gets a ducting block (model, label, step, attribution) only when the feature is enabled, so the frontend offers the overlay only then. baseUrl is never sent to clients.
  • Self-hosting (recommended, optional): baseUrl points the server at a self-hosted Open-Meteo instance (AGPL). It has no call limits and no non-commercial restriction. It is required only for commercial deployments.

How often the forecast is generated

The forecast is generated on a schedule, a few times a day, not on demand:

  • Server, from Open-Meteo:
    • one fetch shortly after the server starts, then the next one refreshMinutes after each refresh finishes;
    • the default is 360 minutes, 4 times a day, matching the 4 daily GFS runs; the allowed range is 60–1440;
    • each fetch covers the next 48 hours, hourly (forecastHours), is analysed once, and is kept in memory.
  • Browsers, from the server:
    • they read the server's in-memory copy at GET /api/ducting, every 30 minutes while the overlay is shown, or every minute until the first data arrives;
    • they never call Open-Meteo, so the number of viewers does not change the API usage.
  • Drawing: each browser draws the overlay locally from that data, only when new data arrives, the forecast time changes or the theme changes. Panning and zooming never redraw it.
  • Between refreshes: the 48-hour forecast keeps the timeline useful. The overlay opens at the current hour.
  • Known limit: the schedule follows the server's start time, not the clock, so it is not aligned to when each GFS run becomes available. The shown forecast can therefore be up to a few hours older than the newest run, still well inside its 48-hour window. Aligning refreshes to run availability would be a possible follow-up.

Frontend (public/map-ducting.js)

  • Tropospheric ducting appears in the map's Overlays group on the Map, Live and Repeater Planner pages, through the shared overlay builder from feat(map): more tile providers (topo, satellite, gray, vector), hillshade overlay and custom tile servers #2434.
  • A banded field, like a forecast map. One canvas-backed image layer per map, in its own pane above the basemap and below labels and markers.
    • Coloured by n: clear above −44 N/km, then one flat colour per band — −44 purple, −48 blue, −54 cyan, −58 green, −62 yellow, −70 orange, −80 red, −90 and stronger pink — at one opacity, with crisp edges between bands. The thresholds were tuned empirically on archived forecast data across several regions. Legend labels: Normal / Above normal / High / Very high; colour means more bending than usual (warm, humid air shows above normal even without an inversion), not a confirmed duct.
    • Values are interpolated with separable Catmull-Rom bicubic between cell centres (bilinear next to missing data), at 48 px per cell, so band edges are smooth curves; drawn in Web Mercator rows so it lines up with the basemap at every zoom.
    • Cells where the model finds a trapping layer that may carry LoRa get a dashed outline: its lowest trapped frequency (as shown) is at most this site's LoRa frequency (los.frequencyMhz), or at most 915 MHz when none is set or it is left at its default of 910.525 MHz. It is a model estimate: the levels are ~200–250 m apart, so thin ducts are invisible.
    • The edge of the forecast area is a faint dotted line, and the field fades out over the last cell toward it.
    • Cost: redrawn only when data arrives, the forecast hour changes or the theme changes, never on pan or zoom. Median redraw 15–22 ms for a 30 × 16 cell grid at 1440 × 892 px.
  • Controls:
    • One panel sits bottom-left: a title bar (collapse chevron, drag grip, Reset), the forecast timeline, and the legend: the band bar labelled Normal / Above normal / High / Very high with the caption "Refractivity gradient over the lowest 1.5 km (N/km)", the dashed (LoRa) and dotted (forecast edge) line keys and the model attribution.
    • The forecast timeline is a scrollable strip with day labels at local midnights and hour labels at 06/12/18; the time under the centre marker is shown. Scroll, drag, mouse wheel or click picks a time; ◀ ▶ step, Now returns to the current hour, and the keyboard works (arrows, Page Up/Down for a day, Home/End). It is a role=slider for screen readers and starts at the current hour.
    • The chevron collapses the legend; the timeline stays, and so does the status line under the forecast time (loading, being prepared, unavailable, or out of date). On screens wider than 600 px the panel can be dragged anywhere on the map, by pointer or by arrow keys on the grip; it stays inside the map and steps aside from page panels that would cover its buttons. Position and collapsed state are remembered in localStorage.
    • On narrow screens the panel stays docked, starts collapsed, and moves above the attribution and Live's feed bar.
  • Cell popup: clicking anywhere in the field (one map click handler that never stops the click, so the Planner and Live keep working; the overlay has no interactive layers) shows that cell's type, its gradient over the lowest 1.5 km, and for a trapping layer in the model its base and top, strength, lowest trapped frequency (≈, model estimate) and, per judged frequency (this site's, or 868 and 915 MHz), "LoRa … MHz: possibly trapped / not trapped by this layer". It notes that the model's ~200 m level spacing can't resolve thinner layers.
  • Theme: colours come from --mc-duct-s1…--mc-duct-s8, --mc-duct-alpha (0.8), --mc-duct-lora and --mc-duct-edge CSS variables, defined for light and dark, and the field is redrawn on a theme change.
  • Lifecycle: the overlay refreshes every 30 minutes while it is shown, and every minute while it has no data yet (for example, right after the server starts). A timer aimed at the top of each hour moves the now line, and the shown hour unless the user picked one, without a request. These requests read the server's in-memory copy and never reach Open-Meteo. A generation token and an AbortController mean that a layer removed mid-fetch never touches the map again, and teardown releases the field, every listener and control.
  • Fixes found while testing:
    • an expanded layer picker now stacks above the other map corners, so the legend no longer covers it;
    • the overlay's canvas renderer works around a Leaflet 1.9.4 bug. Leaflet's _updatePaths, which runs on every map move, redraws at once but leaves a queued animation-frame redraw orphaned. Switching the overlay off before that frame threw reading 'clearRect'. The renderer subclass cancels the queued frame first.

Limitations, stated in the UI and docs

  • Vertical resolution. 25 hPa levels are about 200–250 m apart near the ground, so thinner ducts (including most evaporation ducts over the sea) cannot be seen. The overlay is an indicator, not a guarantee.
  • Horizontal resolution. This is model-grid scale (tens of kilometres), so local terrain effects are not captured. The smooth field is interpolated between cell centres and shows no detail finer than the grid.
  • Licensing. The free Open-Meteo tier is non-commercial, so commercial sites must self-host it and set baseUrl. For every other site self-hosting is optional but recommended: it removes any concern about API call limits.
  • Several server replicas. Each replica of one installation fetches the forecast on its own, so N replicas use N times the calls and can briefly serve different forecasts. On a test deployment with five replicas behind one address, the public API answered HTTP 429 within minutes; pointed at a self-hosted Open-Meteo, all five refreshed. The docs tell multi-replica sites to self-host. One shared fetcher would be a follow-up.

Out of scope

  • Path-specific propagation modelling.
  • Correlating actual long-distance receptions with ducting events. This would be a natural follow-up.
  • Historical ducting data (the next step, not yet). The goal is to show the past 2 to 7 days next to the forecast, and to line them up with long links the mesh actually heard. It isn't in this PR because of API calls:

Real-data check

Two servers ran against the real Open-Meteo API, using the synthetic dataset from #2434:

Worldwide nodes (early build, node cells only) US Gulf coast (area 22–38° N, 106–76° W), self-hosted Open-Meteo
Cells 119 at 1° (coarsened from 0.5° to fit maxPoints) 902 at 0.75°
Forecast 48 hours 48 hours
API calls per refresh about 500 about 3,800 (no call budget: self-hosted)
Refresh time 71 s 15 min (paced at 400 calls/min)
/api/ducting size 90 KB (13 KB gzipped) 863 KB (132 KB gzipped)
Field coloured (n ≤ −44) — 56.4% of cell-hours
Strong or above (n ≤ −62) — 4.8%
Median n — −45 N/km

Shares are over all cells and hours with data. The Gulf server uses area to stand in for a regional mesh: the synthetic dataset's nodes are spread worldwide, which by default triggers the fallback described under Grid. The Go server's own gzip is opt-in (compression), since the reverse proxy usually compresses.

Every automated test uses a fake Open-Meteo server instead (tests/e2e/lib/fake-open-meteo.js), so CI never calls the real API.

Screenshots

Real GFS forecast data (served by a self-hosted Open-Meteo) over the US Gulf coast, Texas to Florida (forecast area 22–38° N, 106–76° W, 0.75° cells), at the forecast hour with the most strong cells in this run (Sat 21 Nov, 08:00 local). The view is framed inside the forecast area. Headless Chromium at 1280×800, Map Controls collapsed, on the keyless OSM Gray basemap. Click a thumbnail for the full size. The images are on a separate assets branch, so they are not in this diff.

Map, light: bands of the lowest-1.5 km refractivity gradient; dashed outlines are ducts that may carry LoRa (model estimate)
Map, light: bands of the lowest-1.5 km refractivity gradient; dashed outlines are ducts that may carry LoRa (model estimate)
Map, dark
Map, dark
Live page
Live page
Zoomed in over the Gulf
Zoomed in over the Gulf
Popup: an elevated duct with its gradient (−54 N/km), lowest trapped frequency ≈ 700 MHz, and a verdict per frequency: LoRa 868 MHz and 915 MHz possibly trapped (model estimate); the dotted line is the edge of the forecast area
Popup: an elevated duct with its gradient (−54 N/km), lowest trapped frequency ≈ 700 MHz, LoRa 868 and 915 MHz each possibly trapped (model estimate); the dotted line is the edge of the forecast area

Panel and timeline (same real GFS forecast over the Gulf coast on the Carto basemap, 1440×900 and 390×844; the forecast was refreshed just before, so the panel opens at its first step, the current hour):

Desktop, light: title bar, timeline and legend
Desktop, light: title bar, timeline and legend
Desktop, dark: panel dragged to the top right, Reset shown
Desktop, dark: panel dragged to the top right, Reset shown
Timeline at a midnight: the next day pushes the previous label off
Timeline at a midnight: the next day pushes the previous label off
Phone, light: docked and expanded
Phone, light: docked and expanded
Phone, dark: collapsed by default, timeline kept
Phone, dark: collapsed by default, timeline kept
Timeline, dark: keyboard focus, five hours ahead
Timeline, dark: keyboard focus, five hours ahead

Testing

Added tests

  • Go:

    • ducting_calc_test.go: the physics against hand-computed profiles, including the mean gradient of the lowest 1.5 km (−30.04 N/km, arithmetic in the test);
    • ducting_config_test.go: defaults, bounds, models, budget;
    • ducting_grid_test.go: cells, step doubling, wrapping at ±180°;
    • ducting_source_test.go: batching, pacing, caps for the public API only, 429, URL-free errors;
    • ducting_service_test.go: refresh loop, backoff, last-good snapshot, expiry, 404 when disabled.
  • Frontend unit: tests/unit/test-map-ducting.js, 94 tests (timeline layout across DST changes, nearest-time picking, day-label push-off, keyboard steps, rapid steps during a smooth scroll (a slow page must not pick an in-between hour), panel position clamping and fractions, stored preferences including a throwing localStorage, colour bands and their edges, bicubic interpolation (exact at cell centres, continuous, separable equals the naive 4×4, bilinear fallback), the n field and missing data, Mercator rows, lattice sampling and edge fading, forecast-area outline runs, LoRa outlines, time index, popup, legend, retry cadence, restyle without rebuilding, fetch race and teardown).

  • E2E: tests/e2e/test-map-ducting-e2e.js, 25 checks against the fake Open-Meteo server:

    • the client config never carries baseUrl, and the fake saw only valid, batched requests;
    • cells and classes match the server data, and the field's pixels match n through Leaflet's own projection (band colours, calm air transparent);
    • the timeline (keys, wheel, drag, click, Now), the popups and the theme restyle work, and the map never pans or zooms while the timeline is used;
    • the panel collapses, moves by its grip without moving the map, keeps its place and state across a reload, and Reset docks it again; the strip is at least 220 px wide at 1440×900 and 200 px at 390×844, with no clipped day label;
    • the panel overlaps no other map control, and the expanded picker stays on top;
    • disabling and re-enabling leave no duplicates;
    • the Live and Planner pages work, and without ducting in the client config there is no entry;
    • the dotted forecast-area edge lies exactly on the area's outer boundary;
    • the Leaflet redraw case;
    • the fake's error scenarios.

    The narrow layouts (375 and 320 px) were checked by hand in the browser review, in light and dark, on the Map, Live and Planner pages.

  • Race stress: a new scenario g in tests/e2e/test-map-race-stress-e2e.js. It mixes random toggling (API and picker), theme flips, navigation, timeline scrolls, and delayed, pending and failing /api/ducting answers. It then checks the final state, theme listener counts and teardown.

  • Backoff scenarios: the fake can answer pending, HTTP 500, HTTP 429 or null data. In each case the server sent exactly one request in two minutes, with no retry loop.

Local runs

Two full passes, each on a fresh clone of the branch:

  • Pass 1 at 9cdcda0d.
  • Pass 2 at 6dd39613, plus targeted reruns for the three later commits.

Both passes used CI-equivalent servers. The E2E suites ran in three shards, each on a fresh fixture: the main server (13581), user management (13582), and a split frontend (13591 + 8788).

Check Pass 1 Pass 2
Unit gate (test-all.sh, inventory) from a copy with no node_modules, as in CI ✅ ✅
npm run lint ✅ 0 errors ✅ 0 errors
gofmt, go vet, Go server and ingestor tests (Docker) ✅ server coverage 88.4% ✅
Go -race: the ducting tests, the full server, the full ingestor ✅ ✅
CI-only checks: Dockerfile, disk monitor, service user, CSS variables, XSS gate, proto ✅ not rerun
Every E2E suite deploy.yml runs, plus 3 slide-over flake-gate runs ✅ 142/142 ✅ 142/142
Ducting E2E against the fake Open-Meteo ✅ 22/22 ✅ 23/23 (planner on, no skips)
Backoff: pending, HTTP 500, HTTP 429 and null-data scenarios, 2 minutes each ✅ exactly 1 request each ✅ exactly 1 request each
Race stress gate, all scenarios a–g, 20 iterations each ✅ seeds 101, 202; ❌ 303 (see below) ✅ seeds 404, 505, 606
Scenario g, 50 iterations ❌ seed 303 → ✅ after the fixes; ✅ seeds 303, 707, 808 (150/150)
Perf A/B against #2434's branch (288aa396), overlay off ✅ 0 reds, 169 budgets passed skipped: no change affects the overlay-off path
Gallery, including the ducting entries on real data ✅ ✅
Carto key scan, tree and history ✅ 0 hits ✅ 0 hits

What the stress gate found:

  • Pass 1, seed 303. It hit a real bug: the Leaflet canvas clearRect error. It is fixed in 6dd39613, with an E2E check that fails on the old code with the same error.
  • Pass 2, seed 303 iteration 43. This was deterministic. In it, the layer correctly showed "unavailable" after a chaos HTTP 500. The harness, however, judged by whichever delayed request finished last, which was an older, already-aborted one. That is fixed in 272f892c.
    • It also exposed a real UX gap: the overlay waited its full 30-minute refresh after a failed or pending answer. That is fixed in d5cbb992 with a 1-minute retry while there is no data. Its unit test fails on the old code.

Field redesign (3bfb0016, b1e8add4, e7e21451), run after the two passes against servers built from that code:

Check Result
gofmt, go vet, Go server tests, -race on the ducting, OpenAPI and client-config tests (Docker) ✅
test-all.sh, npm run lint ✅ 0 errors
CSS variable lint (check-css-vars.js) and the XSS --diff gate against master ✅ 0 undefined; ✅
Ducting E2E against the fake Open-Meteo, planner on ✅ 24/24
Stress scenario g, seeds 303 and 707, 20 iterations each ✅ 40/40
Full stress gate, scenarios a–g, seed 909 ✅ (f: 50/50, others 20/20 each)
Gallery: the five ducting entries on real Gulf coast data, each image checked by eye ✅

Full coverage (01305948, b6e4e4c1, 8813167e), run against servers built from that code:

Check Result
gofmt, go vet, Go server tests, -race on the ducting, OpenAPI and client-config tests (Docker) ✅
test-all.sh, npm run lint, CSS variable lint ✅ 0 errors; ✅ 0 undefined
Ducting E2E against the fake Open-Meteo, planner on (default coverage: 442 cells at 0.5°) ✅ 25/25
Stress scenario g, seeds 303 and 717, 20 iterations each ✅ 40/40
Full stress gate, scenarios a–g, seed 919 ✅ (f: 50/50, others 20/20 each)
Gallery: the five ducting entries on the real Gulf coast data, each image checked by eye ✅

Banded field coloured by the mean gradient (812321bc, df3737c5, 69127d60, c98b04cd), on the tree rebased onto #2434's latest head:

Check Result
gofmt, go vet, Go server tests, -race on the ducting, OpenAPI and client-config tests (Docker) ✅
test-all.sh, npm run lint, CSS variable lint ✅ 0 errors; ✅ 0 undefined
Ducting E2E against the fake Open-Meteo, planner on ✅ 25/25
Stress scenario g, seeds 303 and 727, 20 iterations each ✅ 40/40
Full stress gate, scenarios a–g, seed 939 ✅ (f: 50/50, others 20/20 each)
Field redraw time, 30 × 16 cells at 1440 × 892 px (headless Chromium, 12 forecast-time changes) median 15–22 ms
Real data from a self-hosted Open-Meteo (Gulf coast, 902 cells), five screenshots checked by eye ✅

Seed 939 first failed scenario e (two tabs, overlay mirroring) on one iteration. It reproduced on #2434's own code, so the fix went there: bd36b634, with an E2E check that fails without it.

Re-review fixes (1af37db1 server, 97392f99 overlay); details in the reply comment. What changed:

  • the status line now stays visible when the panel is collapsed;
  • a panel laid out while hidden puts its timeline on the current hour;
  • LoRa at the default los.frequencyMhz judges 868 and 915 MHz;
  • an hourly tick moves the shown hour;
  • the outlier trim drops the farthest nodes up to the cap;
  • the ETag is weak.

Re-verified:

  • ducting unit 102/102, also under TZ America/Chicago, Australia/Lord_Howe and Europe/Brussels;
  • test-all.sh, lint 0 errors, CSS variable check;
  • go vet and go test in cmd/server;
  • a 304 for the weak and the bare ETag, with and without gzip, on a running server;
  • the ducting E2E four times on fresh servers: 36/36 three times. The first run failed one test that these commits don't touch ("a moved, collapsed panel keeps its place and state across a reload": the cells did not appear within 25 s).

The two bugs were also reproduced in Chromium with real Leaflet, before and after the fix, on the plain and the Istanbul-instrumented build.

Deep linking of the overlay state and hour is tracked in #2459.

Third maintainer review fixes (55ddb2ca, 3dd63059):

  • After an incomplete fetch, the early retry is taken only when the public API's call budget can afford it and every regular refresh in the following 24 h. Otherwise the next refresh comes after refreshMinutes, and the failed cells are carried over meanwhile. Self-hosted sources still retry early.
  • Simulated over 48 h with one batch failing for good: before, there was a 26 h gap with 5 budget refusals; after, refreshes come about every 6 h with no refusals. A virtual-clock test pins this.
  • /api/ducting now carries a carried count.
  • The docs state the profile rules (pressure levels less than 30 m above the 2 m point are ignored; a missing 2 m point means no data).
  • A Go test keeps the frontend's 910.525 MHz default in sync with the server's.

Internal review fixes (b87dbdff server, 5ab3d04b overlay):

  • The corner lift no longer forces a layout on every map layer add or remove. Adding and removing 2,000 markers with the overlay on took about 9.7 s before and about 135 ms after.
  • A partial fetch keeps the failed cells from the previous forecast and retries on the failure backoff.
  • Pressure levels less than 30 m above the 2 m point are ignored.
  • A missing 2 m point gives no data.
  • A lost pick follows the clock again.
  • An aborted request no longer flags the forecast as out of date.

Re-verified: Go -race -run Duct and the full suite, ducting unit 108/108, test-all.sh, lint, and the ducting E2E 36/36.

Maintainer review fixes (425e6797, 8268f950, 8b03f9f4, 2285471f); details in the reply comment. Re-verified: gofmt, vet, Go race run and full suite; test-all.sh (ducting unit 69/69), lint 0 errors, CSS variable lint; ducting E2E 28/28 (incl. a Planner site placed with the overlay on, which fails on the previous code); Planner E2E 25/25; stress g 20/20 and a full gate a–g (seed 959), all passing; start_hour/end_hour checked against a self-hosted Open-Meteo; ETag/304 and Cache-Control checked on a running server. The ducting E2E now also runs in GitHub Actions (shard 1).

Review fixes (2fc5cb9d, eb228633, f2706b03): a security review and a code review of c98b04cd, accepted findings fixed; the details are in the PR comment. Re-verified afterwards: gofmt, vet, Go race run and full suite; test-all.sh (ducting unit 61/61), lint 0 errors, CSS variable lint; ducting E2E 25/25; stress g 20/20 and a full gate a–g (seed 949), all passing.

One finding along the way: the field's transparency check needs a calm cell with calm neighbours, which the fake's per-cell hash never produced once coverage included the margin. The fake's mixed scenario now has calm 3° patches, as real weather does. The full deploy.yml E2E run was not repeated for these commits (they change only ducting files and the ducting block of style.css); GitHub Actions runs it on this push.

Race shard flake. The run on 762e8c16 failed server race shard 3 in TestNodeAnalyticsWindowIgnoresLocalZone, a test already on master. The fix (set the zone in a child process instead of assigning time.Local) merged on its own as #2438, so the rebase dropped this branch's copy of it.

GitHub Actions at c98b04cd (an earlier head): all 13 checks green (4 skipped, as usual for a PR). Earlier heads: at 8813167e (with full coverage): all 13 checks green, as at e7e21451 (field redesign) and e11c78cb before it. The 4 skipped are push-only jobs (the ingestor race detector has no ingestor changes to run on, plus staging deploy, badges and release artifacts).

Rebase onto master (7536aba4). The branch had been based on #2434's pre-merge commits, which conflicted with #2434's squash merge. It now sits on master, and its diff no longer contains any #2434 file changes. I also checked that this PR and the two open map and observer PRs, #2446 and #2445, don't affect each other:

Check Result
test-all.sh with no node_modules ✅ all standalone frontend suites passed
Lint ✅ 0 errors
Go: internal/dbschema with -race, cmd/ingestor, cmd/server ✅ all ok
test-map-providers-e2e.js ✅ 28/28
test-map-providers-harness-e2e.js ✅ 16/16
test-map-ducting-e2e.js, against its own fake Open-Meteo ✅ 28/28
Race stress, seeds 20261118 and 5150 ✅ scenarios a–h all pass, including ducting g and #2446's cross-tab h

Not replicated locally:

Commits

  • 845ecbc0 feat(ducting): refractivity and tropospheric duct analysis
  • fb8e8d92 feat(ducting): config section, Open-Meteo call budget and grid cells
  • 6a484dce feat(map): tropospheric ducting overlay
  • c8820475 feat(ducting): Open-Meteo fetcher, background refresh and GET /api/ducting
  • a7aab4c7 docs(ducting): operator and user guide for the ducting overlay
  • c0e6fba9 fix(map): ducting overlay placement, normal-cell outlines, mobile layout
  • 21f1b988 fix(map): an expanded layer picker stacks above the other map corners
  • c4e3237f test(ducting): fake Open-Meteo, overlay E2E, stress scenario g, gallery
  • 33828c0b fix(map): ducting overlay never redraws a removed canvas
  • 77c9673b fix(map): ducting overlay retries every minute until it has data
  • 8b46ae04 test(ducting): stress scenario g judges the newest request's answer
  • c6b5af11 test(gallery): ducting shots centre on coloured cells, popup on the nearest
  • 15dce05a feat(ducting): forecast the area around the nodes, not just their cells
  • 1376fe20 feat(map): ducting overlay as a smooth graded field, like forecast maps
  • 679556f5 test(gallery): ducting shots framed like a regional forecast map
  • 2276ec73 feat(ducting): forecast the nodes' whole bounding box, filled
  • 827b9f74 feat(map): ducting overlay marks the edge of the forecast area
  • e05f1ff2 test(gallery): ducting shots fill the view with the forecast area
  • dae0c83f feat(map): ducting field in colour bands with bicubic interpolation
  • 997dcf24 feat(ducting): mean refractivity gradient of the lowest 1.5 km; no call caps for self-hosted Open-Meteo
  • fae233ef feat(map): ducting field coloured by the mean refractivity gradient
  • 9bb437fe test(gallery): ducting shots pick the hour and area by the mean gradient
  • fcf17155 fix(ducting): bound upstream responses, no redirects, stricter baseUrl
  • 391f71bc fix(ducting): grid ignores stale and outlying nodes; field covers high terrain
  • 6c045494 fix(map): ducting overlay redraws on re-add and flags an out-of-date forecast
  • 9c45f08e fix(ducting): pinned forecast window, partial batch failures, robust outliers, ETag
  • 83e6327b fix(map): ducting overlay no longer swallows map clicks; honest LoRa wording
  • 1108e4bc ci(e2e): run the ducting overlay E2E in shard 1
  • 12f87ec4 docs(ducting): say what the colours and the LoRa outline can and cannot show
  • 74d65420 fix(map): judge LoRa against the site's own frequency; no false duct thickness
  • fcf2bc85 fix(ducting): no pacing for a self-hosted Open-Meteo; precise outlier docs
  • 201204d0 docs(ducting): describe the per-frequency LoRa verdict; drop stale pacing notes
  • f162c4f8 test(ducting): follow the opt-in tile groups
  • c6d35eed docs(ducting): the level-spacing note is shown for ducts only
  • 7536aba4 docs(ducting): note that server replicas each fetch the forecast
  • f3abb8b5 docs(ducting): self-hosting Open-Meteo is recommended, not required
  • e10f03e1 feat(ducting): movable, collapsible panel and a scrollable forecast timeline
  • ca97bfbf fix(ducting): late scroll events of a superseded smooth scroll picked a time
  • 1af37db1 fix(ducting): trim the farthest outliers up to the cap; weak ETag
  • 97392f99 fix(ducting): status line survives collapse, late-layout timeline, hour tick
  • b87dbdff fix(ducting): keep failed batches' cells from the last forecast; no levels within 30 m of 2 m
  • 5ab3d04b perf(ducting): no forced layout per map layer; follow the clock after a lost pick
  • 55ddb2ca fix(ducting): early retry after a partial fetch only when the call budget affords it
  • 3dd63059 fix(ducting): carried count in /api/ducting, documented profile rules, LOS default pinned

🤖 Generated with Claude Code

@zfouts
zfouts force-pushed the feat/tropo-ducting branch from f3ee4fb to c98b04c Compare November 19, 2026 19:38

@efiten efiten left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough work and for the honest limitations section.

One reservation up front: we are not yet convinced the overlay adds enough to CoreScope to justify about 8,000 lines (about 2,850 of them product code) plus an external API with quota logic. The points below are what would be needed for it to become mergeable. Addressing them does not by itself mean it will be merged. Section 3 explains the reservation.

Scope of this review: the diff between #2434's head (0506fc1d) and this branch (c98b04cd), read only. Nothing was run. Points derived from source but not reproduced are marked as such.

1. Needed before merge

  1. Map clicks are swallowed while the overlay is on. public/map-ducting.js:920-925 adds an interactive rectangle with bindPopup for every cell, across the whole forecast area. Leaflet 1.9.4 stops the event when it opens a popup, so inside that area:

    • map.on('click', onMapClick) at public/planner.js:974 never fires: sites, chain points and relay ends cannot be placed;
    • Live's clickable path polylines, on the lower canvas, lose click and hover.

    Derived from the Leaflet source, not reproduced in a browser. The Planner E2E check (tests/e2e/test-map-ducting-e2e.js:687) only verifies that the entry exists. Suggestion: one map click handler that looks the cell up from the lattice and does not stop propagation, plus an E2E that places a Planner site with the overlay on.

  2. Hour rollover during a paced fetch. forecast_hours (cmd/server/ducting_source.go:239) counts from the hour at request time. At the default size a fetch takes about 4.5 minutes, and the Gulf run took 15. If the hour changes between batches, cmd/server/ducting_service.go:163-170 drops every later column, and those rows stay blank for a full refresh period. Pinning start_hour/end_hour once per refresh, or intersecting the time axes, would fix it. Not tested against the real API.

  3. "Can carry 868 MHz / 915 MHz: yes/no". With levels 200 to 250 m apart, any trapping layer found between two levels is at least about 220 m thick, and passes the 868 MHz test from ΔM ≈ 0.4. That is below model noise. Real thin ducts, which are the ones that do carry 868 MHz, are mostly invisible at this resolution (the docs say so). A yes/no answer and a three-digit f_min suggest a precision the data does not have.

    • The two thresholds also disagree: the dashed outline uses LORA_MAX_MHZ = 1000 (public/map-ducting.js:76), the popup uses 868 and 915 (:177-178). A cell with f_min 950 MHz gets an outline saying it can carry LoRa and a popup saying "no" twice.
    • Suggestion: wording like "model shows a trapping layer (at least about 200 m thick)", and one threshold.
    • Question: ducting_calc.go:193 applies one constant to surface and elevated ducts. If I recall Turton, Bennetts and Farmer (1988) correctly, elevated ducts use a larger constant (about 1.5x). Is the single constant deliberate?
  4. Colour band thresholds. STOP_N = [-44 … -90] (public/map-ducting.js:85) has no source in the code, docs or PR. Using the PR's own formulas on a standard lapse rate with constant RH, 25 °C / 80% gives about −54 N/km and 30 °C / 80% about −61 N/km: warm humid air without any inversion lands in "Enhanced" or "Strong". That matches the 56.4% of cell-hours coloured in the Gulf run. Could you cite where the thresholds come from, or re-base them so normal humid air stays clear, and soften the "Strong" wording in the user guide?

  5. Bounding box without a recency or outlier guard. cmd/server/ducting_service.go:310 takes every node with a position, with no last_seen cut. A single node with a wrong fix widens the box and doubles the step (0.5 to 8°). Please filter on recency, trim outliers, or require area. Logging the step actually used (:128) would make this visible to the operator.

  6. Framing. The PR body says "impossible" links "are usually tropospheric ducting". In an analyzer such links also come from misresolved hops (hash prefix collisions), high sites, and line of sight over water, and the overlay cannot tell these apart. Please drop "usually" (also in the FAQ) unless there is data behind it.

  7. The browser tests do not run in CI. tests/e2e/test-map-ducting-e2e.js:5-6 says "Local only". The E2E, the fake Open-Meteo and stress scenario g are the only tests that could catch point 1 or a break in the Leaflet private-API subclasses (public/map-ducting.js:574-602). Please wire at least the E2E into deploy.yml.

2. Should fix

  • Call budget and restarts. The ledger is in memory (ducting_source.go:111) and the first fetch starts immediately (ducting_service.go:261), so every restart spends about 1,890 calls on top of the steady 7,560 a day. Open-Meteo's limit is per IP, so two instances on one host (live plus staging) exceed it. A startup delay with jitter, and a note on the per-IP limit in docs/deployment.md, would help.
  • One failed batch discards the whole fetch (ducting_source.go:213-216), and the retry pays again for the batches that succeeded.
  • /api/ducting has no ETag. The body is pre-encoded, so an ETag on generatedAt is cheap; the PR's own numbers put the payload at up to 863 KB uncompressed. The client also rebuilds all rectangles when generatedAt has not changed (map-ducting.js:882-890).
  • An expired forecast is shown without a marker. _fail returns early when data exists (map-ducting.js:875-876), so after a long outage an open tab keeps showing a dead forecast.
  • AGENTS.md: the forecast hour and overlay state are not in the URL hash (deep linking); the --mc-duct-* variables are not in the customizer's THEME_CSS_MAP (fine as a tracked follow-up).
  • Nits: the comment at style.css:5690-5695 still lists −79 to −600 N/km; CHANGELOG says "smooth colour field", it is banded now; tests/unit/test-map-ducting.js:761 asserts wall-clock time (ms < 400) in the unit gate, a flake risk on a loaded runner.

3. Why the reservation

  • No history. The slider runs from now to +48 h and nothing is stored, so an operator cannot check whether last night's odd reception coincided with a duct.
  • No link to observed packets. That is listed as out of scope. Without it the overlay is a regional tropo forecast, comparable to what F5LEN and Hepburn already publish, which a FAQ link would also cover.
  • What would add value in an analyzer: keep the analysed snapshots for some days, and mark observed long links (zero-hop or direct receptions beyond the radio horizon for the node heights) with whether a duct was present along the path at that time.

Would you see that as the direction for this feature, or is it outside what you want to build? That answer weighs more for us than the fixes above. Either way, this can only merge after #2434.

@zfouts

zfouts commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (commits 2fc5cb9d, eb228633, f2706b03). A security review and a code review were run on c98b04cd; their accepted findings:

Security (2fc5cb9d, eb228633)

  1. The upstream's time axis is bounded before anything is allocated from it. A location is dropped if its axis is longer than forecastHours + 1, not hourly and ascending, or outside a 24 h window. A hostile upstream could otherwise exhaust memory from inside the 8 MB body cap.
  2. The fetcher no longer follows redirects. This rules out blind SSRF from a bad upstream and an https→http downgrade.
  3. The public-host check lower-cases the hostname and trims a trailing dot. The docs now say a proxy in front of the public API must keep the public hostname.
  4. A baseUrl with a query string or fragment is rejected.
  5. The docs recommend area for public instances, so advertised positions can't steer the grid.
  6. /api/ducting sends Cache-Control: public, max-age=300 on ok responses and no-store otherwise.

Code review (eb228633, f2706b03)

  1. Only nodes heard in the last 14 days count. With 20 or more nodes, outliers outside the 2nd–98th percentile are trimmed, so one distant or misplaced node no longer coarsens the grid. Each refresh logs its box, trimmed count, step and cell count.
  2. High terrain (Denver, Johannesburg, Mexico City) gets a field value. Where the model's levels stop below 1.5 km above ground, the mean gradient uses the available depth down to 1 km.
  3. Re-adding the overlay redraws immediately from the data already loaded. Before, it could stay blank for up to 30 minutes during a server outage.
  4. A forecast counts as expired one hour after its last time. forecastHours is raised to at least the refresh interval.
  5. The legend says "Forecast out of date" while older data is shown during an outage.
  6. Cell centres are wrapped into [−180, 180). Steps that don't divide 180 produced −180.25, which the API rejects.
  7. An empty grid on a fresh install is served as pending and retried after 5 minutes.
  8. Docs: the 0.5° claim is made precise, and n = 0 is documented as no data. The CSS comment is fixed.

Not changed

  • Persisting the call budget across restarts: it would mean the server writing to disk, and the per-process caps already apply.
  • A separate "no data" marker for n: a rounded mean gradient of exactly 0 isn't physically realistic, so it's documented instead.
  • Customizer entries for the new colour variables: a follow-up, like the other map colours.

Verified

  • gofmt, vet, the Go race run and the full server suite.
  • test-all.sh (ducting unit 61/61), lint with 0 errors, the CSS variable lint.
  • Ducting E2E 25/25.
  • Stress: scenario g 20/20, and a full gate a–g (seed 949), all passing.

@zfouts

zfouts commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. Here is where each point stands; commits are listed under each one, and everything below is on the branch now.

Direction (section 3)

Yes, that's the direction. The overlay in this PR is meant as the foundation for two follow-ups:

  • History: keep the analysed snapshots for several days, so an operator can check whether last night's odd reception coincided with a duct. Storage is planned on top of the PostgreSQL work (feat(db): PostgreSQL as an alternative database backend #2396).
  • Linking to observed packets: mark observed long links (zero-hop or direct receptions beyond the radio horizon for the node heights) with whether a duct lay along the path at that time.

If you'd rather see either of those in this PR before it's considered, say so; otherwise I'd keep them as follow-ups so this stays reviewable.

1. Needed before merge

  1. Map clicks. Fixed in 8268f950. The overlay no longer adds any interactive layers. One map click handler looks the cell up from the lattice and opens a popup without stopping propagation, and only if nothing else handled the click. The LoRa outlines and the edge line are non-interactive, on a pointer-events: none pane.
    • New E2E checks: with the overlay on, a Planner click inside the forecast area places a site, a map click on Live reaches Live's own handlers, and a cell popup opens with the right text.
    • The Planner check fails on the previous code (no site placed, ducting popup opened instead).
  2. Hour rollover. Fixed in 425e6797. The window is computed once per refresh and sent as start_hour/end_hour in every batch (checked against Open-Meteo's query handling and a self-hosted instance). The response axis must match it exactly.
    • A test advances the clock across an hour between batches and keeps every column.
  3. LoRa yes/no. Changed in 8268f950 and 2285471f.
    • One threshold everywhere: the outline and popup use f_min ≤ 868 MHz.
    • The popup now reads "Trapping layer in the model (≥ ~200 m thick)", "Lowest trapped frequency: ≈ 700 MHz (model estimate)", and "LoRa 868/915 MHz: possibly trapped (model estimate)" / "not trapped by this layer".
    • The user guide explains that the visible ducts are thick ones and that the thin ducts which most often carry 868 MHz are mostly invisible at this resolution.
    • Elevated-duct constant: kept one constant, with a code comment and sources. ITU-R P.834-4 §7.2 and Fig. 4 give the elevated-duct cut-off as depending on the profile beneath the duct: higher than the surface-duct value when the gradient is only just past trapping, lower when it is intense. So there is no fixed ratio. NTIA report 81-69 (eq. 7) uses one thickness relation for both. I couldn't get a copy of Turton, Bennetts and Farmer (1988) to check the ~1.5× figure; if you have it, I'm happy to revisit.
  4. Band thresholds. The thresholds (−44 … −90 N/km on the mean gradient over the lowest 1.5 km) were tuned empirically on archived forecast data across several regions; the user guide now says so.
    • You're right that warm, humid air without an inversion lands above the first band. The labels are softened (Normal / Above normal / High / Very high), and the guide says colour means more bending than usual, not a confirmed duct.
  5. Recency and outlier guard. Done.
    • Only nodes heard in the last 14 days count (eb228633).
    • With 5 or more nodes, nodes beyond max(500 km, 4 × the median distance) from the median position are left out, at most 10% of the nodes (or one, in a small mesh). This survives several nodes at the same wrong position, and a real second area is kept (425e6797).
    • Every refresh logs the box, the trimmed count, the step and the cell count.
  6. Framing. "Usually" is gone from the PR body and the FAQ (2285471f). The FAQ now lists misresolved hops (hash prefix collisions), high sites and line of sight over water as other causes, and says the overlay can't tell them apart.
  7. CI. The ducting E2E now runs in E2E shard 1 (8b03f9f4): the fake Open-Meteo on 13597, then a ducting + planner server on 13596.

2. Should fix

  • Restarts: the first fetch after start waits a random 60–300 s when using the public API (a self-hosted instance and the CI fake start at once). docs/deployment.md notes that Open-Meteo's free limits are per IP. (425e6797)
  • One failed batch: the fetch keeps the successful batches; the failed batch's cells are absent until the next refresh. More than half failing still fails the refresh and keeps the last good forecast. (425e6797)
  • ETag and caching:
    • ok responses carry ETag: "<generatedAt>-<model>" and honour If-None-Match with a 304, plus Cache-Control: public, max-age=300. (425e6797, eb228633)
    • The client doesn't rebuild when generatedAt is unchanged, so an open popup stays open. (8268f950)
  • Expired forecast: the legend says "Forecast out of date — showing the last one received" on an error, a failed request, or once the last forecast hour has ended. It doesn't show it on pending, which a restarting server returns while the client's data is still valid. (f2706b03, 8268f950)
  • Nits:
    • The style.css comment and the CHANGELOG ("colour bands") are fixed.
    • The wall-clock assertion is gone from the unit gate.
    • forecastHours is now raised to at least the refresh interval + 2 h.
    • High terrain: the mean gradient uses the available depth down to 1 km. Denver-like sites get a value; sites where 700 hPa is less than 1 km above ground (e.g. Mexico City) don't, and the docs say so.
  • Follow-ups, not in this PR:
    • The forecast hour and overlay state in the URL hash (deep linking).
    • The --mc-duct-* variables in the customizer's THEME_CSS_MAP.

Not changed

  • Persisting the call ledger across restarts. It would mean the server writing state to disk. The per-process caps plus the new start delay cover the restart case.

@zfouts

zfouts commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up from a further review pass (commits 920592a5, b0c32408). It corrects two details in my earlier comments.

  1. LoRa verdict: judged against this site's own LoRa frequency (the line-of-sight setting, los.frequencyMhz) when the server sets one; otherwise 868 and 915 MHz each, one popup line per frequency. My earlier reply said one 868 MHz threshold, but a duct with f_min ≈ 900 MHz was then "not trapped" for a 915 MHz mesh.
    • The dashed outline marks a duct that may carry at least one judged frequency.
    • The verdicts compare the same rounded f_min the popup shows, so the number and the answer can't disagree at an edge.
  2. Duct thickness: the popup no longer says "≥ ~200 m thick". A surface duct can top out at the first model level, under 100 m above ground. It now says the model's ~200 m level spacing can't resolve thinner layers.
  3. Outlier filter: the 2nd–98th percentile trim in my first comment was replaced in 425e6797. Nodes beyond max(500 km, 4 × the median distance) from the median position are left out, capped at 10% of the nodes (or one in a mesh of fewer than 20). The docs now state that cap.
  4. Pacing: a self-hosted Open-Meteo, and the CI fake, are no longer paced at 400 calls/min, which is the public API's limit. A fixture refresh drops from 95 s to 0.2 s, so the CI shard barely waits.
  5. CI: a skipped ducting E2E check now counts as a failure when CI=true, so a misconfigured server can't silently skip the Planner checks.

Re-verified on the pushed code:

  • gofmt, vet, the Go race run and the full server suite.
  • test-all.sh (ducting unit 71/71) and lint, with 0 errors (no new warnings).
  • Ducting E2E 28/28 and Planner E2E 25/25.
  • Stress: scenario g 20/20, and a full gate a–g (seed 969).

@zfouts
zfouts force-pushed the feat/tropo-ducting branch 2 times, most recently from 762e8c1 to 8cf5a3d Compare November 20, 2026 00:03
@zfouts

zfouts commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (rebased onto #2434 f3402c5d; commits: 8cf5a3d 5e233c2 9b33213).

  1. Docs match the per-frequency LoRa verdict. The user guide, FAQ and changelog describe the site-frequency or 868 + 915 MHz verdicts and drop the "≥ ~200 m" claim. They also note that within a few MHz of the judged frequency the rounding decides. docs/deployment.md says the verdict follows los.frequencyMhz (default 910.525), so an EU site with line of sight on should set its frequency.
  2. Stale pacing comments in deploy.yml and ducting_source.go are fixed: a self-hosted fetch is not paced.
  3. feat(map): more tile providers (topo, satellite, gray, vector), hillshade overlay and custom tile servers #2434 made its new tile groups opt-in after the maintainer's review. The gallery switches on the groups a shot uses (OSM Gray under the overlay), and one stacking test turns EOX on.
  4. CI race shard 3 failure on 762e8c16. It was TestNodeAnalyticsWindowIgnoresLocalZone, a master test that assigned time.Local while a leftover timer could fire. It now sets the zone in a child process (TZ=Etc/GMT-2). It still fails on the bug it guards against, and passes under -race. The same commit is on fix/node-analytics-localzone-race for master.
  5. PR description:
    • The stale pacing, hit-rectangle and "can carry LoRa" wording is corrected.
    • The test count and the commit list are current.
    • The screenshots are retaken, so the popup shows the per-frequency verdicts.

@zfouts
zfouts force-pushed the feat/tropo-ducting branch from 8cf5a3d to 73894a0 Compare November 20, 2026 00:38
@zfouts

zfouts commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto #2434 e92b8631 (its Auto layer now ignores the saved pick). Two small changes from a further review:

  • 29658379: the timezone test's child run checks that the test actually ran (--- PASS), so a rename can't make it pass vacuously.
  • 73894a05: in map.md, the level-spacing note is shown for ducts only.

On history snapshots (from your review). Showing the past days is the goal: the past 2 to 7 days next to the forecast, and long links the mesh actually heard marked against them. It isn't in this PR because of API calls:

The PR description's Out of scope section now says the same.

@zfouts

zfouts commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Docs note added (commit d6825f80)

  1. docs/deployment.md: several server replicas of one installation each fetch the forecast on their own, so N replicas use N times the Open-Meteo calls and can briefly answer with different forecasts. With more than one replica, point baseUrl at a self-hosted Open-Meteo.

Found on a test deployment with five server replicas: against the public API four of the five got HTTP 429 within minutes; against a self-hosted Open-Meteo all five refreshed (288 cells each). No code change. A single shared fetcher would be a separate follow-up.

efiten pushed a commit that referenced this pull request Nov 21, 2026
…al (#2438)

## Summary

`TestNodeAnalyticsWindowIgnoresLocalZone` set the zone by assigning the
global `time.Local`. Every `time.Now()` reads that variable, so if a
timer left over from an earlier test fires during this test, the race
detector reports a data race. It counts as a failure of this test,
whichever test left the timer.

It showed up as an intermittent failure of the server race detector
(shard 3/4) on a PR run (#2436). Three local runs of the same shard
passed. The code under test is fine; only the test was racy.

## Change

The test now re-runs itself in a child process with `TZ=Etc/GMT-2`
(UTC+2) and writes nothing global:
- **Embedded zone data:** `time/tzdata` is embedded in the test binary,
so the zone resolves without the host's zoneinfo.
- **Zone check:** the child first checks that its local offset really is
+02:00.
- **Test name:** the child's `-test.run` pattern is built from
`t.Name()`.
- **Vacuous pass guarded:** the parent requires `--- PASS: <name>` in
the child's output, so a rename can't make it pass without running.
- **Windows:** the test is skipped there before the re-exec. Go on
Windows takes the local zone from the OS and ignores `TZ`, so the child
cannot be put in UTC+2.
- **Bounded child:** the child runs under a 60 s context, so a hung
child fails with its output.

This follows the existing re-exec pattern in
`distance_background_fill_test.go`. `TestMain` is just
`os.Exit(m.Run())`, so the child runs only this test. It works under the
sharded `-test.run` in the race job, and in coverage builds.

## Testing

- `go test -race -run TestNodeAnalyticsWindowIgnoresLocalZone`: pass.
gofmt and vet are clean.
- **Still guards the original bug:** with `time.Now().UTC()` changed
back to `time.Now()` in `GetNodeAnalytics`, it fails as before. The 7d
window holds 166 of 168 packets, and `From` is `...+02:00`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
zfouts and others added 15 commits November 21, 2026 19:49
Shared types for the tropospheric ducting overlay (ducting_types.go) and
the physics (ducting_calc.go), pure functions with no I/O:

- vapour pressure from RH, refractivity N = 77.6/T (P + 4810 e/T)
  (ITU-R P.453), modified refractivity M = N + 0.157 h
- DuctProfile builds the ascending profile from a model column: the 2 m
  surface point plus pressure levels above ground and within 3 km,
  skipping missing or implausible values
- AnalyzeDucting finds trapping layers (M decreasing with height), the
  duct bottom (surface-based or elevated, interpolated where M returns
  to the trapping-layer top value), thickness d and strength dM, and the
  lowest trapped frequency fmin = 120000 / (d sqrt(dM)) MHz
  (lambda_max ~ 0.0025 d sqrt(dM)); classes normal / super-refractive /
  elevated duct / surface-based duct

Known-answer tests use values computed independently. The sample
/api/ducting payload in tests/fixtures is the frontend's contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New `ducting` config section, off by default:
- model allowlist: gfs (NOAA GFS, worldwide, default), icon (DWD ICON,
  worldwide), rrfs-conus (US only, explicit opt-in; a warning is logged
  when the area is unset or extends outside the contiguous US)
- gridStepDeg, maxPoints, refreshMinutes, forecastHours with range
  checks and defaults; baseUrl for a self-hosted Open-Meteo (absolute
  http(s), no credentials; warnings never echo the URL)
- call budget: Open-Meteo counts >10 variables proportionally (GFS: 42
  variables = 4.2 calls per point); points are capped so a day stays
  under 8,000 calls (free tier: 10,000)
- grid: without an area, only the cells that contain nodes, so a mesh
  anywhere in the world works without querying empty ocean; the step
  doubles (up to 8 degrees) past the point cap; longitude wraps at 180
- /api/config/client gets `ducting` (model, label, step, attribution)
  only when enabled; baseUrl is never sent to browsers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A "Tropospheric ducting" entry in the map's Overlays group (Map, Live,
Repeater Planner), present only when the server enables `ducting`.
map-ducting.js fetches /api/ducting (every 30 min while shown) and draws
one cell per grid point, coloured by the lowest frequency the duct can
trap: can carry 868/915 MHz LoRa (<= 1000 MHz), 1-3 GHz, above 3 GHz,
or super-refraction; elevated ducts are drawn lighter than surface-based
ones. A legend (model, attribution, update time, "indicator only" note)
and a forecast-time slider are added with the layer; clicking a cell
shows duct type, base/top, strength, lowest trapped frequency and
whether 868 and 915 MHz can be carried.

Colours come from --mc-duct-* CSS variables (light and dark) and follow
theme changes. Removing the layer mid-fetch ignores the late response
and releases the timer, controls and listeners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cting

When ducting.enabled, the server keeps an in-memory ducting forecast and
serves it read-only at GET /api/ducting (404 when disabled; nothing is
written to any database):

- ducting_source.go: Open-Meteo client. Batches of 50 locations, paced
  to <= 400 calls/min, hard caps of 4,500 calls per rolling hour and
  9,500 per day checked before anything is sent; 60 s timeout, 8 MiB
  body limit, array or single-object responses, null -> NaN, locations
  outside a regional model's coverage dropped. Errors carry the status
  and the API's reason but never the URL (the *url.Error wrapper is
  dropped), since baseUrl may be private.
- ducting_service.go: grid from the visible nodes (same rule as
  /api/nodes, so hidden and blacklisted nodes never shape it), physics
  on every cell and hour, snapshot pre-encoded once per refresh. One
  refresh at a time; the first runs at startup without blocking it.
  The last good forecast survives failures; retries back off 5, 10,
  20 ... min up to refreshMinutes, and wait >= 60 min after a 429 or a
  spent budget. Status pending -> ok, or error with a short message;
  "forecast expired" once the last forecast hour has passed.
- DuctingCell.C is []int: encoding/json writes []uint8 as base64.
- openapi.go documents the route.

Tests run against httptest fakes only: query string and batching,
pacing, budget caps, 429/4xx/5xx/oversize/cancel, snapshot shape equal
to tests/fixtures/ducting-sample.json, an inversion column giving the
expected surface duct, failure and backoff transitions, hidden nodes,
and handler reads racing a refresh (-race clean).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- deployment.md: "Tropospheric ducting overlay" under Map Tile
  Providers: enabling, every key with default and range, the models
  (GFS and ICON worldwide; RRFS US-only and opt-in), the Open-Meteo
  call budget arithmetic, refresh and backoff behaviour, self-hosting
  Open-Meteo via baseUrl for commercial use, what is public, the
  physics, limitations and attribution.
- user guide: what the colours, slider and popup mean (map.md), a short
  config example (configuration.md), and FAQ 12 "Why did a node far
  away hear my packet?".
- CHANGELOG entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found in browser validation against a server with real Open-Meteo data:

- The legend and time control sat bottom-right, under the Map page's
  Map Controls panel. They now sit bottom-left; on Live the corner is
  offset to clear the feed panel and the VCR bar.
- On narrow screens the attribution bar wraps across the full width and
  covered the time control. While the overlay is on a map, the
  bottom-left corner is lifted by the measured attribution height
  (re-measured on resize and layer changes; released on remove). The
  attribution is never truncated.
- Cells with normal propagation were undrawn, indistinguishable from
  "no data". Every cell with data now has a faint outline
  (--mc-duct-grid), with a legend row for it.
- The legend showed the model name twice; only the attribution is shown.
- The legend is collapsible and starts collapsed at <= 600 px.

Checked on Map, Live and Repeater Planner at 1280x800, 375x812 and
320x700, light and dark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Leaflet gives every map corner the same z-index, so a later corner
covers an earlier one. With the ducting legend bottom-left, the long
expanded picker list (top-left) ran under the legend and its lower
entries could not be clicked on an 800 px tall screen. While a picker
is expanded, its corner now stacks above the others (:has()).

Found by the new ducting E2E (it fails without this change, at the
points the legend covered).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Local suites (not added to GitHub Actions):

- tests/e2e/lib/fake-open-meteo.js: a dependency-free fake Open-Meteo
  that validates the query (model, every variable, forecast_hours,
  unixtime) and answers deterministic, physically consistent columns.
  Scenarios: mixed (normal, super-refraction, surface duct that traps
  868 MHz, elevated duct, varying by hour), pending, error500,
  ratelimit, nulls. Point ducting.baseUrl at it.
- tests/e2e/test-map-ducting-e2e.js (22 checks): client config without
  baseUrl, /api/ducting classes equal the scenario's, batched requests,
  overlay entry on Map/Live/Planner, cell fills per hour, slider,
  popups (868/915 yes/no), legend and time box unobstructed, an
  expanded picker on top, theme restyle, pending/error states, off ->
  nothing left behind, no page errors.
- Stress scenario g (runs when the server has ducting): seeded mix of
  overlay toggles (API and picker), toggles during a delayed or failing
  /api/ducting, navigation between Map/Live/Planner mid-fetch, theme
  flips and slider moves during a refresh; checks one legend/time box
  per map, none when off, no listener growth, nothing drawn into a
  removed map. The ducting layer is not a tile-pane layer, so it is
  left out of the existing overlay-pane count.
- gallery.js: ducting entries (legend light/dark, zoomed cells, popup,
  Live), skipped with a reason when the server has no ducting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Leaflet 1.9.4's canvas _updatePaths (run on every map move) redraws at
once but leaves an already queued animation-frame redraw in place with
its id dropped. Switching the overlay off before that frame removed the
renderer without being able to cancel it, and the orphaned callback
threw "Cannot read properties of undefined (reading 'clearRect')".
Seen once in the race stress gate (seed 303, scenario g, on #/live).

- public/map-ducting.js: the overlay's renderer is an L.Canvas subclass
  whose _updatePaths cancels the queued frame before redrawing.
- tests/e2e/test-map-ducting-e2e.js: queue a redraw, run a move redraw,
  switch off in the same task; no page error. Fails on the previous
  code with the clearRect error, passes now (22 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The overlay only asked /api/ducting again on its 30-minute refresh. A
user who switched it on while the server was still preparing the first
forecast (about a minute on real data), or whose request failed, saw
"being prepared" / "unavailable" for up to half an hour.

- public/map-ducting.js: while there is no data, the refresh interval is
  one minute; the first good answer sets it back to 30 minutes. One
  interval as before (_schedule re-arms it when the period changes), so
  teardown is unchanged. Last good data is still kept on a failed refresh.
- tests/unit/test-map-ducting.js: pending, then a failure, then data:
  one timer throughout, 1 min -> 1 min -> 30 min, none after remove.
  Fails on the previous code.
- docs/deployment.md: say how often the browser asks, and that these
  requests read the server's copy, never Open-Meteo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The random phase decided whether cells must be drawn from whichever
/api/ducting route handler finished last. Handlers sleep 0-2.5 s, so an
earlier request (already aborted by a removed layer) could finish after
the attached layer's request got a chaos 500, and the check then wanted
cells from a layer that had correctly shown "unavailable" (seed 303,
g#43, "cells drawn=0 want 15").

- tests/e2e/test-map-race-stress-e2e.js: record each request's outcome
  by number; the attached layer's answer is the one to the newest
  request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…earest

With nodes worldwide the median of all ducting cells fell in an area with
almost no ducting, and the popup entry could open a cell on another
continent (Leaflet then panned there, under the legend).

- scripts/map-perf/gallery.js: the 'ducting' view centres on the densest
  cluster of coloured cells (class >= 2) at the current hour, falling
  back to the median; the surface-duct view prefers a duct that can carry
  LoRa (fmin <= 1000 MHz) and uses zoom 8; the popup opens on the
  surface-duct cell nearest the view centre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The grid was only the cells containing a node, so the overlay showed
isolated squares. Established ducting maps show a regional field; the
server now covers each node cell plus a margin.

- ducting_types.go, ducting_config.go: `ducting.marginDeg` (default 2,
  allowed 0..10, 0 = node cells only, ignored with `area`); shown in the
  startup log line.
- ducting_grid.go: ductingGrid dilates the node cells by ceil(margin /
  step) rings on the same lattice; latitude rings beyond 85 dropped,
  longitudes wrapped and de-duplicated across the antimeridian. The
  margin is recounted at every step doubling; past 8 degrees the trim
  keeps cells with the most nodes, then those nearest a node. The dilated
  set is bounded (50 x maxPoints) before it counts as too many.
- ducting_service.go: passes the margin.
- Tests: margin 0 equals the old grid; 25 cells for one node at margin 1;
  overlap de-duplication; antimeridian and pole edges; step doubling with
  the margin recounted; trim order; bounded growth; config defaults and
  warnings; the service covers the region by default (81 cells).
- docs/deployment.md, docs/user-guide/configuration.md: the new key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The overlay drew one categorical square per grid cell, with outlines,
which looked nothing like the established ducting forecast maps (a
continuous colour field on a graded scale over a region).

- public/map-ducting.js: the field is one canvas-backed image overlay per
  map in its own pane (z 245, no pointer events), drawn in Web Mercator
  rows and bilinearly interpolated between cell centres, fading out at
  cells without data. Colour follows dN/dh on a graded ramp: clear above
  -60 N/km, faint purple/blue for super-refraction (from -79), green,
  yellow, orange, red to pink for ducting (from -157) up to -600 and
  beyond; opacity rises with strength so ducts stand out. Cells where a
  duct can carry 868/915 MHz get a dashed outline. Invisible hit
  rectangles keep the popups. Redrawn only on data, hour or theme change
  (Gulf data, 861 cells: 656x390 px, ~9 ms). The legend is a gradient bar
  with Normal / Super-refraction / Ducting / Strong. Teardown removes the
  field too.
- public/style.css: --mc-duct-s1..s8 and --mc-duct-alpha (light and
  dark); the categorical bin variables and swatches are gone.
- tests/unit/test-map-ducting.js: ramp, opacity curve, Mercator rows,
  lattice and sampling, fading, LoRa outline, restyle without rebuilding
  rectangles, teardown (41 tests).
- tests/e2e/test-map-ducting-e2e.js: probes the field's pixels through
  Leaflet's projection against the data (duct colours, calm transparent),
  slider and theme redraws, outlines; tests/e2e/test-map-race-stress-e2e.js:
  one field per map while on, none after.
- tests/e2e/lib/fake-open-meteo.js: the mixed scenario has calm 3-degree
  patches, as real weather does, so a calm cell has calm neighbours.
- docs/user-guide/map.md, CHANGELOG.md: describe the field and scale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- scripts/map-perf/gallery.js: the ducting entries use the keyless OSM
  Gray basemap (neutral under a colour field; works without a Carto
  key), frame the whole coverage when it is regional (fit to the map
  with Map Controls collapsed, clear of the legend), set the forecast
  slider to the hour with the most ducting and record that time; the
  zoomed and popup entries centre on a duct that can carry LoRa.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… a time

On a slow page (the instrumented CI build) rapid arrow keys restarted the
timeline's smooth scroll before it had moved. Stepping back to where the
strip still was cleared the "code is scrolling" target while the earlier
smooth scroll was still in flight, so its scroll events were read as a
user scroll and picked an in-between hour (CI: the popup-follows-timeline
and Now tests timed out or landed one hour off).

While a code scroll is in flight the next one now jumps instead of
starting a second smooth scroll, the target is never dropped early, and
the idle settle finishes a scroll that stopped short instead of dropping
its target.

Regression test replays the sequence with a smooth scrollTo that has not
moved; it fails without the fix. Ducting E2E against an instrumented
frontend: 0/3 -> 4/4 runs green; plain 34/34; stress g 4/4; unit 94 in
three time zones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 22, 2026
…port of e10f03e)

Ports the panel and timeline of Kpa-clawbot#2436 (e10f03e) and its race fix
(ca97bfb, folded in) to the stored-grid overlay, in both modes:

- Grid times (history then forecast, uneven) on the timeline; every grid
  pick goes through _pickTime, at most once per animation frame while
  scrolling, with the ductT deep-link write still debounced.
- ductT from the URL restores the time and the strip position (a user
  pick); Now goes to the latest time <= now and removes ductT.
- Grid label: just "<time> · analysis, N h ago" / "· forecast" (no
  prefix: the suffix says what it is, and a prefix had no room at 320 px);
  Open-Meteo mode keeps "Forecast time: <time>". Now line in both modes.
- Collapsing hides the whole legend body, long-links table included;
  _fitLegend caps the legend body for the whole panel, docked or moved,
  and the panel is re-clamped after every legend render.
- The shared E2E helper (tests/e2e/lib/ducting-e2e.js) gets the timeline
  helpers; its settled() also waits for the overlay's own scroll to be
  over, so a test's bare scrollLeft (no input event) is never swallowed.

Tests: unit 141 (UTC, America/Chicago, Australia/Lord_Howe); grid E2E 31
plain and 6/6 against the instrumented frontend; Open-Meteo E2E 34 plain
and instrumented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Two commits since the last round, both UI-only (no server changes):

  1. e10f03e1 — movable, collapsible panel and a scrollable timeline. The time slider was hard to use (48 hourly steps in ~230 px, dates only after you landed), and the legend could not be moved or obviously collapsed.
    • The controls are now one panel: a title bar with a collapse chevron (hides the legend, keeps the timeline), a drag grip and Reset. On screens wider than 600 px it can be dragged anywhere on the map (pointer or arrow keys on the grip). It stays inside the map, steps aside from page panels that would cover its buttons, and remembers position and collapsed state in localStorage. Phones keep it docked and collapsed by default.
    • The range input is replaced by a timeline strip. It has day labels at local midnights (which push each other off), hour labels at 06/12/18 and a now line. The time under the centre marker is shown. Scroll, drag, wheel or click pick a time; ◀ ▶, Now, arrows, Page Up/Down and Home/End work too. It is a role=slider with value text, and redraws are coalesced to one per frame.
  2. ca97bfbf — fix a race the instrumented CI build exposed. On a slow page, rapid arrow keys restarted the strip's smooth scroll before it moved. The late scroll events of a superseded scroll were then read as a user pick of an in-between hour. A regression unit test replays the sequence (it fails without the fix). Against an instrumented frontend the ducting E2E went from 0/3 to 4/4 green.

Tests: unit 94 (UTC, America/Chicago, Australia/Lord_Howe, including labels across the 2026 DST changes); ducting E2E 34 plain and instrumented, plus new checks for collapse, drag and reload, strip width at 1440×900 and 390×844, and map not panning while the timeline is used; stress scenario g 4/4. The description has the updated details and new screenshots (real GFS data, Carto basemap).

@zfouts

zfouts commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master (6ab97f52) into the branch: merge commit d9300b34, no conflicts, so every hash in the description still holds. Go suites, test-all.sh, and the ducting, map and node-analytics Heard-by E2E suites pass locally; the description has the counts.

zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 23, 2026
Both branches now carry master 6ab97f5, where Kpa-clawbot#2434 landed squashed.
The tree is master + Kpa-clawbot#2396 (63ebfb7) + Kpa-clawbot#2436 (d9300b3) built fresh,
with only CHANGELOG resolved by hand; the superseded pre-squash Kpa-clawbot#2434
and pre-rebase Kpa-clawbot#2436 commits in this branch's history are replaced by
those versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 23, 2026
… into feat/ducting-grid-history

Conflicts were Kpa-clawbot#2436's panel commit e10f03e against this branch's own
port of it (73641fe), which also carries grid mode: this branch's side
is kept in map-ducting.js, style.css, the ducting tests and the docs.
CHANGELOG lists the map-provider entries once. The docs take f3abb8b's
wording (running your own Open-Meteo is recommended, not required) for
the open-meteo source. ca97bfb follows as its own commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@efiten efiten left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 9bb437f..ca97bfb.

From the earlier review, the points on map clicks, hour rollover, the LoRa verdict, the recency and outlier guard, the framing and E2E in CI are resolved in code. The band thresholds took the "soften the labels and say they are empirical" option. Call budget, failed batches and ETag are handled as asked. Deep linking is deferred, see the question at the end.

Should fix

  1. The "Forecast out of date" line is invisible when the legend is collapsed (public/map-ducting.js:1771-1775 with :1254). It is rendered inside .mc-duct-legend, which collapse hides, and so are the "being prepared" and "unavailable" states. Phones start collapsed. In Chrome at 1280 px (collapsed by click) and 390 px (default), with _stale true, the visible panel shows only the title, the forecast time and the day labels. This reopens the "expired forecast without a marker" point for the default phone view. Showing the state in the part that stays visible (header or forecast-time line), or expanding on stale, would fix it.
  2. The timeline stays on the first hour when the panel is laid out while hidden (map-ducting.js:1588-1606 and :1408). With scrollWidth 0, _tlScrollTo sets _tlTarget and the scrollLeft assignment does nothing, so the target never clears, and _onPanelResize skips its late-layout restore because it requires _tlTarget == null. In Chrome, with the map in a display:none wrapper and a forecast that started 5 hours ago, after showing it: idx 5, target 50, scrollLeft 0, so the label says 13:00 while 08:00 sits under the centre marker. It recovers on the next wheel, touch, drag or key, or on the next refresh (up to 30 min). I did not check whether any CoreScope page loads the data while the map container is hidden. Skipping the target when scrollWidth is 0, or dropping the _tlTarget == null condition when the strip is not at the target, would fix it. A fake DOM with scrollWidth 0 and a scrollLeft that does not stick would give it a unit test.

Minor

  1. cmd/server/ducting_grid.go:323-326: the outlier trim is all or nothing. Above 10% of nodes beyond the limit (or more than one below 20 nodes), nothing is trimmed and one far node stretches the box again. It is documented, and on our data 1 of 1,728 nodes is beyond the limit. Trimming the farthest nodes up to the cap would degrade more gently.
  2. cmd/server/ducting_service.go:380: one strong ETag for both the gzip and the identity body when the gzip middleware is on. A weak ETag (W/) is the accurate form.
  3. map-ducting.js:342-347: with line of sight on and los.frequencyMhz left at the default 910.525, an EU site is judged at 910.525 MHz. This is documented in deployment.md, but an operator who turned LOS on earlier gets that verdict with only the frequency in the legend as a hint.
  4. map-ducting.js:92: the shown hour and the now line only move when a refresh lands, so the current hour can lag up to 30 minutes. I did not check whether this predates the range.

What I ran (scratch worktree on d9300b3, this range merged with master)

  • go vet ., go test -run Duct . and go test ./... in cmd/server: ok, no FAIL lines.
  • node tests/unit/test-map-ducting.js: 94 passed, also under TZ America/Chicago, Australia/Lord_Howe and Europe/Brussels.
  • node scripts/check-css-vars.js: 0 undefined.
  • The ca97bfb test fails with map-ducting.js from e10f03e (1 failed, "no second smooth scroll while one is in flight") and passes at ca97bfb.
  • Outlier filter on 1,728 positions from our instance (last_seen within 14 days): median 73 km, limit 500 km, 1 node trimmed (8,841 km), 270 cells at 1 deg.
  • Items 1 and 2: Playwright repros in Chrome with real Leaflet, style.css and map-ducting.js, and a stub CSApi.
  • Not run: the ducting E2E, Planner E2E, race stress, eslint, Go -race. Not read: map-ducting.js:470-870 (field rendering) and the test file bodies.

Question: deep linking (hour and overlay state in the hash) is a MUST in AGENTS.md for shareable UI state. Do you want it in this PR, or as a follow-up issue linked from here before merge?

zfouts and others added 3 commits November 23, 2026 11:03
Review follow-ups on Kpa-clawbot#2436 (server):

- The outlier trim was all or nothing: above the cap (10% of the nodes,
  or one in a mesh of fewer than 20) nothing was trimmed, so one far node
  stretched the box again. It now drops the farthest outliers up to the
  cap and keeps the rest.
- GET /api/ducting sends a weak ETag (W/"<generatedAt>-<model>"): the gzip
  and the identity body share it. If-None-Match matches with or without
  the W/ prefix.
- Docs updated for both.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ur tick

Review follow-ups on Kpa-clawbot#2436 (overlay):

- The loading / being prepared / unavailable / out-of-date line moved out
  of the collapsible legend to under the forecast time, so a collapsed
  panel (the default on phones) still says so. One role=status element.
- A panel laid out while hidden no longer leaves the timeline on the
  first hour: no scroll target is recorded while the strip has no size,
  so the resize restore puts the shown hour under the centre marker, and
  a target the strip cannot reach is dropped by the idle timer.
- With los.frequencyMhz at its shipped default (910.525) the LoRa verdict
  judges 868 and 915 MHz, as when none is set.
- An hourly tick moves the now line, and the shown hour unless the user
  picked one, at the top of each hour instead of at the next refresh.
  No request is made.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (commits 1af37db1 server, 97392f99 overlay; master merged in as 10e5220f).

Deep linking: follow-up issue, #2459. It covers the overlay on/off state and the shown hour in the hash, written with replaceState, plus unit and E2E tests. It adds new behaviour on three pages, and none of the fixes below depend on it, so I kept it out of this PR.

  1. Status hidden when collapsed. The loading / being prepared / unavailable / out-of-date line is no longer inside .mc-duct-legend. It is one role="status" element under the forecast time, in the part that collapse never hides, and it is hidden while there is nothing to say. The legend keeps no copy. Checked in Chromium with real Leaflet and style.css: stale and collapsed at 390 px and 1280 px, the line is visible and the panel stays inside the map; on the previous file the visible panel had no status text. Unit tests cover pending, error and stale with the panel collapsed. The E2E's status checks now also run collapsed.
  2. Timeline stuck on the first hour after a hidden layout. _tlScrollTo records no target while the strip has no size (scrollWidth 0), so _onPanelResize puts the strip on the shown hour once it is laid out. The panel's existing ResizeObserver fires when a display:none wrapper is shown, so no new hook was needed. A target the strip cannot reach is also dropped by the idle timer, so one cannot outlive a scroll that moved nothing. Your repro (hidden wrapper, forecast started 5 h ago, then shown) now gives scrollLeft 50 at hour 5 with no target left; on the previous file, 0 with the target stuck at 50. That was checked on the plain and the Istanbul-instrumented build. "No second smooth scroll while one is in flight" (ca97bfbf) still passes.
  3. All-or-nothing outlier trim. Above the cap, the farthest outliers are dropped, up to 10% of the nodes (or one in a mesh of fewer than 20), and the rest stay in the box. A real second area therefore keeps its nearer nodes; area remains the way to get a tighter box. docs/deployment.md and docs/user-guide/configuration.md are updated.
  4. ETag. It is now W/"<generatedAt>-<model>". If-None-Match matches with or without W/. On a running server: 304 for both forms, with and without Accept-Encoding: gzip.
  5. LoRa at 910.525 MHz. A los.frequencyMhz left at the shipped default is treated as not chosen, so 868 and 915 MHz are judged, as when line of sight is off. A frequency the operator sets (869.525, 915, …) is judged on its own. On a real 910.525 MHz mesh the dashed outline does not change, because the compared figure is rounded to two significant figures; the popup shows the 868 and 915 lines instead of one. The docs say so.
  6. Hour lag. One timer aimed at the next top of the hour moves the now line, and the shown hour unless the user picked one. It makes no request, re-arms itself and is cleared on removal. It also flags "out of date" at the hour the forecast runs out. The lag came in with this PR (REFRESH_MS arrived in 6a484dce), not from earlier code.

Checks:

  • Ducting unit 102/102, also under TZ America/Chicago, Australia/Lord_Howe and Europe/Brussels; the new tests fail on the previous file (90 passed, 12 failed).
  • test-all.sh green, eslint 0 errors, CSS variable check 0 undefined; go vet and go test in cmd/server ok on the merge.
  • Ducting E2E against a fresh fake Open-Meteo: 36/36 on three runs. One earlier run failed "a moved, collapsed panel keeps its place and state across a reload" (cells did not appear within 25 s); that test is unchanged here, and I'll watch for it in CI.

zfouts and others added 2 commits November 23, 2026 11:27
…evels within 30 m of 2 m

Follow-ups from an internal review of Kpa-clawbot#2436 (server):

- A fetch where some batches failed replaced a complete forecast with a
  half-empty one and waited a whole refreshMinutes (6 h by default). The
  failed batches' cells now keep the previous forecast's values for the
  hours both cover, and the refresh is retried on the failure backoff
  (5, 10, 20 ... min, capped at refreshMinutes; the call budget still
  applies).
- A pressure level a few metres above the 2 m point made gradients of
  hundreds of N/km ("surface-based duct" at ~12.8 GHz). Levels less than
  30 m above it are ignored.
- A missing 2 m point gives no data instead of treating the first
  pressure level as the surface.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… a lost pick

Follow-ups from an internal review of Kpa-clawbot#2436 (overlay):

- The corner lift measured the attribution bar on every layeradd and
  layerremove, so with the overlay on each of the Map page's markers and
  each of Live's animated lines forced a layout. It now re-measures on map
  resize and through the ResizeObserver on the bar; without one, only
  layers with attribution trigger it, at most once per frame. Adding and
  removing 2,000 markers with the overlay on: about 9.7 s -> 135 ms
  (Chromium, median of 5).
- A picked hour that a new forecast no longer contains clears the pick,
  so the shown hour follows the clock again.
- A request aborted by the next refresh no longer flags the forecast as
  out of date.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Further fixes from an internal review (commits b87dbdff server, 5ab3d04b overlay):

  1. Forced layout per map layer. With the overlay on, the corner lift re-measured the attribution bar on every layeradd/layerremove. Each of the Map page's node markers and each of Live's animated lines therefore forced a layout. It now re-measures only on map resize and through the existing ResizeObserver on the bar. Without a ResizeObserver, only layers that carry attribution trigger it, at most once per frame. Adding and removing 2,000 markers with the overlay on, in Chromium (median of 5): about 9.7 s before, about 135 ms after.
  2. Partial fetch. A fetch where some batches failed used to replace a complete forecast with a half-empty one, and the next refresh came a full refreshMinutes later (6 h by default). The failed batches' cells now keep the previous forecast's values for the hours both forecasts cover. The refresh is retried on the failure backoff (5, 10, 20 … min, capped at refreshMinutes), and the call budget still applies.
  3. Level too close to the 2 m point. A pressure level a few metres above the 2 m point produced gradients of hundreds of N/km: surface 1001 hPa/12 °C/95 % under 1000 hPa at 8 m gave −385 N/km and a "surface-based duct" trapping only above about 12.8 GHz. Levels less than 30 m above the 2 m point are now ignored. TestDuctStandardAtmosphereIsNormal relied on such a level (10.9 m AGL); its expected minimum gradient was recomputed.
  4. Missing 2 m point. A cell whose 2 m point is missing is now no data, instead of treating the first pressure level as the surface.
  5. Lost pick. When a new forecast no longer contains the user's picked hour, the pick is cleared, so the shown hour follows the clock again.
  6. Aborted request. A request aborted by the next refresh no longer flags the forecast as out of date.

Checks:

  • Go: gofmt, go vet and go test -race -run Duct in cmd/server, plus the full ./... suite.
  • Ducting unit tests: 108/108.
  • test-all.sh, eslint (0 errors), and the ducting E2E against a rebuilt server: 36/36.
  • In a browser, at 390 and 1280 px on the Map page: the panel still clears a wrapping attribution bar.

docs/deployment.md now describes the carry-over and the early retry.

zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 23, 2026
Brings the Kpa-clawbot#2436 review fixes to the global-grid branch.

- Calc (b87dbdf) ported to internal/ducting, where the physics lives
  here: pressure levels less than MinLevelGapM (30 m) above the 2 m point
  are ignored, and a missing 2 m point gives no data. The ingestor's grid
  job and the server's Open-Meteo source both get it. cmd/server/
  ducting_calc.go stays deleted; its tests are in internal/ducting.
- Server: the Open-Meteo source keeps the carry-over of failed batches,
  the backoff retry, the farthest-first outlier trim and the weak ETag.
  The shared If-None-Match matcher now ignores W/ on the route's own tag
  too (tropo's separate matcher is dropped as a duplicate).
- Overlay: the status line outside the collapsible legend also serves
  grid mode (meta loading / being prepared / unavailable / out of date,
  and a failed window); the hour tick follows the clock in grid mode too
  (now line, "ago" label, the shown step unless one was picked). The
  other fixes (late-layout timeline, 910.525 default, no forced layout
  per layer, lost pick, AbortError) apply unchanged.
- Tests: grid unit tests for the status line and the hour tick; the E2E
  helpers shifted / inPageStatus move to tests/e2e/lib/ducting-e2e.js.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@efiten efiten left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 1af37db, 97392f9, b87dbdf and 5ab3d04 (merge 10e5220 not reviewed).

Every point from the previous round is resolved, and the new tests fail without the fixes: head's test-map-ducting.js against map-ducting.js from ca97bfb gives 91 passed, 17 failed, and six Go mutations (no carry-over, partial returns nil, gap 0, missing 2 m point accepted, strong ETag, all-or-nothing trim) each fail 2 to 4 Duct tests. The status line is visible collapsed at 390 px and 1280 px, and the hidden-layout repro now ends at scrollLeft 50 with no target left. The perf change reproduces: adding and removing 2,000 markers with the overlay on, median of 5, 11,426 ms on 97392f9 and 85 ms on head (93 ms with the overlay off). The new TestDuctStandardAtmosphereIsNormal expectation checks out independently: -36.813 N/km for the 2 m to 975 hPa layer once the 10.9 m level is dropped.

Should fix

  1. The early retry after a partial fetch can spend the daily call budget and then stop refreshes for about a day (cmd/server/ducting_service.go:197-199, :379-400, :421-422, budget check at ducting_source.go:255). Each retry refetches the whole grid: 450 cells is 9 batches, 1,890 calls with gfs. maxPoints is sized for 4 fetches a day, and the hard cap leaves room for one extra fetch per rolling day. The 5, 10, 20, 40, 80 min schedule sends 5 fetches in 195 minutes, then the cap refuses everything until the first one is 24 h old. On a virtual clock driving the real run loop (default config, 450 cells, capped = true, fake Open-Meteo failing 1 of 9 batches):

    • one batch failing permanently: fetches at 0, 5, 75, 115 and 195 min, then "budget" until the next fetch at 1755 min, a gap of 26 h 0 min;
    • one batch failing for the first 3 hours only: a complete fetch at 195 min, then none until 1715 min, a gap of 25 h 20 min.

    Before this range the same failure gave a refresh every 6 h with 50 cells blank. It only applies to the public API with a grid near the budget; self-hosted is not affected. Any of these would bound it:

    • retry only the failed cells and merge them into the stored snapshot, so a retry costs what failed;
    • allow an early retry only when the ledger still has room for the next regular refresh;
    • at most one early retry per refreshMinutes.

    A virtual-clock test asserting no gap above refreshMinutes + 1 h under a persistent partial failure would pin it.

Minor

  1. cmd/server/ducting_calc_test.go:131-133: the comment still says -45.398 N/km between the 2 m point and the 1000 hPa level; the assertion is now -36.813 for 2 m to 975 hPa.
  2. ducting_service.go:233-268: carried cells come from an older model run, and nothing in the response or the UI says so; generatedAt is the new fetch time for all cells. A carried count in the response, or one line in docs/deployment.md near :634, would be enough.
  3. docs/deployment.md:652: the two new rules (levels less than 30 m above the 2 m point are ignored, a missing 2 m point is no data) are in code comments only.
  4. public/map-ducting.js:100-106: LOS_DEFAULT_MHZ = 910.525 copies defaultLOSFrequencyMHz (cmd/server/los_config.go:20). If the server default changes, the overlay treats the new default as an operator choice. A "frequency is default" flag in /api/config/client, or a Go test reading the constant from map-ducting.js, removes the drift.

What I ran (scratch worktree on 5ab3d04)

  • go vet ., gofmt -l ducting_*.go: clean. go test -race -count=1 -run Duct .: ok. go test -count=1 ./... in cmd/server: ok, apart from TestSaveGeoFilterPreservesFileMode, which I skipped because it does not hold on Windows.
  • node tests/unit/test-map-ducting.js: 108 passed, also under TZ America/Chicago, Australia/Lord_Howe and Europe/Brussels. node scripts/check-css-vars.js: 0 undefined.
  • The budget simulation above (temporary test file), a Python recomputation of the standard atmosphere case, and three Chrome checks with real Leaflet, style.css and a stub CSApi (perf, collapsed status, late layout). Open-Meteo was not contacted.
  • Not run: the ducting E2E, test-all.sh, eslint, the full Go suite under -race, 304 behind gzip on a running server, the hour tick and the abort path in a real browser, Live and Planner.

Deep linking in #2459 settles the question from the last round.

Question: do you want to bound the early retry (item 1) in this PR before merge, or merge with the current behaviour and track it in an issue?

zfouts and others added 2 commits November 23, 2026 16:25
…dget affords it

After an incomplete fetch the refresh loop retried on the failure backoff
(5, 10, 20, 40, 80 min), each retry asking for the whole grid. With the
default 450 cells (1,890 gfs calls a fetch) one batch failing for good sent
5 fetches in about 200 minutes, and the daily cap then refused every
refresh for 26 hours.

The early retry is now taken only when the call ledger has room for it and
for every regular refresh that would follow it, refreshMinutes apart, while
the retry is still inside the rolling day. Otherwise the next refresh comes
after refreshMinutes; the failed cells keep the previous forecast's values
meanwhile. A self-hosted baseUrl has no budget and retries as before.

Virtual-clock tests drive the real run loop for 48 hours (one of 9 batches
failing for good, and for the first 3 hours): no gap above refreshMinutes
+ 1 h and no budget refusal.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…, LOS default pinned

- /api/ducting: `carried` counts the cells a refresh took from the previous
  forecast because their batch failed (left out when 0). Documented next to
  the partial-fetch behaviour.
- docs: levels less than 30 m above the 2 m point are ignored; no 2 m
  values means no data.
- Test: LOS_DEFAULT_MHZ in public/map-ducting.js must equal
  defaultLOSFrequencyMHz.
- ducting_calc_test.go: the standard atmosphere comment gives the current
  figures (-36.813 N/km, 2 m to 975 hPa).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (commits 55ddb2ca and 3dd63059). I've bounded the retry in this PR rather than tracking it in an issue.

  1. The early retry spent the budget. After an incomplete fetch, the early retry is now taken only when the call ledger can afford it and every regular refresh after it, refreshMinutes apart, for the 24 h the retry stays in the rolling window (partialRetryDelay, cmd/server/ducting_service.go:420). Otherwise the next refresh comes after refreshMinutes, as after a complete fetch, and the failed cells keep the previous forecast's values meanwhile. The server logs [ducting] no early retry: ....

    • Ledger read. ductingSource.affords (cmd/server/ducting_source.go:234) copies the ledger under the lock and sums it outside, changing nothing.
    • Self-hosted (uncapped) still retries on the plain backoff.
    • Shorter look-ahead isn't enough. Projecting only the next regular refresh still left a 14 h gap with 2 refusals in the permanent-failure case.
    • Tests. TestDuctingServicePartialRetryKeepsRefreshing drives the real run loop on a virtual clock for 48 h: default config, 450 cells, capped, 1 of 9 batches failing. Stored refreshes (minutes from start), including the first fetch's small start delay:
    Scenario Before (5ab3d04b) After
    Batch fails for good 0, 9, 83, 128, 212, then 1776: gap 26 h 04 min, 5 budget refusals 0, 9, 373, 738, 1102, 1466, 1630, 1954, 2319, 2683: longest gap ~6 h 04 min, no refusals
    Batch fails for the first 3 h 0, 9, 83, 128, 212, then 1736: gap 25 h 24 min, 9 refusals 0, 9, 373, 738, 1102, 1466, 1830, 2194, 2559: no refusals

    The test asserts no gap above refreshMinutes + 1 h and no refusal. On 5ab3d04b it fails with longest time without a stored refresh 26h4m12s, want at most 7h0m0s.

    Unchanged here: a fetch that fails outright (more than half the batches, or an HTTP error) still retries on the plain backoff, as before this PR's last range.

  2. Stale comment in ducting_calc_test.go. It now says −36.813 N/km for the 2 m to 975 hPa layer, with the 10.9 m level dropped. I also corrected the range quoted for the other layers (−26.6..−35.4) after recomputing it.

  3. Carried cells. GET /api/ducting now carries carried, the number of cells taken from the previous forecast; it is left out when zero. docs/deployment.md (the partial-fetch paragraph) says those cells come from the previous model run, not the one generatedAt names.

  4. Profile rules in the docs. The calculation section now states that pressure levels less than 30 m above the 2 m point are ignored, and a missing 2 m point means no data for that cell.

  5. LOS_DEFAULT_MHZ drift. A new Go test (cmd/server/los_default_frontend_test.go) reads LOS_DEFAULT_MHZ from public/map-ducting.js and asserts it equals defaultLOSFrequencyMHz. Changing the frontend value to 869.525 fails it, with a message to update both together.

Checks:

  • gofmt -l and go vet clean.
  • go test -race -run "Duct|LOSDefault" ok; go test ./... in cmd/server ok.
  • Ducting unit 108/108, test-all.sh green, eslint 0 errors.

The description is updated.

@efiten

efiten commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

v3.19.0 is out, and its release commit (#2476) turned [Unreleased] in CHANGELOG.md into [3.19.0]. That is the only conflict with master now. Could you merge master in and put your entry under a new [Unreleased] heading? I'll do the re-review of 55ddb2ca and 3dd63059 once it merges cleanly.

Conflicts:
- CHANGELOG.md: [Unreleased] became [3.19.0] in the release commit
  (Kpa-clawbot#2476); the ducting entry moves under a new [Unreleased] / Added.
- test-all.sh: run both new suites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Merged master (v3.19.0, master at 7beed94a) into the branch: 3145dc90.

  1. CHANGELOG.md. The ducting entry moved under a new [Unreleased] / Added.
  2. test-all.sh also conflicted (the Home health card and Analytics route detail: a slower, older load draws over the newer one #2461 suite was added on the same line); it now runs both.

Re-tested on the merge: the cmd/server suite (vet + tests, cgo, musl stack flag) passes, test-all.sh is green, and eslint has 0 errors. CI is running on 3145dc90.

efiten pushed a commit that referenced this pull request Nov 27, 2026
… waits on state (#2446)

Closes #2444. Follow-ups from the review of #2434.

## What changes

> **Master merged in** for v3.19.0 (`986bc45e`, master at `7beed94a`).
It conflicted in `CHANGELOG.md` (this PR's line is now its own
`[Unreleased]` / Fixed entry), in `test-all.sh`, and in `public/home.js`
/ `public/analytics.js`, against #2462's generation counters. Both sides
are kept, and in the health card's `catch` the stale check runs before
`removeMiniMap()`. Re-tested: `test-all.sh` (#2444 tile sync 23/23,
#2461 17/17) and lint, 0 errors. CI is green.
>
> Earlier merge (`16300744`, master at `007ba78a`, with #2442 and
#2450): no conflicts. Re-tested: `test-all.sh` and lint.
>
> Earlier merge (`c4da7137`, master at `6ab97f52`, with #2429 and
#2451–#2454): no conflicts, the three commits below are unchanged.
Re-tested on the merge: `test-all.sh` green (map tile pin 31/31); E2E
against a local server: map providers 28/28, providers harness 16/16,
map teardown races 19/19, vector zoom 3/3, map modal 10/10.

Three commits, one per point in the issue, plus `1a8dcbda` for the
review (section 4) and `7ef2d744` and `0cc89290` from an internal review
(section 5).

### 1. `68dc7e27` No Auto tile burst on a load with a saved pick

On a map with a picker that loads with a valid saved pick,
`MC_attachAutoTiles` used to add the theme's Auto group to the map
first. The control then swapped in the pinned layer straight away, so
the Auto tiles were started only to be cancelled.

Now, when the map has a picker and a valid saved pick at attach time
(`public/map-tile-providers.js:1639`), the Auto group stays off the map.
Its layer is built only when the group first joins the map, which
happens in two cases:
- the user picks **Auto**;
- config arriving later turns the pinned group off, so the pin reads as
Auto.

Maps without a picker, and loads without a pin, are unchanged.

Measured on a pinned reload (light theme, pin `osmfr-hot`, CI fixture
server, Chromium), counting tile images started:

| Page | Before: Auto / pinned | After: Auto / pinned |
|------|-----------------------|----------------------|
| `#/map` | 15 / 15 | 0 / 15 |
| `#/live` | 18 / 24 | 0 / 24 |

Chromium had already sent 0 network requests to the Auto host before
this change: an image aborted in the same task never goes out. So the
waste was DOM and JS work, not network. Other browsers were not
measured.

Remaining case: when config arrives after the map is created and the
pinned group is opt-in, the pin is not valid yet at load, so Auto still
shows first.

Tests:
- Unit (`tests/unit/test-map-layer-builder.js`):
- a pinned picker-map load starts no Auto tile; on the old code it
failed with `Auto tiles started: …cartocdn…light_all…`;
  - picking Auto afterwards shows the theme's map;
- config turning the pinned group off and back on starts the Auto tile
exactly once.
- E2E `7d` (`tests/e2e/test-map-providers-e2e.js:453`) counts both
`<img>` src assignments and network requests to each host. On the old
code:
`{"autoStarted":15,"pinStarted":15,"autoRequested":0,"pinRequested":15}`.

### 2. `23acaa15` A pick made in another tab reaches open maps

The cross-tab `storage` handler only covered the two theme keys. It now
also handles `mc-tile-pinned` and a cleared storage (`key === null`)
(`public/map-tile-providers.js:1750`).

- **Validation.** The new value goes through `getPinnedId` as usual.
Empty or removed means Auto. An unregistered id reads as no pin, so a
map without a picker drops to the theme's map, the same as after a
reload.
- **Maps without a picker** re-sync and follow the pin when it fits the
theme, without a reload.
- **Maps with a picker** keep their layer and radio, and their Auto
still ignores the pin. An explicit pick in that tab stands until the
next load.
- **No write-back.** The handler never writes, so tabs can't echo picks
between each other.
- **Unsaved picks.** A newer value from another tab replaces this tab's
in-memory copy of a pick it failed to save (quota full). The existing
rule still holds: a failed write never brings back an older stored pin.
- **No mid-click deferral.** A `storage` event runs as its own task, so
it can't arrive during a layer-control click handler. This re-sync also
never adds or removes a layer the picker lists.

Tests:
- Unit (`tests/unit/test-map-tile-pin.js`): a pick dispatches one event;
clearing it, an empty value, an unregistered id and a cleared storage
each behave as above; other keys are ignored; nothing is written back; a
newer value supersedes an unsaved pick.
- E2E `7e` (`:518`, `:523`, `:531`) uses three tabs in one browser
context, with real `storage` events:
  - tab A picks and tab B's node map switches without a reload;
  - Auto in tab A returns tab B to the theme's map;
- tab C, on the map page, keeps its layer and radio, and no tab writes
the pick back. Since `1a8dcbda`, C first waits for its own
`mc-tile-pinned` storage event.

  On the old code the pick checks time out.
- Race stress scenario `h` (`tests/e2e/test-map-race-stress-e2e.js`,
local only like the rest of that suite) has two tabs make rapid
alternating picks. They must converge, with no page errors and bounded
writes. It failed 4 of 6 iterations on the old code.

One line each in `docs/user-guide/map.md`, `docs/deployment.md` and the
CHANGELOG now describes the cross-tab behaviour. Since `1a8dcbda` that
includes the Home and Analytics maps (section 4).

### 3. `6fda048f` `4b` waits on state, not a fixed 300 ms

Both `waitForTimeout(300)` calls in check `4b` (`:263`) are replaced
with `waitForFunction` on the write count and the checkbox state. After
the wait the check confirms the count has not gone past the expected
value. It still fails with the `0506fc1d` deferral disabled (`eox-labels
box not ticked after the first click`). No `waitForTimeout` is left in
either providers E2E file.

### 4. `1a8dcbda` Review follow-ups

- **Home and Analytics follow the pick.** The Home mini-map and the
Analytics route map used to resolve their tiles once, when built, so a
pick in another tab (or a theme flip) did not reach them, although the
docs said it did. Both now go through the shared `_applyTilesToNodeMap`
helper (`public/nodes.js`), the same one the node, reach and RX coverage
maps use. The provider's own `maxZoom` (OpenTopoMap 17, USGS 16) and
dark filter carry over.
- **Teardown.** Each page drops its map through one function that
unregisters it from the tile-sync registry before removing it:
`removeMiniMap` (`public/home.js:275`) and `removeSubpathMap`
(`public/analytics.js:27`). That includes paths that used to replace the
map's container without removing the map: `showChooser` and `renderHome`
on Home, `renderTab` on Analytics.
- **Other storage areas.** The `storage` handler ignores events from
another storage area (`_otherStorageArea`,
`public/map-tile-providers.js:1745`). A `sessionStorage.clear()` in a
same-origin iframe (`key === null`) no longer drops an unsaved pick. An
event with no `storageArea`, or a `localStorage` that throws when
accessed, is treated as `localStorage`.

Tests:
- `tests/unit/test-issue-2444-secondary-map-tile-sync.js` (new, 18
cases) covers each map's build, a pick, a cross-tab storage event, a
theme flip, destroy, replace, re-render and the fallback with no helper.
On the old code: 4 passed, 12 failed.
- `test-map-tile-pin.js` adds cases for a foreign storage area, an
absent one and a throwing `localStorage`. On the old code the
foreign-area case fails with "the unsaved pick was dropped".
- E2E `7e` (`:551`): the Home and Analytics maps follow a pick in tab A,
and its Auto. On the old code it times out.

### 5. `7ef2d744`, `0cc89290` Internal review follow-ups

- **Lazy Auto tests.** These tests now pin the lazy Auto path:
- on a pinned picker load, the Auto group stays empty, also after a
theme flip and a cross-tab pin;
- a vector theme default is not built, so there is no MapLibre download,
until Auto is picked.

Each test was checked by deleting the line it guards. The unreachable
`lazy && !lc` fallback is removed: the control is null only without
Leaflet.
- **Home mini-map timer.** The resize timer now captures its own map, so
a card replaced within 100 ms no longer throws on a null map.
- **Overlapping and failed loads.** Tests cover overlapping Home loads
and a failed load: the earlier map is removed and unregistered.
- **Cleared storage.** A cleared `localStorage` in another tab now
re-syncs the ticked overlays too.
- **Unsaved overlay tick.** An overlay tick whose save failed now gives
way to a newer value from another tab, or to storage cleared there, as
the pin already did (`0cc89290`).

A slower, older Home or Analytics load drawing over a newer one was
fixed on `master` by #2462 (for #2461), which is now merged in here.

## Performance

Commit 1 removes work: no Auto tile layer and its tile images on a
pinned load of a picker map (table above). The `storage` handler runs
only when another tab changes the pin: one validated read and one event
dispatch, which each map handles with its existing `sync()`.

## Testing

| Check | Result |
|-------|--------|
| `sh test-all.sh` | all standalone frontend suites pass (on `0cc89290`:
layer builder 35/0, tile pin 34/0, secondary map tile sync 23/0,
overlays + vector 34/0; on `1a8dcbda`: tile pin 34/0, layer builder
32/0, secondary map tile sync 18/0, secondary map tile builder 10/0) |
| `npx eslint public/*.js` | 0 errors, 87 warnings, unchanged from
`master` |
| `test-map-providers-e2e.js` | 28 passed, 0 failed; on `1a8dcbda` 29
passed, 0 failed |
| `test-map-providers-harness-e2e.js` | 16 passed, 0 failed |
| Race stress, seeds 20261118, 4242, 777 and 31337 | all scenarios pass
(the cross-tab one was called `g` in those runs) |
| Race stress, cross-tab scenario only, seed 909, 20 iterations | passes
|

The E2E and stress suites ran against the CI fixture, freshened and
migrated, on a local server. The engineer ran two of the seeds and I
re-ran everything with the other two.

**Scenario name and the other open PRs.** The cross-tab stress scenario
is `h`, not `g`. #2436 (the ducting overlay) adds its own scenario `g`.
With both named `g`, git merged the two branches silently into a file
with two `scenarioG` declarations, and only one of them would have run.
`h` also runs outside the scenario table, so the line #2436 changes
there stays untouched. I checked on `master` with #2436, this PR and
#2445 merged together:

- all three merge with no conflicts, in each of three orders;
- `test-all.sh`, lint and the Go suites pass;
- the providers E2E passes 28/28, the harness 16/16 and the ducting E2E
28/28;
- the race stress suite passes scenarios a–h on seeds 20261118 and 5150.

No screenshots: nothing visual changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	CHANGELOG.md
#	test-all.sh
@efiten
efiten merged commit 80c691c into Kpa-clawbot:master Nov 27, 2026
17 checks passed
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 28, 2026
… positions

The merge of master brought the ducting overlay (Kpa-clawbot#2436), whose node read
ductingNodeCoords selected nodes.lat/lon in ducting_service.go. With
location privacy on, the overlay's forecast cells followed exact
positions; it serves them in /api/ducting and names them to the weather
API. The read now lives in node_coords.go and returns servedNodePos; the
visibility rule still classifies by the stored position. Rows without
lat or lon, or with no servable position (malformed key), are skipped.

TestDuctingNodeCoordsFuzzed covers privacy on and off, NULL rows and a
malformed key. /api/ducting gets its leak-route entry (ducting is off in
the fixture, so it is the 404).

Co-Authored-By: Claude Fable 5.2 <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.

2 participants