Skip to content

fix(dbschema): observers rebuild keeps local objects, requires a rowid idx, closes DB on failed open - #2445

Merged
efiten merged 8 commits into
Kpa-clawbot:masterfrom
zfouts:fix/observers-rebuild-local-objects
Nov 24, 2026
Merged

efiten merged 8 commits into
Kpa-clawbot:masterfrom
zfouts:fix/observers-rebuild-local-objects

Conversation

@zfouts

@zfouts zfouts commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2443. Follow-up to #2407.

What changes

Master merged in again (da87b2cd, master at 007ba78a, with #2442 and #2450): no conflicts. CI is green on the head 7d2ab1a7. One run on da87b2cd failed master's new repeater-info E2E; this PR changes nothing that suite uses, and it passed on the next run.

Earlier merge (3e5288b0, master at 6ab97f52, with #2429 and #2451–#2454): no conflicts, the three commits below are unchanged. Re-tested on the merge: go vet and go test across all modules (Alpine, cgo, 8 MiB musl stacks), all green.

Three commits, one per fix, plus ba69a7f2 for the first review (section 4), 0a17c0b8 from an internal review (section 5), and 7d2ab1a7 for the approving review's three points (section 6).

1. 4121a791 Close the DB when OpenStore fails

OpenStoreWithInterval returned without closing the *sql.DB when ping, schema setup, dbschema.Apply or statement preparation failed. One deferred close now covers every error after sql.Open (cmd/ingestor/db.go:159). This is why TestOpenStoreRefusesUnconvertibleObservers could not remove its temp dir on Windows.

  • TestOpenStoreClosesDBOnFailure counts the descriptors open on the DB file after a failed open, using /proc/self/fd on Linux, and on every OS checks that the file can be removed afterwards (an open handle blocks that on Windows). On the old code: failed OpenStore left 3 descriptor(s) open on the database.

2. 6cac470c Require observers.idx to be the INTEGER primary key

observersColumnsInfo (internal/dbschema/observers_idx.go:123) treated idx as done when it had pk == 1. That accepts keys that are not the rowid alias observer_idx relies on. It now requires all of:

  • idx is the only primary-key column;
  • it is declared exactly INTEGER;
  • pragma_index_list('observers') has no pk-origin index.

The last check catches idx INTEGER PRIMARY KEY DESC (a documented SQLite quirk: type INTEGER, pk=1, but not an alias) and WITHOUT ROWID tables.

AssertReady and the rebuild share this check. So the server reports observers.idx (not the rowid alias) for these shapes, and the rebuild no longer takes them as already migrated: it refuses with its own message (section 4), leaving the table untouched.

  • The new AssertReady cases (TEXT key, composite key, DESC, WITHOUT ROWID) returned err = <nil> on the old code.
  • TestObserversIdxRefusesNonRowidIdxKey and TestObserversIdxRefusesWithoutRowid also returned err = <nil> on the old code: the table was treated as migrated.

3. 8bca5304 Keep local indexes, triggers and views across the rebuild

Before this change, indexes and triggers an operator added to observers were dropped with the old table, without a message. Any view on observers made the rename fail with a raw error in view …: no such table: main.observers.

The rebuild now recreates them rather than refusing.

  • Capture. Inside the rebuild transaction, before anything is dropped, captureLocalObservers (observers_idx.go:460) reads from sqlite_master, in creation order:

    • indexes and triggers on observers;
    • views, and triggers on other tables, whose SQL names observers, packets_v or an already captured view.

    It repeats until nothing new is found. CoreScope's own packets_v and two observers indexes are excluded.

  • Drop. The captured views, and the triggers on other tables, are dropped before the rename.

  • Recreate. Everything is recreated from its original SQL after our own objects. The ingestor logs one line naming what it recreated.

  • Failure. If an object cannot be recreated, the whole transaction rolls back. The error names the object and how to continue (observers_idx.go:435): drop it and recreate it after the upgrade, or run the previous version.

These rules come from experiments on SQLite 3.53.4:

  • the rename fails for a view on observers, a view on a dropped view, and a trigger on another table that mentions observers;
  • DROP TABLE takes the table's own triggers with it, and DROP VIEW takes its INSTEAD OF triggers.

Concurrent starts. A new test runs Apply 8 times at once over two *sql.DB handles on one WAL file. It found a second race: a deferred transaction that reads first fails with database is locked once another process has rebuilt, and busy_timeout doesn't retry that upgrade. The rebuild transaction now takes the write lock before its first read. Since ba69a7f2 it does this with BEGIN IMMEDIATE (section 4); this commit first used a no-op DELETE FROM observers WHERE 0.

  • BEGIN IMMEDIATE waits on busy_timeout, so concurrent rebuilds take turns and the later one sees the table done.
  • It only runs when a rebuild is needed: a migrated table returns before the transaction.

4. ba69a7f2 Review follow-ups

  • Lock without compiling triggers. DELETE FROM observers WHERE 0 compiled every DELETE trigger on observers, so one referencing a dropped table failed the upgrade (lock observers: no such table: main.gone) where the base commit did not. The rebuild now runs as a raw BEGIN IMMEDIATE … COMMIT on the pinned connection, which compiles nothing against observers. Every exit that does not commit issues ROLLBACK on that same connection, so the connection never returns to the pool inside a transaction. If ROLLBACK itself fails, the connection is discarded. TestObserversRebuildCarriesBrokenDeleteTrigger failed with that error before this change.
  • A refusal for idx that is not the rowid alias. A plain idx column can be dropped, and the message suggests ALTER TABLE observers DROP COLUMN idx. An idx in the primary key cannot (cannot drop PRIMARY KEY column), so that message says to recreate the table without it. The tests execute every statement a message suggests, and check that DROP COLUMN really fails for the primary-key shapes.
  • Quoted names in suggestions. The suggested DROP VIEW "my view" is quoted the same way as the DROP the rebuild runs itself, through a shared quoteIdent.
  • Wording. AssertReady says observers.idx (not the rowid alias). The unknown-column refusal no longer suggests renaming, which would not help.
  • Tests. There is now a direct table test for mentionsIdentifier (observers_archive, client_observers, "Observers", main.observers, [observers]).

Tests:

Test Old code
TestObserversRebuildKeepsLocalObjects (index, trigger, views, a view on a view with an INSTEAD OF trigger, a view on packets_v, a trigger on observations that writes observers) the index and trigger vanished; the view failed the rename
TestObserversRebuildLocalTriggersFire error in trigger local_observations_count
TestObserversRebuildLocalViewsQueryable rename error
TestObserversRebuildRefusesUnrecreatableLocalObject (schema, rows, local objects and packets_v unchanged after the refusal) new behaviour
TestObserversRebuildLocalObjectsIdempotent new behaviour
TestObserversRebuildConcurrentApply drop packets_v: database is locked in 4 of 5 runs; 30 of 30 pass with the fix under -race

5. 0a17c0b8 Internal review follow-ups

  • Quoted view names. A trigger on a view whose name contains " is now captured by its tbl_name, and mentions also match the name as written inside double quotes. Before, an INSTEAD OF trigger on such a view was lost without a word, and a view built on it failed the rename.
  • DROP COLUMN suggestions. Each refusal that suggests DROP COLUMN also says to drop any index, view or trigger that uses the column first; SQLite rejects the drop otherwise.
  • Foreign-key refusal. It now says how to continue: declare the child column REFERENCES observers(id) (extended in section 6).
  • Rollback helper. The rollback-or-discard step is a named helper, rollbackOrDiscard, with its own tests. A table dropped between the two reads now ends the rebuild instead of reporting a missing id column.
  • CHANGELOG. The concurrency sentence now covers only what the code serialises: concurrent rebuilds of the observers table.

6. 7d2ab1a7 Approving review's points

  • Foreign key refusal. It names both causes and both ways out: a child column declared REFERENCES observers with no column, or rows that already reference a missing observer (list them with PRAGMA foreign_key_check(...)).
  • Lock test. A deterministic test pins BEGIN IMMEDIATE and the "migrated meanwhile" exit. It fails 30 of 30 with plain BEGIN.
  • Backtick-quoted names. A captured view name written in backticks is matched too.

Tests: TestObserversIdxForeignKeyRefusalCoversOrphanRows (runs the suggested PRAGMA foreign_key_check, deletes the orphan, then the rebuild succeeds) and TestObserversRebuildWaitsForWriterThenSeesMigrated (fails 30 of 30 with plain BEGIN).

Not covered

  • A view or trigger in the database that is already broken, unrelated to observers, still makes the rename fail with the raw SQLite error, as it does today.
  • A local SELECT * view on observers gains the idx column after the rebuild.
  • Two ingestors starting on one legacy file at once can still fail in EnsurePacketsView (view packets_v already exists). That code predates this PR, which does not touch it.
  • A WITHOUT ROWID legacy table with no idx column fails with a raw no such column: rowid and is rolled back. That fails safe, and the shape is exotic.

Performance

None of this is on a hot path. The capture runs once, inside the one-time rebuild, over the schema's few dozen sqlite_master rows. The extra primary-key probe in observersColumnsInfo is one pragma_index_list read at startup, and only when the other checks pass.

Testing

Run in a cgo golang:1.27-alpine container:

  • gofmt -l is empty and go vet is clean in internal/dbschema and cmd/ingestor.
  • internal/dbschema: go test -count=3 -race ./... passes.
  • cmd/ingestor, cmd/server and cmd/migrate: go test -count=1 ./... passes.
  • On ba69a7f2: go vet and go test -count=1 ./... pass in internal/dbschema, cmd/ingestor, cmd/server and cmd/migrate. TestObserversRebuildConcurrentApply passes in 15 of 15 runs.
  • On 7d2ab1a7: gofmt -l empty, go vet clean, go test -count=1 ./... ok in internal/dbschema and cmd/ingestor; the new tests pass in 20 repeated runs and TestObserversRebuildWaitsForWriterThenSeesMigrated with -count=50.
  • Windows (independent, on 7d2ab1a7): TestOpenStoreRefusesUnconvertibleObservers and TestOpenStoreClosesDBOnFailure passed 5 consecutive runs, and the full native ingestor suite passed; the same cleanup test fails on master 007ba78a.

This is backend only, so there are no frontend or browser changes.

🤖 Generated with Claude Code

zfouts and others added 3 commits November 21, 2026 15:49
OpenStoreWithInterval returned on every error after sql.Open (Ping,
applySchema, dbschema.Apply, prepareStatements) without closing the
database, so a refused observers rebuild left the file open. On Windows
TestOpenStoreRefusesUnconvertibleObservers could not then remove its temp
dir. One deferred close keyed on the named error covers every path.

TestOpenStoreClosesDBOnFailure counts the process's descriptors on the
database file (via /proc/self/fd) after a refused open.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
observersColumnsInfo took any primary key that included a column named idx
for the rebuilt shape. `idx TEXT PRIMARY KEY` or `PRIMARY KEY (idx, id)`
then passed AssertReady and made the rebuild report "already migrated",
though idx is not the rowid alias observations.observer_idx relies on.

idxIsPK now requires idx to be the sole primary-key column, declared
exactly INTEGER, with no "pk"-origin index in pragma_index_list. SQLite
builds that index for every key that is not the rowid, which also rejects
the two shapes that pass the type test yet alias nothing: the documented
`INTEGER PRIMARY KEY DESC` quirk and a WITHOUT ROWID table (where
`SELECT rowid` fails with "no such column"). Such tables are refused on
the existing unknown-column path, untouched.

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

The observers rebuild (Kpa-clawbot#2407) drops the legacy table and renames the new
one into place. An index or trigger an operator had added on observers
went with DROP TABLE, silently; a view on observers, a view on such a
view, a view on packets_v, or a trigger on another table that mentions
observers made ALTER TABLE RENAME fail ("error in view v: no such table:
main.observers"), stopping the ingestor with a raw error.

Inside the transaction, before any DROP, the rebuild now captures those
objects from sqlite_master in rowid order (indexes and triggers on
observers; views and other triggers whose SQL names observers, packets_v
or an already captured view, as a whole word, repeated to a fixpoint;
INSTEAD OF triggers come along with their view), drops the views and
outside triggers, and re-runs each definition after the rename and after
its own indexes and packets_v. One that fails rolls everything back with
an error naming it and the way out; what was recreated is logged.

The concurrency test exposed a second failure: two processes rebuilding
one file each read inside a deferred transaction, and the later writer's
stale WAL snapshot fails with "database is locked" without waiting on
busy_timeout. The transaction now starts with a no-op write (DELETE ...
WHERE 0), which takes the write lock under busy_timeout before any read,
so concurrent rebuilds serialise and the later one finds the table done.

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

zfouts commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master (6ab97f52) into the branch: merge commit 3e5288b0, no conflicts, the three fix commits are unchanged. go vet and go test pass across all modules locally; the description has the details.

@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 3e5288b (base 6ab97f5).

The three fixes do what the description says. There is one step back against base, in a schema that is already broken, plus a few operator messages that do not match what SQLite does.

Should fix

  1. internal/dbschema/observers_idx.go:227: DELETE FROM observers WHERE 0 compiles every DELETE trigger on observers. With a DELETE trigger that references a dropped table, the rebuild now fails with lock observers: no such table: main.gone and leaves the table unmigrated, so the ingestor does not start. Base 6ab97f5 returns no error on the same database. A broken INSERT trigger on observers is carried across fine, so only DELETE triggers hit this. The message names no trigger and gives no way forward, unlike the other refusals in this PR. Two options:
    • take the lock with a raw BEGIN IMMEDIATE on the pinned *sql.Conn the function already holds;
    • keep the statement and wrap the error like the other refusals (name the object, say how to continue).

Minor

  1. observers_idx.go:257-259: the refusal suggests ALTER TABLE observers DROP COLUMN <name>. For idx TEXT PRIMARY KEY SQLite answers cannot drop PRIMARY KEY column: "idx". The "idx is not the rowid alias" case needs its own message.
  2. AssertReady: for INTEGER PRIMARY KEY DESC and WITHOUT ROWID it reports observers.idx (not the primary key), but idx is the primary key there, just not the rowid alias. "not the rowid alias" matches the code comment.
  3. observers_idx.go:336-338: the suggested DROP %s %s is unquoted, while dropLocalObservers (:451) quotes. For a name like my view the pasted statement does not run.
  4. mentionsIdentifier (observers_idx.go:462-478) has no direct test. Its word-boundary rule is what keeps observers_archive or client_observers out of the capture. A small table test with those two plus "Observers", main.observers and [observers] would pin it.
  5. TestOpenStoreClosesDBOnFailure only observes on Linux (/proc/self/fd). Asserting that os.Remove(path) succeeds after the failed open would cover Windows too.

What I ran (Windows, scratch worktree on 3e5288b)

  • internal/dbschema: go vet, gofmt -l, go test -count=1 ./...: clean, ok. TestObserversRebuildConcurrentApply -count=15: 15 of 15 pass.
  • cmd/ingestor: go vet, go test -count=1 ./...: ok, no FAIL lines. TestOpenStoreRefusesUnconvertibleObservers, which fails locally on Windows because of the TempDir lock, passes on this head.
  • A scratch test with 12 cases (10 on head, 2 on base). Quoted and bracketed names, IF NOT EXISTS, a partial unique index, "Observers" and main.observers references, a forward-referencing view pair, and a trigger on observations that reaches observers through a view were all recreated with identical SQL. Items 1 and 2 come from the same scratch test.
  • Not run: cmd/server, cmd/migrate, -race, anything on Linux. CI covers those and is green.

Question: do you want to take item 1 in this PR, or merge as is and track item 1 in a follow-up issue?

…als that run

Review follow-ups on Kpa-clawbot#2445:

- Take the rebuild's write lock with a raw BEGIN IMMEDIATE on the pinned
  connection instead of `DELETE FROM observers WHERE 0`. The DELETE compiled
  every DELETE trigger on observers, so one referencing a dropped table
  failed the upgrade ("no such table") where the base commit did not.
  Every exit without COMMIT rolls back on the same connection; a failed
  ROLLBACK discards the connection instead of pooling it.
- An idx column that is not the rowid alias gets its own refusal: a plain
  idx can be dropped (ALTER TABLE ... DROP COLUMN idx), a primary-key idx
  cannot, so that message says to recreate the table.
- AssertReady reports "observers.idx (not the rowid alias)".
- The suggested DROP for an object that cannot be recreated quotes its
  name, like the DROP the rebuild runs itself (shared quoteIdent).
- Tests: broken DELETE trigger carried across, every suggested statement
  executed, mentionsIdentifier table test, and the failed-open test also
  checks the file can be removed (Windows).

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 (commit ba69a7f2). Item 1 is taken in this PR.

  1. Broken DELETE trigger. The DELETE FROM observers WHERE 0 lock is gone. The rebuild now runs as a raw BEGIN IMMEDIATE … COMMIT on the pinned *sql.Conn, which compiles nothing against observers. Every exit that does not commit, including the "already migrated meanwhile" exit and a panic, issues ROLLBACK on the same connection before it goes back to the pool. If ROLLBACK fails, the connection is discarded. TestObserversRebuildCarriesBrokenDeleteTrigger failed on 3e5288b0 with lock observers: no such table: main.gone and passes now, with the trigger carried across unchanged. TestObserversRebuildConcurrentApply passes in 15 of 15 runs.
  2. Refusal for an idx that is not the rowid alias. It has its own message (refuseNonAliasIdx). For a plain column it suggests ALTER TABLE observers DROP COLUMN idx. For an idx in the primary key, including WITHOUT ROWID, it says SQLite cannot drop it, so the table has to be recreated without it, or the previous version run. The tests execute each suggested statement, and check that DROP COLUMN fails for the primary-key shapes. The generic message no longer suggests renaming, since a renamed column is still outside the canonical shape.
  3. Wording. AssertReady now says observers.idx (not the rowid alias).
  4. Quoting. The suggested DROP quotes the name through the same quoteIdent that dropLocalObservers uses. TestRecreateRefusalSuggestsRunnableDrop runs the suggestion for my view, a name containing quotes, and a keyword.
  5. mentionsIdentifier. TestMentionsIdentifier covers observers_archive, client_observers, "Observers", main.observers, [observers], and the start and end of the string.
  6. Windows. TestOpenStoreClosesDBOnFailure also asserts that os.Remove(path) succeeds, and no longer skips without /proc. The Linux descriptor count is kept.

Run in a cgo Alpine container: go vet and go test -count=1 ./... pass in internal/dbschema, cmd/ingestor, cmd/server and cmd/migrate, and gofmt -l is empty. I have not run them on Windows; CI covers Linux. The PR description is updated (section 4).

Left as is: a WITHOUT ROWID legacy table with a plain, non-key idx would still fail at SELECT rowid after the suggested drop. That shape needs both a hand-made WITHOUT ROWID table and an extra idx column, so I've left it out.

zfouts and others added 2 commits November 23, 2026 10:48
…how to continue

Follow-ups from an internal review of Kpa-clawbot#2445:

- A view whose name contains a double quote lost its INSTEAD OF trigger
  silently, and a view on it failed the rename: triggers on a captured
  view are now captured by tbl_name, and mentions also match the name as
  written inside double quotes.
- Refusals that suggest DROP COLUMN also say to drop any index, view or
  trigger using the column first (SQLite rejects the drop otherwise).
- The foreign key refusal says how to continue (REFERENCES observers(id)).
- The rollback-or-discard step is a named helper with tests; a table gone
  between the two reads ends the rebuild instead of reporting "no id".
- CHANGELOG: the concurrency claim covers concurrent observers rebuilds,
  which is what the code serialises.

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 (commit 0a17c0b8):

  1. Quoted view names. An INSTEAD OF trigger on a view whose name contains " was dropped without a word, and a view on such a view failed the rename. Triggers on a captured view are now captured by tbl_name, and mentions also match the name as written inside double quotes. Both cases are now in the tests.
  2. Suggested DROP COLUMN. Every refusal that suggests it now also says to drop any index, view or trigger that uses the column first; SQLite rejects the drop otherwise.
  3. Foreign key refusal. It now says how to continue: declare the child column REFERENCES observers(id).
  4. Rollback. The rollback-or-discard step is a named helper with its own tests. A table dropped between the two reads ends the rebuild instead of reporting "no id column".
  5. CHANGELOG. The concurrency sentence is narrowed to what the code serialises: concurrent rebuilds of the observers table.

Checks: go vet and go test pass in internal/dbschema and cmd/ingestor. TestObserversRebuildConcurrentApply passes in 15 of 15 runs.

@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 ba69a7f and 0a17c0b (merge da87b2c not reviewed).

Every point is resolved as described. TestObserversRebuildCarriesBrokenDeleteTrigger is a real regression test: with DELETE FROM observers WHERE 0 put back after the BEGIN it fails with begin observers rebuild: no such table: main.gone. The deferred order (ROLLBACK, then the foreign_keys restore, then conn.Close()) holds on the exits I could exercise on a one-connection pool: a refusal, "migrated meanwhile", and a write lock held past busy_timeout (fails after 5.5 s with database is locked, pool clean, a retry succeeds). The discard through conn.Raw(... driver.ErrBadConn) (observers_idx.go:426) closes the driver connection, and go-sqlite3 v1.14.52 has no ResetSession, so nothing reuses the connection mid-transaction. Leaving out the WITHOUT ROWID table with a plain idx is reasonable: no earlier version could have run on that shape either.

Three small points, none blocking:

  1. observers_idx.go:627-631: the foreign key refusal states one cause as fact. A child column that is already REFERENCES observers(id) but holds an orphan row (inserted with foreign_keys=OFF, as the sqlite3 CLI does by default) gets the advice to declare REFERENCES observers(id), and the refusal repeats on every start. Wording it conditionally and adding "or delete the rows PRAGMA foreign_key_check(<table>) lists" would cover both.
  2. TestObserversRebuildConcurrentApply pins BEGIN IMMEDIATE only by chance: with plain BEGIN it passed 30 of 30 runs in one batch and failed only somewhere in a 300-run batch. The "migrated meanwhile" exit (:258-262) was reached 3 times in 60 runs. A deterministic version: handle 1 takes BEGIN IMMEDIATE on a pinned conn, handle 2 starts ensureObserversIdx in a goroutine, handle 1 reshapes observers and commits, then assert handle 2 returns nil with foreign_keys=1 and both handles can write. In my scratch copy that passes on head and fails every time with deferred BEGIN.
  3. :498-506: a captured view whose name holds a backtick, referenced in backtick quoting ( `ab ``), is not matched. It fails closed (rename observers_new: error in view v2: no such table: main.ab), table untouched, but without the "how to continue" text. Fine as a follow-up or out of scope.

What I ran (Windows, scratch worktree on 0a17c0b)

  • internal/dbschema: gofmt -l empty, go vet clean, go test -count=1 ./... ok. TestObserversRebuildConcurrentApply: 180 runs, all pass.
  • cmd/ingestor: go vet clean, go test -count=1 ./... ok. TestOpenStoreClosesDBOnFailure no longer skips on Windows and passes.
  • Two mutations (deferred BEGIN, the DELETE lock put back) and six scratch tests for the exits above, the WITHOUT ROWID case, a trigger on packets_v, backtick and bracket names, and the FK orphan.
  • Not run: cmd/server, cmd/migrate, -race, Linux, the panic and failed-COMMIT exits (read only).

Question: do you want to take item 1 and the test from item 2 in this PR, or should I merge as is and track them in a follow-up issue?

…DIATE; backtick view names

Three points from the review of Kpa-clawbot#2445.

- The foreign key refusal stated one cause as fact. A child column that is
  already `REFERENCES observers(id)` but holds a row for a missing observer
  (written with foreign_keys off) was told to redeclare the column, at every
  start. It now gives both causes and both ways out, with the
  `PRAGMA foreign_key_check("<table>")` that lists the rows.
- TestObserversRebuildWaitsForWriterThenSeesMigrated pins BEGIN IMMEDIATE and
  the "migrated meanwhile" exit: one handle holds the write lock and migrates
  the table by hand while a second handle's rebuild waits, then returns nil
  with foreign_keys restored. With a deferred BEGIN it fails every run
  ("drop packets_v: database is locked").
- A captured view whose name holds a backtick, referenced in backtick
  quoting, is now matched like the double-quote form, so a view on it is
  carried across instead of failing the RENAME.

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

zfouts commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the approval. I've taken all three points in this PR (7d2ab1a7).

  1. Foreign key refusal. It now names both causes and both ways out. One is a child column declared REFERENCES observers with no column (declare it REFERENCES observers(id)). The other is rows that already reference a missing observer: list them with PRAGMA foreign_key_check("<table>"), quoted with the same quoteIdent, and delete or fix them. TestObserversIdxForeignKeyRefusalCoversOrphanRows covers the second case. It builds a child already declared REFERENCES observers(id) with an orphan row inserted under foreign_keys=OFF, checks the refusal, runs the suggested PRAGMA (it lists the orphan), deletes the row, and the rebuild then succeeds. The existing FK test also asserts both hints.

  2. Deterministic lock test. TestObserversRebuildWaitsForWriterThenSeesMigrated follows your outline:

    • handle 1 takes BEGIN IMMEDIATE on a pinned connection;
    • handle 2 runs ensureObserversIdx in a goroutine and waits on busy_timeout;
    • handle 1 migrates observers and commits;
    • handle 2 returns nil through the "migrated meanwhile" exit, with foreign_keys restored, and both handles can write afterwards.

    Handle 2's connection is opened (Ping) before handle 1 takes the lock. Without that, handle 2 waits in connection setup instead (the DSN pragmas), and the mutation goes unnoticed. With plain BEGIN the test fails 30 of 30 (drop packets_v: database is locked). It passes -count=50.

  3. Backtick-quoted names. A captured view name is also matched as written inside backticks ( `oddtick``), alongside the double-quoted form. The quoted-name test has the backtick case: a view on such a view is recreated with identical SQL. Before the change it failed withno such table: main.oddtick.

Checks:

  • internal/dbschema: gofmt -l empty, go vet clean, go test -count=1 ./... ok.
  • The new and concurrency tests pass in 20 repeated runs; TestObserversRebuildConcurrentApply with -count=15.
  • cmd/ingestor: ok.

@n30nex

n30nex commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

I reproduced the Windows cleanup failure on upstream 007ba78a. In TestOpenStoreRefusesUnconvertibleObservers/unknown_column, legacy.db was still in use when Go removed the temporary directory.

On 7d2ab1a77, that test and TestOpenStoreClosesDBOnFailure passed five consecutive runs on the same Windows host. The full native ingestor suite also passed in 364 seconds. This independently confirms that a failed open releases the database file on Windows.

@efiten
efiten merged commit 70dc445 into Kpa-clawbot:master Nov 24, 2026
17 checks passed
efiten added a commit that referenced this pull request Nov 24, 2026
Release notes and changelog entry for v3.19.0.

- `docs/release-notes/v3.19.0.md`: the full notes, also the GitHub
release body (`deploy.yml` reads it as `body_path`).
- `CHANGELOG.md`: `[Unreleased]` becomes `[3.19.0] - 2026-11-24` with
six highlights. The SMTP and map-provider lines that were under
`[Unreleased]` are covered by the highlights and the notes.

32 commits since v3.18.0, up to `70dc4453` (#2445): 14 fix, 8 feat, 5
test, 2 ci, 2 docs, 1 refactor. Types come from the PR titles; #2442,
#2429 and #2430 have no prefix and count as feat, #2450 as fix.

Read before upgrading, in the notes: the one-time `observers` rebuild
(#2407, #2445), the content-hash migration now running in the ingestor
(#2409), `users.db` schema v10 with accounts on (#2429), and SNR per
node from direct receptions only (#2451-#2454).

Left out on purpose: #2446 (map picker follow-ups to #2434, not yet
approved), for v3.19.1.

Not done: no staging run of master before tagging.

After merge: tag `v3.19.0` on this PR's squash commit once its `:edge`
image carries that revision.
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>
efiten added a commit that referenced this pull request Nov 27, 2026
…y default) (#2436)

## 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](#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](https://open-meteo.com/) 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:
  ```json
  "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 (#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 #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:
- Each refresh is already sized to Open-Meteo's free tier: `maxPoints`
is lowered so the refreshes fit in 10,000 calls a day.
- Showing past days by asking Open-Meteo for them again would spend more
of that budget on every refresh. The cheaper way is to keep the
forecasts we have already fetched.
- Keeping them in memory would work, but an operator would lose the
history at every server restart. They belong in the database, kept for 2
to 7 days.
- The server only reads the analyzer database (#1283). Stored snapshots
therefore go through the ingestor, or through the Postgres support in
#2396 with Postgres enforcing the retention. That design is its own PR,
built on this one.

## 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.

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/ducting-map-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/thumbs/ducting-map-light.png"
width="260" alt="Map, light: bands of the lowest-1.5 km refractivity
gradient; dashed outlines are ducts that may carry LoRa (model
estimate)"></a><br>Map, light: bands of the lowest-1.5 km refractivity
gradient; dashed outlines are ducts that may carry LoRa (model estimate)
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/ducting-map-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/thumbs/ducting-map-dark.png"
width="260" alt="Map, dark"></a><br>Map, dark | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/ducting-live-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/thumbs/ducting-live-light.png"
width="260" alt="Live page"></a><br>Live page |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/ducting-zoom-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/thumbs/ducting-zoom-light.png"
width="260" alt="Zoomed in over the Gulf"></a><br>Zoomed in over the
Gulf | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/ducting-popup-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/f6b99cf88d58ee36aaf413e299a0073599095c11/tropo-ducting-r4/thumbs/ducting-popup-light.png"
width="260" alt="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"></a><br>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):

| | | |
|---|---|---|
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/desktop-light-expanded.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/desktop-light-expanded.png"
width="260" alt="Desktop, light: title bar, timeline and
legend"></a><br>Desktop, light: title bar, timeline and legend | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/desktop-dark-moved.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/desktop-dark-moved.png"
width="260" alt="Desktop, dark: panel dragged to the top right, Reset
shown"></a><br>Desktop, dark: panel dragged to the top right, Reset
shown | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/timeline-daychange-light.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/timeline-daychange-light.png"
width="260" alt="Timeline at a midnight: the next day pushes the
previous label off"></a><br>Timeline at a midnight: the next day pushes
the previous label off |
| <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/phone-light-expanded.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/phone-light-expanded.png"
width="260" alt="Phone, light: docked and expanded"></a><br>Phone,
light: docked and expanded | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/phone-dark-collapsed.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/phone-dark-collapsed.png"
width="260" alt="Phone, dark: collapsed by default, timeline
kept"></a><br>Phone, dark: collapsed by default, timeline kept | <a
href="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/timeline-midscroll-dark.png"><img
src="https://raw.githubusercontent.com/zfouts/CoreScope/9d6225779c198d57d06b3b376a3ad410ae2c5d36/tropo-ducting-panel-r2/thumbs/timeline-midscroll-dark.png"
width="260" alt="Timeline, dark: keyboard focus, five hours
ahead"></a><br>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:

- All three merge onto `master` with no conflicts, in each of three
orders.
- #2446 also added a race stress scenario named `g`. Git merged the two
silently into a file with two `scenarioG` declarations, and JavaScript
would have kept only one, without any error. #2446 now calls its
scenario `h` and runs it outside the scenario table, so this PR's `g`
lines are untouched.
- Tested on `master` with all three merged:

| 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:
- the CI coverage hook, which only runs on push;
- in the two passes the XSS gate ran against #2434's branch rather than
a PR base (the redesign's run used `master`);
- the Go tests ran on Alpine (musl), not glibc.

## 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](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: efiten <erwin.fiten@gmail.com>
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 29, 2026
… Pushover to Postgres

Brings in 37 master commits, including the push relay (Kpa-clawbot#2447), Pushover
(Kpa-clawbot#2455), plain SMTP (Kpa-clawbot#2466), neighbour rank (Kpa-clawbot#2457), the observers rebuild
fix (Kpa-clawbot#2445) and Kpa-clawbot#2486.

Conflicts: config.example.json, docs/api-spec.md and auth_service.go keep
both sides (as n30nex's merge notes say); dbschema's observers check keeps
the Postgres branch in front of Kpa-clawbot#2445's rowid-alias check; the
release-routing test keeps musl-test; CHANGELOG keeps only unreleased
entries; notify_service.go keeps master's destinations plus the cluster
lock on evaluation, and the email claim moves to notifyChanges.claim.

users.db schema: master's v11 (push relay) and v12 (Pushover) come first,
this branch's rate_limits becomes v13, and v14 adds push_relay_state,
push_relay_pending and notification_pushover_subscriptions.

Push relay and Pushover on Postgres with several server replicas:
- Postgres migrations v11-v14 with the five SQLite triggers as plpgsql;
  instr -> strpos, typed VALUES, a qualified ON CONFLICT WHERE, integer
  booleans. The parity test also compares trigger names.
- Relay enrollment, delivery phase and the pending enrollment (with the
  Ed25519 proof seed) move from <users.db>.push-relay*.json and process
  memory into the accounts store. Writes are compare-and-set on a
  revision; replicas reload it per tick, per dispatch pass and per job.
  Old files are imported once, except an enrollment under a manual relay
  or for another public origin, which is left on disk and never prunes.
- Credentials and the seed are sealed with userManagement.encryptionKey
  (CORESCOPE_ACCOUNTS_KEY), required on Postgres; on SQLite without a key
  they are stored as before, inside users.db. Leftover plain values are
  re-sealed at startup once a key is set. users.db is set to 0600, and
  user backups blank the relay secrets.
- Queue rows are claimed with a 5-minute lease (SKIP LOCKED on Postgres);
  each queue drains under a cluster lock; advisory locks use their own
  connection pool, so lock holders cannot starve the accounts store.
  Device links and the Pushover per-user limit lock the user.
- The enrollment proof and the Pushover connect token work on any
  replica; the proof endpoint validates before any database read and is
  limited per IP; device link/unlink are limited per user.

Also fixed while integrating:
- node_reach used IS NOT 'tx', which Postgres rejects (from Kpa-clawbot#2486).
- docker/server-exec.sh did not pass five variables the server reads
  (CORESCOPE_ACCOUNTS_KEY, CORESCOPE_PUSHOVER_TOKEN,
  CORESCOPE_PUSH_RELAY_CREDENTIAL, CORESCOPE_SMTP_PASSWORD, CORESCOPE_URL);
  tests/unit/test-server-exec-env.js now checks the list.
- corescope-migrate copy-users/verify-users failed on
  notification_pushover_sent (no key); it gets a rowid on Postgres, like
  mail_events, and verify redacts credential and seed columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

observers idx rebuild: handle local indexes, triggers and views

3 participants