Skip to content

feat(db): PostgreSQL as an alternative database backend - #2396

Open
zfouts wants to merge 86 commits into
Kpa-clawbot:masterfrom
zfouts:feat/postgres-support
Open

zfouts wants to merge 86 commits into
Kpa-clawbot:masterfrom
zfouts:feat/postgres-support

Conversation

@zfouts

@zfouts zfouts commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This adds PostgreSQL as an alternative database backend for CoreScope, alongside SQLite.

  • SQLite stays the default, and nothing migrates automatically. An install that changes nothing behaves exactly as before.
  • PostgreSQL 16+ is an operator opt-in. Set db.driver / db.dsn, or DB_DRIVER / DB_DSN in the environment.
  • The same binaries, schema shape and API results run on both backends. The only intended differences:
    • /api/backup answers 501 on Postgres; use pg_dump.
    • /api/perf/sqlite answers 404 there.
  • Postgres installs can scale out. Run one ingestor and any number of server replicas, with no shared disk. Optional user accounts can live in Postgres too, so accounts work across replicas.

About the size: the four changes that also reach SQLite installs are split out as #2407, #2408, #2409 and #2410 (see Compatibility). All four have merged, and master (144937cd) is merged into this branch (e51a03dd), so those changes appear here only as master's reviewed versions. Beyond those, this is one PR so the whole thing can be tested end to end; the pieces only work together. If reviewers would rather take it in smaller steps, I'm happy to split it into a stack, roughly: the backend switch with no SQLite behaviour change → the Postgres schema, ingestor and server → the disk-free control channel and Kubernetes HA → accounts in Postgres. The commits are already grouped that way.

On #2145

@n30nex, #2145 is a serious, carefully built piece of work, and it shaped how I approached this one:

  • two-way backend switching with recovery copies, resume and abort;
  • verified conversion across every telemetry table;
  • guards so a missing database can never silently become an empty replacement;
  • validation across both backend matrices, race jobs and browser shards;
  • notes that are candid about what it doesn't claim (hop-index acceleration, a general speed advantage).

The discussion there, with @dborup and @nullrouten0, is a big part of why the problem space is so well mapped now.

This PR is a second take on the same goal, built around a few different design choices (below). I'd really value the people in #2145 reviewing and testing this one too. You know the edge cases better than anyone, and if pieces of #2145 belong in here, or this should fold into that effort, I'm glad to work it out together. The aim is simply to get the best Postgres support into CoreScope.

Design

  • Plain database/sql with portable SQL, no ORM.
    • internal/dbx registers a pgx-qmark driver that rewrites ? placeholders. Most queries are therefore written once and run unchanged on both backends.
    • Where a backend genuinely differs, the per-database SQL sits side by side at the call site (db.sqlFor(sqlite, postgres)).
  • One schema, two dialects, enforced by tests.
    • Forward-only Postgres migrations live in internal/dbschema/pgschema.
    • TestPgSchemaParity and TestSQLiteEndStateMatchesIngestor fail if the two schemas drift.
    • Every server endpoint is tested for identical results on both backends.
  • The ingestor is the only writer (bug(db): vacuumOnStartup fails with SQLITE_BUSY when ingestor + server share DB (auto_vacuum migration #919 broken in single-container topology) #1283 holds on Postgres).
    • The server connects with a read-only role and default_transaction_read_only=on.
    • At startup it refuses any role that could write, by any route: table, column, sequence and view privileges, role membership, schema ownership or CREATE, superuser-like attributes, and so on.
    • In the Docker image, the writer credential lives in its own container.
  • Disk-free on Postgres. The file queues and statistics the server and ingestor exchanged on a shared volume go through a small corescope_control schema instead. The server writes there only through a narrow, column-granted role, and the ingestor treats those rows as untrusted.
  • User accounts can move into Postgres (optional).
    • Set userManagement.dsn or DB_DSN_ACCOUNTS, and accounts move to schema corescope_users under a role of their own, which startup checks can write nothing else.
    • Background jobs take a database lock so only one replica runs them, and mail is claimed before sending so no change is mailed twice.
    • Rate limits are shared across replicas, and caches reload every 30 s.
    • Push relay and Pushover notifications (Optional mobile push for watched-node alerts through a push relay #2447, Optional Pushover delivery for watched-node alerts #2455) work across replicas too. The relay enrollment, its delivery phase and the pending enrollment live in the accounts store instead of files next to users.db, so pause, disconnect and the relay's ownership proof work whichever replica a request reaches. Each queued push is claimed by one replica, and each queue drains under a database lock. The relay credential is sealed with userManagement.encryptionKey (required on Postgres).
    • users.db remains the default.
  • Migration tooling.
    • corescope-migrate copy copies SQLite → Postgres or Postgres → SQLite in one transaction, verifies before COMMIT, and refuses a non-empty target. Measured throughput: about 36.7k rows/s into Postgres and about 61k rows/s back.
    • verify compares per-table row counts and ordered content digests.
    • copy-users / verify-users do the same for accounts.

Running it

docs/postgresql.md covers:

  • setup, and scripts/postgres-roles.sh, which creates the writer, reader, control and accounts roles;
  • Docker Compose (docker-compose.postgres.yml);
  • migrating existing data, backups and rollback;
  • a Kubernetes high-availability guide: exactly one ingestor, N servers, no shared volume, and a NetworkPolicy.

Compatibility and rollback

Testing

After merging master 144937cd (10 commits: #2366 catalogue key tier, #2492 observer comparison, #2497, #2498, #2511, #2513, #2514, #2517–#2519; merge e51a03dd, follow-up 894410db):

  • Conflicts:
  • Ported to Postgres:
  • 894410db makes the ingestor and server guards reject IS NOT <literal>, ?N and strftime.
  • Master's catalogue-key and foreign-advert store tests now run on both backends. New dual-backend tests cover the comparison and the region filter, and a new pgschema test upgrades a version-3 database that holds data.
  • Re-run locally on 894410db:
    • go test and go vet for all 17 modules with Postgres 17, and gofmt;
    • ingestor, server, migrate and dbschema also without a Postgres DSN;
    • eslint and test-all.sh.
  • E2E was not re-run locally; CI runs it on both backends.

After merging master 1c5ec2fa (37 commits, including #2447 push relay, #2455 Pushover, #2466 SMTP, #2457, #2445, #2486; merge 68b9fe34):

  • Conflicts were resolved following n30nex's merge notes; notify_service.go keeps master's destinations plus this PR's evaluation lock and mail claim.
  • Master's push relay and Pushover assumed one server process (state files, in-memory state, every replica draining the same queue). They are ported to Postgres and to several replicas, as described under Design. Both features' store tests now run on both backends, and new two-replica tests on one Postgres cover: proof answered by another replica, pause stopping a running pass, Pushover connect across replicas, stale writes conflicting, the device lock.
  • Found by the integration run and fixed: fix(reach): exclude observer TX reports from directional evidence #2486's reach query used SQLite-only IS NOT 'tx'; docker/server-exec.sh did not pass five variables the server reads (tests/unit/test-server-exec-env.js now checks the list); corescope-migrate copy-users failed on notification_pushover_sent, which has no key; verify-users did not redact the relay credential and proof seed.
  • Re-run locally on 68b9fe34: go test for all 17 modules with Postgres 17, go vet (also with -tags e2etest), gofmt, eslint, test-all.sh. E2E was not re-run locally this round; CI runs it on both backends.

After merging master 6ab97f52 (#2407's reviewed version, #2429, #2451–#2454; merge 63ebfb71):

  • All 17 Go modules pass on both backends, with vet and gofmt clean. CI runs a Postgres service for the Go and race jobs, and adds a musl test job.
  • Every Playwright E2E suite in CI's list runs against SQLite and against Postgres: 135 suites plus the slide-over repeat runs, 138/138 passing on each backend.
  • All standalone frontend suites pass (test-all.sh).
  • Fixed along the way: two pre-existing ways a server could permanently miss data, on SQLite as well as Postgres. A row committed while a server was starting up, or during a failed poll, was skipped. Both have regression tests on both backends. Comparing replicas side by side is what exposed them: in a first run, two pods restarted mid-ingest each lacked one transmission and its observations.
  • Performance:
    • Hot paths keep their SQLite form unless the shared form was measured equal. The ingest insert path stayed SQLite-original after a benchmark.
    • No overall Postgres speed advantage is claimed.

Kubernetes HA deployment

Validated on a live mesh deployment in Kubernetes, laid out as docs/postgresql.md recommends:

Component Replicas Notes
corescope-ingestor 1 The only writer. Recreate strategy, so two never overlap or fight over the MQTT client id.
corescope (servers) 5 Read-only role, RollingUpdate, behind one Service. No shared volume; emptyDir scratch only.
postgres 1 postgres:17-alpine, ClusterIP only; a NetworkPolicy admits just the CoreScope pods.
  • Existing SQLite data was moved with corescope-migrate copy (verified before COMMIT). The original SQLite file stays on its volume as the rollback copy.
  • Rolling upgrades ran with live traffic, including a schema upgrade. A server that starts before the ingestor has upgraded the schema exits with a clear message, and the kubelet retries it until the ingestor is done.
  • Data consistency across replicas. Each of the 5 server pods was queried directly through a per-pod port-forward, bypassing the Service. All five were restarted while data was still coming in, then compared:
    • packet lists for a 6-hour window, raw, grouped by hash and with expanded observations, plus a packet's detail: identical on 5/5 pods;
    • node, observer and channel sets: identical on 5/5 pods;
    • in-memory counts: identical on every pod (10,182 transmissions, 99,684 observations);
    • against PostgreSQL directly: the window total matched (1,331 transmissions), and so did the highest transmission id. Rows committed while the pods were starting were present on every pod.
  • Control channel. The ingestor's statistics stayed fresh (about 1 s old), and multibyte snapshots reached the ingestor through corescope_control. Geo-prune requests are covered by tests only, because this deployment has no API key configured.
  • Accounts in Postgres are covered by the test suites against a real PostgreSQL, not by this deployment, which runs without user accounts.

Security review

The work went through five independent security review passes (the fifth on the push relay and Pushover port, alongside a code review), plus follow-up hardening, and every accepted finding was fixed on this branch, each with a regression test. The main themes:

  • the reader role can't gain write power;
  • credential isolation between containers;
  • untrusted control-channel rows;
  • the accounts role's boundary;
  • the server's and ingestor's Postgres search path, pinned so a planted schema can't shadow CoreScope's tables;
  • secret redaction in tool output;
  • IPv6 rate-limit keys.

SECURITY.md describes the role model.

Known limitations

  • Postgres has no equivalent yet of SQLite's hop-index acceleration (observation_hops*).
  • /api/backup returns 501 on Postgres; use pg_dump. The same goes for /api/admin/users-backup with accounts in Postgres.
  • With several replicas, revoking an observer MQTT login reaches the other replicas within about 30 s.
  • With several replicas, pausing or disconnecting the push relay reaches a replica that is sending after at most the push in progress.
  • Pre-existing, not changed here: with hotStartupHours set, an older transmission that is outside memory and gains a new observation stays out of memory until restart. This happens on both backends. I can file it separately.
  • Moving between backends pauses ingest, but reads keep working. The servers keep serving the old database during the copy, and then roll over to the new one. Packets heard during the copy aren't recorded, because the ingestor subscribes at MQTT QoS 0 with a clean session. The gap lasts as long as the copy, about 9 minutes per 20M observations. There is no resumable switch like the one in feat: offer PostgreSQL alongside default SQLite with verified backend switching #2145.

zfouts and others added 30 commits November 12, 2026 18:32
The server ran migrateContentHashesAsync on its read-only analyzer handle,
so every batch failed and the server issued UPDATE/DELETE against a DB it
must never write (Kpa-clawbot#1283). The migration now runs in the ingestor as the
async migration content_hash_payload_bits_v1:

- Rows present at boot are rescanned by id; stale hashes are rewritten.
- A row whose new hash already exists is merged into that survivor: its
  observations move unless they would violate the dedup index, the
  survivor's first_seen/last_seen widen, and the duplicate is deleted
  with the same child cleanup retention uses (now one shared helper).
- Collisions are found by lookup, not by catching a constraint error, so
  the SQL also works on Postgres.

The server copy is deleted. /api/stats.hashMigrationComplete keeps its
shape and now reports that migration's _async_migrations status.
readonly_invariant_test.go now fails on any Begin or INSERT/UPDATE/DELETE
against the analyzer DB from cmd/server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
observations.observer_idx pointed at the implicit rowid of observers,
whose declared key is id TEXT. A dump-and-reload (sqlite3 .dump,
iterdump) renumbers implicit rowids and silently re-links observations
to the wrong observer, and Postgres has no rowid at all.

The ingestor now rebuilds observers once with
idx INTEGER PRIMARY KEY AUTOINCREMENT, copying every rowid into idx in
one transaction (fails closed on unknown columns or NULL ids). In SQLite
an INTEGER PRIMARY KEY is the rowid, so rowid == idx forever and older
binaries that still join on rowid keep working: upgrades and rollbacks
are both safe. AUTOINCREMENT is seeded past MAX(observations.observer_idx)
so a new observer can never inherit a deleted one's orphaned rows.

- Fresh installs create the new shape; AssertReady requires observers.idx.
- packets_v has one definition (dbschema.EnsurePacketsView).
- Every server and ingestor query, the fixture capture script and the
  test schemas use idx; guard tests fail if observers.rowid returns.
- Verified on a copy of test-fixtures/e2e-fixture.db: 499/499
  observations keep the same observer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DBConfig gains Driver ("sqlite", the default, or "postgres"; aliases
sqlite3, postgresql, pg) and DSN (the Postgres connection string), with
DB_DRIVER / DB_DSN env overrides following each binary's existing DB_PATH
precedence. Both binaries validate the pair at startup and refuse
db.driver=postgres for now, since the backend is not implemented yet.
The DSN is never logged. SQLite startup is otherwise unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New module internal/dbx registers the database/sql driver "pgx-qmark":
pgx v5.11.0's stdlib driver with every query's ? placeholders rewritten
to $1..$n (quote-, comment- and dollar-quote-aware; results cached in a
bounded map). Code keeps using plain *sql.DB and its existing SQL, so
supporting Postgres needs no call-site changes for placeholders. The
wrapper forwards every optional driver interface pgx implements.

dbxtest.OpenPostgres gives each test an isolated schema in the database
named by CORESCOPE_TEST_PG_DSN and skips when it is unset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TableHasColumn and the new TableExists ask information_schema first and
fall back to the SQLite catalogue when it does not exist. They take a
Querier, so they work inside a transaction without being told the
backend; the order matters, because a SQLite-only probe would abort a
Postgres transaction while a failed information_schema query leaves a
SQLite one usable (pinned by a test that writes after probing).
AssertReady uses TableExists instead of querying sqlite_master.

dbx.IsPostgres(db) reports whether a *sql.DB uses the Postgres driver,
for the few statements that need a per-backend form.

The modules that import dbschema now resolve dbx locally; pgx brings
golang.org/x/sync 0.10.0 -> 0.17.0 into cmd/server.

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

The production binaries are static musl, and musl gives every non-main
thread a 128 KiB stack (glibc gives 8 MiB). cgo calls run on the calling
thread's stack, and SQLite's multiSelect recurses ~850 B per UNION ALL
term, so lookupPrefixes (up to 400 terms) and sharedEightBytePrefixes (up
to 450) overflow it and SIGSEGV the whole server. Public endpoints reach
both: /api/nodes/reported at ~40+ targets, rx-coverage at ~75+ heard keys.
CI never saw it because its runners use glibc.

Root cause confirmed by symbolizing the fault to multiSelect at the
thread's stack guard page, and by measuring the thread stacks.

Every musl link now passes -Wl,-z,stack-size=8388608: musl sizes thread
stacks from PT_GNU_STACK, which zig sets (readelf: MemSiz 0x800000 on all
three binaries). It reserves address space only. make test passes it too.
TestMuslThreadStackWideUnionQueries runs both queries off the main thread
and crashes the test binary on musl without the flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DB gains a pg flag and sqlFor(sqlite, postgres), the one place a query
picks a per-backend form. Nothing sets pg yet; SQLite is unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New package dbschema/pgschema creates the end-state schema on Postgres
(16+): 25 tables, 39 indexes and packets_v, as embedded, forward-only
migrations recorded in schema_version. Apply holds a session advisory
lock on one pinned connection so two ingestors cannot race, applies each
migration in its own transaction, and refuses a server older than 16 or
a schema written by a newer binary. AssertReady is the reader's check.

Translation rules: every TEXT column is COLLATE "C" (SQLite's byte
order), INTEGER -> BIGINT, REAL -> DOUBLE PRECISION, AUTOINCREMENT ->
BIGINT GENERATED BY DEFAULT AS IDENTITY, and defaults produce
byte-identical text to SQLite's datetime('now'). Index names, partial
and expression indexes, CHECKs and FKs match SQLite. A Postgres database
never holds pre-migration data, so SQLite's one-shot and async
migrations are seeded as done.

TestPgSchemaParity boots a real SQLite store and a Postgres schema and
compares tables, columns (type class, nullability, defaults), primary
keys, foreign keys, unique constraints, indexes and the view, failing on
the exact mismatch; it caught all 7 differences seeded to check it. The
opt-in observation_hops index stays SQLite-only for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
schemaColumns asks information_schema first and falls back to PRAGMA
table_info, so the server's schema detection works on both backends.

newPostgresTestDB builds a server *DB on pgschema's end state through the
real detectSchema and prepareStatements. newDualTestDB puts the same
end-state schema on SQLite (opened through the real read-only OpenDB)
and Postgres, seeds identical rows into both, and requireSame asserts a
server method returns deeply equal results from each — proving the SQL
equivalent, not merely runnable. The SQLite schema is a dump of a freshly
booted ingestor (testdata/sqlite-endstate-schema.sql).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every statement the ingestor executes per packet or per maintenance
cycle now has a form Postgres accepts, with identical results on
SQLite:

- INSERT OR IGNORE / OR REPLACE -> ON CONFLICT DO NOTHING / DO UPDATE
  (observation_radios, observer_metrics, key_backfill_*, _migrations,
  advert evidence); MoveStaleNodes names its 16 columns instead of
  SELECT *.
- IS NOT 'tx' -> IS DISTINCT FROM; two-arg MAX in the neighbor-edge
  upsert -> a CASE that keeps SQLite's NULL semantics; untyped
  parameters are CAST; runtime datetime('now') is a Go-side value with
  byte-identical text; DO UPDATE references are table-qualified.
- PRAGMA / sqlite_master probes use dbschema's dual-backend probes.

Two hot spots keep their exact SQLite SQL and get a Postgres form chosen
once at prepare time (Store.pg): the transmissions insert (LastInsertId
vs RETURNING id) and the last_seen clamp (MAX(MIN(...)) vs an equivalent
CASE). The portable forms cost ~14% CPU on SQLite ingest; with the split
BenchmarkInsertTransmissionHotPath is within noise of base (-0.8%,
+2.0%, -0.4% over three interleaved rounds; allocs +0.5%).

TestSQLiteHotPathSQLUnchanged pins the prepared SQLite text byte for
byte; the go/ast guard fails on any SQLite-only form outside an explicit
per-function allowlist; equivalence tests compare each rewrite with the
SQLite original over NULL, '', both timestamp layouts and integers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Completes the move that fbdb584 picked up by accident: the end-state
SQLite schema now lives in internal/dbschema as dbschema.SQLiteEndState,
so the copy tool and tests in any module can create a ready SQLite
database without running the ingestor's migration history. The server's
dual-backend harness reads it from there. (fbdb584 alone does not build
the server tests; this commit restores that.)

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

The server's read path — packet lists, nodes, channels, metrics, scope
stats, the packet-store startup load and incremental ingest, reach,
scope audit, reported nodes — now runs on both backends with identical
results, proven by 138 dual-backend tests that seed the same rows into
SQLite and Postgres and require deeply equal output.

- Shared helpers render epoch and text timestamps; SQLite strings are
  byte-for-byte unchanged, Postgres uses to_char/date_bin with a guard
  so malformed text yields NULL as on SQLite.
- GROUP_CONCAT -> string_agg, json_each -> jsonb_array_elements_text
  (guarded by IS JSON ARRAY), INSTR -> strpos, bare-column MAX ->
  DISTINCT ON, IS NOT 'tx' -> IS DISTINCT FROM, untyped params CAST,
  sqlite_master probes -> dbschema.TableExists.
- Case-insensitive LIKE is explicit (LOWER(..) with the input lowered in
  Go); NULL ordering is explicit and orders end in a key, so ties no
  longer depend on a planner. SQLite planner hints (+col, CROSS JOIN)
  are kept for SQLite only.
- The file queues shared with the ingestor are anchored by queueAnchor,
  which is the database path on SQLite (unchanged).

SQLite: QueryGroupedPackets page 1 48.8 -> 36.2 ms, LoadChunked within
noise (+3%, ranges overlap). Only previously planner-dependent tie
orders changed. buildPacketWhere had no callers and is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With db.driver=postgres the server opens db.dsn through the pgx-qmark
driver and keeps the Kpa-clawbot#1283 invariant (the server never writes):

- every connection starts with default_transaction_read_only=on, added
  to the DSN by parsing it (URL and key=value forms);
- startup refuses a role holding INSERT/UPDATE/DELETE/TRUNCATE on any
  table in its schema (has_table_privilege, so ownership, superuser and
  inherited grants count) and prints the GRANTs for a read-only role;
- pgschema.AssertReady must pass; the DSN/password never reaches logs
  or errors.

/api/perf reports engine "sqlite" or "postgres"; on Postgres the size
comes from pg_database_size and row counts from n_live_tup estimates
(never COUNT(*) on tens of millions of rows), cached 30 s.
/api/perf/sqlite answers 404 and /api/backup 501 (use pg_dump) on
Postgres. The file queues shared with the ingestor stay beside the
configured dbPath. A source test pins the Postgres open to OpenPostgresDB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The perf page reads the engine reported by /api/perf: on PostgreSQL it
labels the panel "Database (PostgreSQL)", hides the SQLite-only WAL,
freelist and page rows, marks row counts as estimates and skips the
/api/perf/sqlite panel. SQLite output is unchanged apart from the
"Database (SQLite)" header. The rendering decision is a pure function
(perfDbRows) with unit tests for both engines and older servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
corescope-migrate gains two subcommands (the legacy -db mode is
unchanged):

  corescope-migrate copy   -from <db> -to <db> [-batch 5000]
  corescope-migrate verify -a <db> -b <db>

where <db> is sqlite:<path> or a postgres:// URL.

copy reads a fully migrated source (AssertReady, every async migration
done) inside one read-only snapshot, creates the target schema if
absent, refuses a non-empty target, and copies every table in FK order
with explicit column lists and every primary key preserved. Into
Postgres it streams COPY inside one transaction and verifies before
COMMIT, so a failure leaves the target empty; into SQLite it builds
<path>.partial and renames it only after verification. Values are
normalised to the target column's type class, and a SQLite value that
cannot be represented (text in an INTEGER column) fails naming the
table, primary key and column instead of being coerced. Identity
sequences / sqlite_sequence are set to MAX(id) afterwards.

verify streams both sides ordered by primary key and compares a
canonical per-value encoding, reporting rows and match per table and the
first differing key. Passwords are redacted in all output, with a
scrubbing writer as a second line of defence.

Measured: SQLite -> Postgres ~36.7k rows/s (the server's own INSERT
limit for this schema; ~9 min per 20M observations), Postgres ->
SQLite ~61k rows/s. Tested round trip SQLite -> Postgres -> SQLite with
identical digests, plus every refusal path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
corescope-decrypt's -db accepts a SQLite path (as before) or a
postgres:// URL, opened through the pgx-qmark driver with
default_transaction_read_only=on; the password never appears in errors.

Fixes a pre-existing bug on both backends: observers were joined with
o.id = CAST(obs.observer_idx AS TEXT), comparing the text observer id
with the integer key, so observer names were always empty. The join is
now o.idx = obs.observer_idx. TestObserverNamesResolved fails on the old
join; TestPostgresMatchesSQLite requires identical output from both
backends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- scripts/postgres-roles.sh: idempotent provisioning of a writer role
  (owns the database; the ingestor) and a read-only reader role (the
  server): SELECT on all tables plus default privileges on tables the
  writer creates later, no CREATE on public, default_transaction_read_only
  on; refuses superuser names, invalid identifiers and missing passwords,
  and never echoes a password. Proven against Postgres 17: reader SELECT
  works, INSERT/CREATE are denied, reruns are no-ops.
- docker-compose.postgres.yml: Postgres 17 service (not published to the
  host), a one-shot init running the roles script, passwords from .env.
- The image runs server and ingestor in one container, so the entrypoint
  and supervisord give each its own DSN: DB_DSN_INGESTOR (writer) and
  DB_DSN_SERVER (reader), both defaulting to DB_DSN; the server process
  never sees the writer DSN. Existing SQLite deployments are unchanged.
- CI: a Postgres service and CORESCOPE_TEST_PG_DSN on go-test and
  race-test so the Postgres tests run; a new musl-test job (Alpine, the
  production stack-size link flag) gating the build; every E2E shard
  runs on sqlite and postgres, the latter copying the prepared fixture
  into Postgres and serving it through the read-only role.

actionlint: no new findings versus master (18 pre-existing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
redactErr also scrubs a password= query parameter (raw or URL-escaped)
and password=<value> key=value fragments, not just the URL userinfo.
Help text and README use password-less URLs with PGPASSWORD/~/.pgpass,
since a password on the command line is visible in ps. From the
security review of the Postgres support.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With db.driver=postgres the ingestor opens db.dsn (OpenPostgresStore),
applies pgschema, and ingests through the same code as on SQLite.

- One writer connection on Postgres too: ids then commit in increasing
  order, which the server's "id > last seen" tailing relies on.
- SQLite-only machinery is skipped: applySchema and its migrations,
  legacy backfills, WAL checkpoint, incremental vacuum, planner stats
  (autovacuum handles maintenance; logged once). retention.hopIndexDays
  > 0 logs a warning and is treated as 0 — the hop index is SQLite-only.
- Guard: on an empty Postgres the ingestor refuses to start while the
  SQLite file at dbPath still holds transmissions, and says how to copy
  it or move it aside. No config switch; the DSN never appears in errors.
- The file queues shared with the server stay beside dbPath.
- observations.score is DOUBLE PRECISION on Postgres: the ingestor
  writes float64 scores, SQLite keeps fractions despite its INTEGER
  declaration, and pgx silently truncates a float bound to BIGINT. The
  parity test has exactly this one documented type exception, pinned.

TestIngestSameOnBothBackends drives both backends through handleMessage
with real packets, the boot backfills, key backfill, neighbor edges,
every prune and the stale-node/observer moves, then compares every
column of every table (21 with rows), allowing only wall-clock columns
to differ within the test's run time. TestSQLiteEndStateMatchesIngestor
keeps dbschema.SQLiteEndState equal to a real OpenStore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- copy -allow-pending-migrations accepts a SQLite source that a running
  ingestor never finished migrating (CI's fixture, prepared with the
  legacy -db mode): missing/pending async migrations, missing tables
  (copied as empty) and missing nullable columns (NULL) are accepted
  with a WARNING that Postgres will not run those backfills; a missing
  NOT NULL column still fails. Unfinished _async_migrations rows are not
  copied, so Postgres's seeded "done" rows stand. Without the flag the
  refusal names it as the alternative to starting the ingestor.
- From the security review: SQLite targets use Lstat throughout (a
  symlink, even dangling, counts as existing), create <path>.partial
  with O_EXCL|O_NOFOLLOW, and publish with link+remove so an existing
  <path> is never replaced; an existing target path is always refused;
  printed commands are shell-quoted. A Postgres target schema holding
  tables but no schema_version (someone else's database) is refused
  before anything is created. Usage text shows only password-less URLs.
- A refused copy no longer leaves a .partial that blocks the rerun.
- Fractional observations.score round-trips SQLite -> Postgres -> SQLite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
0c3e97f calls usageFor (the password-safe usage text) but did not
include dbref.go, where it is defined, so that commit alone does not
build cmd/migrate. This adds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the security review of the Postgres support:

- The startup write-privilege refusal now also covers views, foreign
  tables and matviews (packets_v is auto-updatable), column-level
  INSERT/UPDATE grants, PG17's MAINTAIN, and every role reachable
  through membership — inherited or not, since SET ROLE reaches both —
  each checked as that role; the error names the role a write path
  comes from. SELECT through a group role still starts.
- Server sessions get statement_timeout (db.statementTimeoutSec,
  default 120 s, 0 disables, negative rejected) and
  idle_in_transaction_session_timeout 60 s alongside the forced
  read-only default, so unauthenticated API requests cannot pin the
  pool. Effective values are read back after connecting.
- Forced DSN keys match case-insensitively in both DSN forms, and an
  options= value that tries to set one is an error (the DSN is never
  quoted).
- /api/perf Postgres stats no longer hold a mutex across queries: one
  refresh at a time with a 5 s timeout, others get the last good value
  flagged "stale"; failures are cached 5 s.
- dbx refuses a connection with standard_conforming_strings off (Rebind
  relies on it) and discards a pooled one whose session turned it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ingestor writes observations.score as a float (MQTT "score", e.g.
0.75), but the server scanned it into sql.NullInt64. A fractional score
failed the row's Scan and the loaders dropped the row silently, so those
observations never reached the API — on SQLite as well as Postgres.

All five scan sites (Load, loadChunk, LoadChunked, IngestNewFromDB,
IngestNewObservations) and scanPacketRow now read NullFloat64 and the
fields are *float64. Integral scores still encode as 3, so the API shape
is unchanged. TestFractionalScoreSurvivesLoaders and
TestFractionalScoreIngestNewObservations (both backends) fail on the old
code with the 0.75 observation missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the security review: in the one-container image the server and
ingestor ran as the same user (root by default), so a compromised server
could read the ingestor's writer DSN from /proc/<pid>/environ or, as
root, from supervisord's /proc/1/environ — defeating the read-only role.

On Postgres the entrypoint now:
- runs the server as its own unprivileged user corescope-server (uid
  SERVER_RUN_AS_UID, default 1001, from the container env only) whose
  only group is corescope-share; refuses if that uid is 0 or equals the
  ingestor's. Verified: the server gets EACCES on /proc/1/environ and on
  the ingestor's environ (ingestor root or uid 1000).
- moves everything the server writes (users.db, backups/, prune-requests/,
  the multibyte snapshot) into /app/data/shared (setgid, 2770) and points
  both processes there; /app/data itself stays unwritable to the server,
  so it cannot create .env. A legacy users.db is moved once.
- makes the resolved config.json group-writable for geo-filter saves
  (owner kept; refused if a symlink leaving /app/data or not a regular
  file) and still refuses a config.json carrying a DSN; warns if
  userManagement.dbPath points outside shared/.
SQLite mode is unchanged.

scripts/postgres-roles.sh: refuses a password in PG_ADMIN_URL (use
PGPASSWORD/.pgpass — argv shows in ps); refuses to adopt a database or
role it did not create unless CORESCOPE_ADOPT=1; REVOKE ALL ON DATABASE
FROM PUBLIC with CONNECT (+TEMP for the writer) granted back; revokes
the reader's role memberships; reader CONNECTION LIMIT 32,
statement_timeout 120s, idle_in_transaction_session_timeout 60s.
Compose and CI pass passwords via PGPASSWORD, never in URLs on argv.

Proofs (containers with supervisord and stub binaries; cs-pg for the
roles script) and docker/test-select-service-user.sh (116/116) pass;
actionlint has no new findings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In the image on Postgres, the ingestor's DB_PATH now points into
/app/data/shared, where it only anchors the file queues it shares with
the server. The empty-target guard looked for leftover SQLite data at
DB_PATH, so it would no longer see an operator's /app/data/meshcore.db
and an empty PostgreSQL would start over unmigrated data.

The guard also checks CORESCOPE_SQLITE_GUARD_PATH when set, and the
entrypoint sets it on Postgres to the operator's SQLite path (DB_PATH,
default /app/data/meshcore.db). TestEmptyPostgresGuardChecksExtraPath
reproduces the image's layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The server and ingestor exchange prune requests/results and the
multibyte snapshot through files in a shared directory. Writers created
a predictable <name>.tmp with os.WriteFile, which follows symlinks: with
the server now a separate unprivileged user, a compromised server could
plant <name>.tmp -> /some/file and have a root ingestor overwrite it.

prunequeue and mbcapqueue now write through os.CreateTemp (random name,
O_EXCL) + Sync + Rename, setting 0644 explicitly so the other process
can read; rename replaces a symlink at the destination rather than
writing through it. Reads Lstat first, accept only regular files,
re-check the opened handle and cap the size at 16 MiB (a 100k-pubkey
request is ~7-10 MiB); listings and existence checks skip non-regular
entries. Tests plant symlinks at the old temp name and the final name
and assert their targets are untouched.

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

On Postgres in Docker the server runs as an unprivileged user that may
write config.json itself but not /app/data (so it cannot plant .env).
SaveGeoFilter's temp-file-and-rename needs directory write, so saves
failed there.

The atomic path is unchanged where it works, now with an unpredictable
temp name (CreateTemp), the original mode kept, and fsync before rename.
Only on a permission error creating the temp file does it fall back:
first an atomic backup of the current config.json into the shared queue
directory (config.json.bak, 0600) — if that fails, nothing is touched —
then an in-place rewrite (O_WRONLY|O_TRUNC, never creating, regular
files only) with fsync, logging the backup path and that the save was
not atomic. Tested as root and as uid 1000 against a read-only
directory.

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

The image did not build: the server and ingestor stages did not copy
internal/dbx (now required through the Postgres support), and the
decrypt stage copied neither dbx nor dbschema. The image also lacked
corescope-migrate, which the Postgres docs tell operators to run for
copy/verify — it now has its own build stage (same static musl flags,
including the thread stack size) and ships in /app.

tests/unit/test-dockerfile-modules.js checks every build stage's
COPY internal/<m>/ list against its cmd's transitive go.mod replaces,
so a missing module fails a unit test instead of the image build (it
reports 5 failures on the previous Dockerfile).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- docs/postgresql.md (new): when to choose it, requirements, the two
  roles and why the server is read-only, Compose and manual setup, the
  Docker image's isolation on Postgres (separate server user,
  /app/data/shared, CORESCOPE_SQLITE_GUARD_PATH), moving data with
  corescope-migrate copy/verify (also shipped in the image), switching
  back, pg_dump/pg_restore backups, what stays SQLite-only, monitoring,
  and every startup refusal with its fix.
- Operator docs made backend-aware: README, DEPLOY.md, deployment,
  getting started, configuration (db.driver, db.dsn,
  db.statementTimeoutSec, DB_DRIVER/DB_DSN, DB_DSN_INGESTOR/SERVER),
  database (SQLite-only parts marked), accounts (users.db stays SQLite),
  geo-filter help page, config.example.json.
- API: /api/perf engine, /api/perf/sqlite (404) and /api/backup (501) on
  Postgres in docs/api-spec.md and the OpenAPI descriptions.
- SECURITY.md: database credentials and roles; threat model updated.
- cmd/migrate/README.md (new) and cmd/ingestor/README.md (stale
  Node.js-era statements replaced).
- AGENTS.md / MIGRATIONS.md: the two-backend architecture, the
  portable-SQL rule and its per-backend exceptions, the dual-schema rule
  enforced by TestPgSchemaParity, Postgres test setup, the read-only
  enforcement and single writer connection on Postgres, file-queue and
  Dockerfile-stage rules, the musl stack-size rule.
- CHANGELOG [Unreleased]: everything on this branch.

Examples never put a password in a URL passed on a command line
(PGPASSWORD / ~/.pgpass); links checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the second security review. The server's startup read-only check
now also:
- walks role membership from session_user as well as current_user (a
  role= setting can make current_user lesser than the session user);
- refuses any reachable role with SUPERUSER, CREATEROLE or BYPASSRLS;
- counts the TRIGGER privilege as write power (next to MAINTAIN, PG17+);
- refuses ownership of, or CREATE on, any schema in current_schemas(true)
  other than pg_catalog — planted objects there could run as the writer.
Findings are listed together (up to 8) with the GRANT recipe. Every
password form in a DSN (userinfo, password= query parameter in any case,
keyword form) is redacted from connect errors. Each case has a Postgres
test.

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

zfouts commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@nullrouten0 agreed on the split. The four changes that reach SQLite installs are now their own PRs, each cut from current master and passing go vet and go test on all modules:

  1. fix(build): pin musl thread stacks at 8 MiB and check the artifacts #2410: musl thread stacks (8ee9bd77). Urgent: I reproduced the crash on master's own code. Under musl without the link flag, master's existing TestLookupPrefixesManyKeys SIGSEGVs in cgo. A repro against the published image would still be welcome.
  2. refactor(schema): give observers an explicit idx primary key #2407: observers.idx primary key (9daef32d). Your upgrade-then-rollback run on a real database copy would be the most valuable test here.
  3. fix(server): never lose rows committed during startup or a failed poll #2408: startup and failed-poll data loss (21d1df86). The test now seeds the ingestor's DDL rather than the Postgres branch's schema helpers, and it is red against master's store and poller and green with the fix.
  4. fix(#1856): run the content-hash migration in the ingestor #2409: content-hash migration in the ingestor (82d538b7 plus 3716afa9 from my earlier reply). One conflict with fix(store): release evicted packet references from secondary indexes #2327 was resolved by keeping the delete of the server copy, along with fix(store): release evicted packet references from secondary indexes #2327's eviction test for it.

The PR description's "Compatibility and rollback" section now lists all four. Once they land I'll rebase this PR onto them.

Brings in v3.18.0 (repeater info and claims, Kpa-clawbot#2415-Kpa-clawbot#2417).

Both sides added users schema v9. Upstream's (repeater_claims,
repeater_info) shipped in v3.18.0, so it keeps v9 and this branch's
rate_limits moves to v10, on SQLite and Postgres alike. The Postgres
account schema gains the repeater tables as its v9, ClaimRepeater uses
ON CONFLICT DO NOTHING instead of SQLite-only INSERT OR IGNORE, and the
repeater store tests run on both backends. RepeaterKnown joins the
server's SQLite/Postgres query parity test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
efiten pushed a commit that referenced this pull request Nov 17, 2026
#2408)

## Summary

Two pre-existing ways a running server **permanently** missed data. The
database was correct; the server's in-memory store was not, and stayed
wrong until the next restart.

Found while comparing several server replicas side by side in #2396: two
replicas that restarted mid-ingest each lacked one transmission and its
12 observations. Split out of #2396 at review's request, because it
affects every SQLite install.

## The bugs

1. **Startup window.** The poller took its starting cursors from a fresh
`MAX(id)` *after* the startup load finished. A row committed between the
load's last chunk snapshot and that query ended up in neither the store
nor any later poll. Its later observations were then dropped as orphans.
2. **Failed poll.** A failed observation read still advanced the cursor
to its upper bound, skipping up to 500 observations for good.

## The fix

- `NewPacketStore` records the transmission and observation high-water
marks **before** the load, as the advert-evidence and rewrite feeds
already did.
  - The loaded max transmission id stays as a floor.
- The loaded max observation id no longer is one: a chunk-1 transmission
can gain an observation whose id is *below* one that chunk 2 loaded.
  - Rows read twice are deduplicated and broadcast at most once.
- A failed read keeps the cursor and retries on the next tick, logging
once per failure streak.
- Comments and a test pin why an observation of a transmission whose
chunk has not merged yet cannot be skipped: the poller's evidence
refresh waits on that chunk's lock.

## Performance

- **Startup:** two extra indexed `MAX(id)` queries, which are
primary-key lookups.
- **Poll loop:** unchanged complexity. The only new per-tick work is a
dedupe check on rows read twice, a map lookup by id (O(1)). Re-reads
happen only for rows in the startup window, which is bounded by what was
committed during the load, and on a retry after a failed read.

## Testing

`cmd/server/startup_poll_gap_test.go` seeds the ingestor's own DDL plus
`dbschema.Apply`:

| Test | What it pins |
|------|--------------|
| `TestStartupLoadPollerGap_SQLite` | A transmission and observations
committed between the load's snapshot and the poller's start reach the
store |
| `TestStartupLoadPollerGapMultiChunk_SQLite` | Same, across 3 chunks,
including an observation id below the max loaded one |
| `TestStartupObsDuringChunkMerge_SQLite` | An observation of a
transmission whose chunk has not merged yet is not skipped |
| `TestPollerRetriesFailedRead_SQLite` | A failed observation read does
not advance the cursor |

**Red/green:** against master's `store.go`, `websocket.go`,
`chunked_load.go` and `db.go`, the first, second and fourth tests fail
with the rows missing, e.g.:

```
tx 3, committed between the load's snapshot and the poller's cursor init, is missing from the store (lost forever)
obs 3, committed while the observation read failed, never reached the store: the cursor passed it
```

The third depends on test hooks this change adds, so it cannot run
against the old code. `go vet` and `go test` pass on all modules, with
gofmt clean.

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


---

## Merge order

These four PRs were split out of #2396 and are **independent — they can
merge in any order.** Verified: every pair is conflict-free, and all
four merged together pass `go vet`, `go test ./...` (all 16 modules) and
`sh test-all.sh`.

Recommended **priority** (not a dependency):

1. **#2410** — musl 8 MiB thread stacks. A public, unauthenticated GET
can SIGSEGV the whole server on the shipped image, so merge this first.
2. **#2408** — never lose rows during startup / a failed poll.
3. **#2407** — explicit `observers.idx` primary key.
4. **#2409** — content-hash migration moved into the ingestor.

After these land, #2396 (Postgres) will be rebased onto master.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Resolves the add/add conflict in cmd/server/startup_poll_gap_test.go,
which Kpa-clawbot#2408 brought to master from this branch: keep this branch's
version. Master's copy is the pre-split one (hand-written SQLite schema,
observers addressed by rowid); this branch's is the same tests on the
shared dbschema.SQLiteEndState, observers by their explicit idx key
(Kpa-clawbot#2407), plus the _Postgres variants. Master's copy has no logic of its
own beyond that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
efiten pushed a commit that referenced this pull request Nov 18, 2026
## Summary

Fixes #1856. The content-hash migration from #787 has done nothing since
#1283. It ran in the server on the read-only analyzer handle, so every
batch failed. Before #1958 it also reported `hashMigrationComplete:
true` anyway. It also meant the server issued `UPDATE` and `DELETE`
against a database it must never write.

The migration now runs in the ingestor as the async migration
`content_hash_payload_bits_v1`. Split out of #2396 at review's request.

## Who is affected

Only installs holding transmissions from **before #787 (April 18)** that
did not run a server between #787 and #1283 (April 18 to May 18), the
only month the old server-side pass could commit. `retention.packetDays`
defaults to keep-forever, so long-lived installs can qualify. For
everyone else this is a one-time scan that changes nothing.

## What changes

- Rows present at boot are rescanned by id in batches of 5000, read
outside the writer lock. Stale rows commit 250 per transaction (the
retention bound), so ingest waits for one chunk at most, not a whole
batch.
- After each scan batch that changed rows, a progress line is logged.
- A stale hash is rewritten in place.
- A row whose new hash already exists is **merged** into that survivor:
- its observations move, except any that would violate the dedup index;
  - the survivor's `first_seen` and `last_seen` widen to cover both;
- the duplicate is deleted with the same child cleanup retention uses
(now one shared helper).
- Collisions are found by lookup, not by catching a constraint error.
- The server copy is deleted. `/api/stats.hashMigrationComplete` keeps
its shape and now reports the ingestor's `_async_migrations` status.
- `readonly_invariant_test.go` now fails on any `Begin` or
`INSERT`/`UPDATE`/`DELETE` against the analyzer DB from `cmd/server`.

## Known limitation: a running server does not follow the pass

A server that loaded these rows before the pass keeps the old hashes,
the merged duplicates, and survivors without their moved observations
until it restarts. That's deliberate:
- `tx_rewrite_feed` cannot carry a merge. Its rows cascade away with the
deleted duplicate, and the server's tail refreshes only `decoded_json`
and `scope_name`.
- Removing a transmission from every in-memory index is hot-path code
that a one-time pass over old rows does not justify.

Instead, when the pass changed anything, its summary log line tells the
operator to restart servers. The reasoning is recorded at the top of
`cmd/ingestor/hash_migrate.go`. (Raised by a reviewer in #2396.)

## Testing

- `cmd/ingestor/hash_migrate_test.go`: in-place rewrite; stale rows of
one scan batch commit in write-sized chunks
(`TestMigrateContentHashesCommitsInWriteChunks`); merge of a colliding
pair (observation move, dedup-index conflicts, span widening, child
cleanup); a stale pair split across batches; no-op; stops on cancel;
reports a write failure; scheduled on open; and
`TestContentHashMigrationSummary` (the restart hint, and silence when
nothing changed).
- `cmd/server/hash_migration_status_test.go`: `hashMigrationComplete`
follows the ingestor's migration row.
- `cmd/server/readonly_invariant_test.go`: no write path to the analyzer
DB from the server.
- Lock hold, measured on 100k stale transmissions (half merging, 5
observations each) with a concurrent writer probing the lock:

  | write batch | hold p50 | hold max | probe max wait | total |
  |---|---|---|---|---|
  | 5000 (before) | 1269 ms | 1356 ms | 1351 ms | 25.3 s |
  | 250 (now) | 63 ms | 108 ms | 158 ms | 27.5 s |

The same run at 10× the size (1M stale transmissions, 5M observations):

  | write batch | hold p50 | hold max | probe max wait | total |
  |---|---|---|---|---|
  | 5000 (before) | 1344 ms | 1808 ms | 1802 ms | 4 m 33 s |
  | 250 (now) | 66 ms | 132 ms | 199 ms | 4 m 38 s |
- Removed `cmd/server/hash_migrate_test.go` and
`hash_migrate_eviction_test.go` (#2327) along with the server code they
covered.
- `go vet` and `go test` pass on all modules, with gofmt clean.

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


---

## Merge order

These four PRs were split out of #2396 and are **independent — they can
merge in any order.** Verified: every pair is conflict-free, and all
four merged together pass `go vet`, `go test ./...` (all 16 modules) and
`sh test-all.sh`.

Suggested order, none of it urgent:

1. **#2408** — never lose rows during startup / a failed poll.
2. **#2407** — explicit `observers.idx` primary key.
3. **#2409** — content-hash migration moved into the ingestor.
4. **#2410** — pin musl thread stacks at 8 MiB. Released images are not
affected (zig already links them with 8 MiB thread stacks); it fixes
native Alpine builds.

After these land, #2396 (Postgres) will be rebased onto master.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
efiten added a commit that referenced this pull request Nov 18, 2026
…2410)

## Summary

Pins musl thread stacks at 8 MiB on every link, and fixes a crash in
**native Alpine builds** (`make build`, `make test`, or `go test` on an
Alpine host).

**The released images are not affected.** An earlier version of this
description said public endpoints could crash the shipped image. That
was wrong, and review caught it: see "Who is affected".

## Root cause

- musl sizes every non-main thread's stack from the ELF `PT_GNU_STACK`
size, with a floor of 128 KiB and a cap of 8 MiB (glibc defaults to 8
MiB).
- cgo calls run on the calling thread's stack, and SQLite's
`multiSelect` recurses about 850 bytes per `UNION ALL` term.
- `lookupPrefixes` (up to 400 terms) and `sharedEightBytePrefixes` (up
to 450 terms) overflow a 128 KiB stack and SIGSEGV the whole process.

## Who is affected

| Link | `PT_GNU_STACK` without the flag | Thread stack | Wide-UNION
tests |
|---|---|---|---|
| Alpine gcc + GNU ld (`make build` / `make test` / `go test` on Alpine)
| `0` | 128 KiB | **SIGSEGV** |
| zig 0.16.0, x86_64-linux-musl (Dockerfile, `crossbuild`, release job)
| `0x1000000` (16 MiB) | 8 MiB | pass 3/3 |
| zig 0.16.0, aarch64-linux-musl | `0x1000000` (16 MiB) | 8 MiB | pass
3/3, run on an arm64 node |

So for the released images the flag pins a value that zig's default
already provides. It stops being a property of a linker default, and a
build check now fails if it is lost. For native Alpine links it is the
fix: with the flag those tests pass.

Control: a zig arm64 link with `-Wl,-z,stack-size=131072` gets 128 KiB
threads and the same tests SIGSEGV in cgo on the arm64 node.

## Fix

- Every musl link passes `-Wl,-z,stack-size=8388608`: the `Dockerfile`,
the `Makefile` (`build` and `test` on Linux, and `crossbuild`) and the
release job in `deploy.yml`.
- This reserves address space only. Memory is committed as pages are
touched.
- **The artifacts are checked.** The Dockerfile's builder stage and the
release job's "Verify release binaries" step read `PT_GNU_STACK` with
`readelf` and fail unless it is exactly 8 MiB. Verified: the builder
stage passes for `linux/amd64` and `linux/arm64`, and fails with
`--build-arg STACK_LDFLAG=` (`/corescope-server: PT_GNU_STACK is not 8
MiB`, memsz `0x1000000`).

## Testing

- `TestMuslThreadStackWideUnionQueries`
(`cmd/server/musl_thread_stack_linux_test.go`, Linux only) runs both
queries off the main thread and asserts exact results, so a failed chunk
cannot pass as "nothing matched". Under `golang:1.27-alpine` with gcc:
SIGSEGV without the flag, pass with it. On CI's glibc runners it passes
either way, which is why the artifact checks above exist.
- `tests/unit/test-issue-1956-release-routing.js`: the release verify
step must check both binaries, and a `0x000000` or `0x1000000` header
must fail the release.
- `tests/unit/test-dockerfile-buildplatform.js`: all three `go build`
lines carry `STACK_LDFLAG`, and the `readelf` check covers all three
binaries.
- `sh test-all.sh` passes. `go vet` passes for `cmd/server` on Linux
with gofmt clean.
- Not verified: a Windows `go vet`. The fix there is the
`_linux_test.go` file name; no Windows machine was available to run it.

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

---

## Merge order

These four PRs were split out of #2396 and are **independent — they can
merge in any order.** Verified: every pair is conflict-free, and all
four merged together pass `go vet`, `go test ./...` (all 16 modules) and
`sh test-all.sh`. (That combined run predates the review fixes on #2409
and #2410.)

Suggested order, none of it urgent:

1. **#2408** — never lose rows during startup / a failed poll.
2. **#2407** — explicit `observers.idx` primary key.
3. **#2409** — content-hash migration moved into the ingestor.
4. **#2410** — pin musl thread stacks at 8 MiB. Released images are not
affected; it fixes native Alpine builds.

After these land, #2396 (Postgres) will be rebased onto master.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: efiten <erwin.fiten@gmail.com>
Brings in Kpa-clawbot#2409 (content-hash migration in the ingestor) and Kpa-clawbot#2410
(musl thread-stack pinning), both split out of this branch at review,
plus Kpa-clawbot#2426, Kpa-clawbot#2423, Kpa-clawbot#2431, Kpa-clawbot#2432, Kpa-clawbot#2433 and Kpa-clawbot#2435.

Conflicts:
- cmd/ingestor/hash_migrate.go, hash_migrate_test.go (add/add): take
  master's reviewed versions. They differ from this branch's only by the
  review fixes (stale rows committed 250 per transaction instead of a
  whole scan batch, progress logging); the SQL is identical and master's
  tests are a superset.
- cmd/ingestor/db.go: master's schedule call (write-batch argument,
  updated PREFLIGHT reason) inside this branch's
  scheduleSQLiteAsyncMigrations on s.db; the evidence-status restore
  stays in loadAdvertEvidenceStatus.
- Dockerfile, Makefile: master's Kpa-clawbot#2410 comments, HOST_TEST_LDFLAGS and
  readelf check; the check also covers /corescope-migrate, which this
  branch builds with the same flag.
- .github/workflows/deploy.yml: keep both new jobs, musl-test (this
  branch) and server-race (master), in the diagram, build-and-publish's
  needs and its gate. The server-race shards get the PostgreSQL service
  and CORESCOPE_TEST_PG_DSN like every Go test job here, so the Postgres
  tests keep running under -race.
- tests/unit/test-issue-1956-release-routing.js: both jobs in the list;
  master's wording for the stack-flag comment.

Duplicates that merged without a textual conflict:
- cmd/server/musl_thread_stack_test.go removed: master's
  musl_thread_stack_linux_test.go is its reviewed successor (same test,
  exact assertions, linux build tag); both declared offMainThread.
- cmd/server/readonly_invariant_test.go: master appended its copy of the
  analyzer-write invariant block from Kpa-clawbot#2409; this branch's copy is the
  same block plus the Postgres control-pool parts, so this branch's file
  is kept unchanged.
- tests/unit/test-dockerfile-buildplatform.js: expects the fourth (migrate)
  build and checks it with readelf.

Verified: go vet and go test for every module against PostgreSQL 17
(CORESCOPE_TEST_PG_DSN set), gofmt clean, test-all.sh, npm run lint.

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

zfouts commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master into this branch to clear the conflicts (commit fc888355). It brings in #2409 and #2410, which were split out of this PR, plus #2426, #2423, #2431, #2432, #2433 and #2435.

  1. Hash migration (cmd/ingestor/hash_migrate.go and its test): took master's reviewed versions. The SQL is unchanged; master adds 250-row write transactions and progress logging, and its tests are a superset.
  2. cmd/ingestor/db.go: master's schedule call now sits inside this branch's scheduleSQLiteAsyncMigrations.
  3. Dockerfile / Makefile: master's fix(build): pin musl thread stacks at 8 MiB and check the artifacts #2410 version. Its readelf stack check now also covers /corescope-migrate.
  4. CI: both new required jobs are kept, musl-test from here and server-race from master. The server race shards also get the PostgreSQL service, so the Postgres tests still run under -race.
  5. Two duplicates git merged silently: musl_thread_stack_test.go was removed, because master's musl_thread_stack_linux_test.go replaces it. readonly_invariant_test.go keeps this branch's version, which is master's block plus the control-pool checks.

Verified locally: go vet and go test for every module against PostgreSQL 17 with CORESCOPE_TEST_PG_DSN set, plus gofmt, test-all.sh and lint.

efiten pushed a commit that referenced this pull request Nov 21, 2026
## Summary

`observations.observer_idx` points at the **implicit rowid** of
`observers`, whose declared key is `id TEXT`. Implicit rowids are not
stable:

- a dump-and-reload (`sqlite3 .dump`, `iterdump`) renumbers them, which
silently re-links observations to the wrong observer;
- PostgreSQL has no rowid at all.

This change makes the key explicit. Split out of #2396 at review's
request, so SQLite installs get it independently of the Postgres work.

## What changes

- **One-time rebuild, in the ingestor.** On first start, `observers` is
rebuilt as `idx INTEGER PRIMARY KEY AUTOINCREMENT`, copying every rowid
into `idx` in one transaction. It fails closed on unknown columns or
NULL ids.
- **Rollback-safe.** In SQLite an `INTEGER PRIMARY KEY` *is* the rowid,
so `rowid == idx` forever. Older binaries that still join on
`observers.rowid` keep working, so both upgrade and rollback are safe.
- **No inherited orphans.** `AUTOINCREMENT` is seeded past
`MAX(observations.observer_idx)`, so a new observer can never inherit a
deleted observer's leftover rows.
- Fresh installs create the new shape directly, and `AssertReady`
requires `observers.idx` as the primary key (a plain column named `idx`
does not pass).
- **Observer writes update first.** With `AUTOINCREMENT`, SQLite
advances `sqlite_sequence` for every INSERT it attempts, even one `ON
CONFLICT` turns into an update. The per-packet observer upsert and the
clock-skew upsert now run an `UPDATE` and fall back to the unchanged
`INSERT ... ON CONFLICT` only for a new observer. So the sequence moves
only when an observer is added, and the next new observer gets `max(idx)
+ 1`.
- `packets_v` now has a single definition
(`dbschema.EnsurePacketsView`).
- Every server and ingestor query, the fixture capture script and the
test schemas use `idx`. Guard tests fail if `observers.rowid` comes
back.

## Operator impact

Every SQLite install gets this on its next ingestor start, with no
config change. The rebuild is one transaction over `observers`, which
holds one row per observer (typically hundreds), so it's quick.

**When the rebuild refuses.** It refuses rather than lose data in two
cases, and then the ingestor stops on every start until the cause is
fixed:

- `observers` has a column CoreScope doesn't know (one added locally).
The rebuild would drop it. Save its data, then drop or rename it: `ALTER
TABLE observers DROP COLUMN <name>`.
- A row has a NULL `id` (the legacy `TEXT PRIMARY KEY` allows one). Find
it with `SELECT rowid, * FROM observers WHERE id IS NULL`, then delete
or fix it.

The error message names the column or the row count and these steps.
Starting the previous version also works: nothing was changed, and
`packets_v` stays readable for external SQLite readers in the meantime.

**A refusal stops the server too, not only ingest.** The server checks
the schema at startup (`AssertReady`) and exits when `observers.idx` is
not the primary key, so the whole site is down until the cause above is
fixed or the previous version is started again. Check for a locally
added column or a NULL `id` before upgrading if you are unsure.

**Ingest cost.** Measured with `BenchmarkUpsertObserverAtExisting`
(`cmd/ingestor`): 20000 `UpsertObserverAt` calls over 500 existing
observers, on a store opened by `OpenStore` with its own pragmas (WAL,
`synchronous=FULL`), Ryzen 3700X in Docker. A plain upsert on the new
table writes 5.23 WAL frames per call; update-first writes 4.23, one
frame less. The pre-PR table was not measured. Time per call is 676 to
726 µs before and 665 to 668 µs after; it is bound by fsync, so the
difference is within noise.

## Testing

- `internal/dbschema/observers_idx_test.go`: the rebuild keeps every
observation linked to the same observer, refuses an unknown column or a
NULL id, never reuses an `idx` (including one only orphaned observations
still reference), is idempotent, and handles the full legacy table.
- `TestObserversIdxPreservesLinksOnE2EFixture`: on a copy of
`test-fixtures/e2e-fixture.db`, 499/499 observations keep the same
observer.
- Refusals and rollback: a refused rebuild leaves the table, its rows,
`foreign_keys` and a readable `packets_v` as they were; a failure after
the old table is dropped rolls all of it back, leaves no
`observers_new`, and the next start completes the rebuild
(`TestObserversIdxRollsBackMidRebuild`,
`TestPacketsViewFollowsObserversShape`).
- Guards: `TestNoObserversRowidInSource` (ingestor) and
`TestNoObserversRowidInServerSources` fail if a query joins on
`observers.rowid` again. `TestFreshObserversMatchesRebuiltShape` pins
that a fresh install and a rebuilt one end up identical.
- `TestUpsertObserverAtLeavesSequenceAlone` and
`TestRecordNaiveSkewLeavesSequenceAlone`: 1000 calls on an existing
observer leave the sequence alone (on the previous head both moved it 1
-> 1001), and a new observer then gets `max(idx) + 1`.
`TestUpdateObserverMatchesUpsert` and `TestUpdateNaiveSkewMatchesUpsert`
check that the update path writes the same row as the upsert (COALESCE
of empty fields, `last_seen` never going back, the `can_relay`
tri-state, the 24 h skew counter).
- `TestAssertReadyRequiresObserversIdxPrimaryKey`: the rebuilt shape
passes; a plain `idx` column or none fails.
`TestOpenStoreRefusesUnconvertibleObservers`: through `OpenStore`, an
unknown column or a NULL id fails the open and leaves the table, its
rows and `packets_v` as they were.
- `go vet` and `go test` pass on all modules (`scripts/allmod.sh`), with
gofmt clean.

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



---

## Merge order

These four PRs were split out of #2396 and are **independent — they can
merge in any order.** Verified: every pair is conflict-free, and all
four merged together pass `go vet`, `go test ./...` (all 16 modules) and
`sh test-all.sh`.

Suggested order, none of it urgent:

1. **#2408** — never lose rows during startup / a failed poll.
2. **#2407** — explicit `observers.idx` primary key.
3. **#2409** — content-hash migration moved into the ingestor.
4. **#2410** — pin musl thread stacks at 8 MiB. Released images are not
affected (zig already links them with 8 MiB thread stacks); it fixes
native Alpine builds.

After these land, #2396 (Postgres) will be rebased onto master.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
zfouts and others added 3 commits November 22, 2026 17:37
Master brings Kpa-clawbot#2407 (observers.idx, reviewed version), Kpa-clawbot#2429 (repeater
details revision), Kpa-clawbot#2451-Kpa-clawbot#2454 (direct receptions, Heard by).

- observers.idx files take master's reviewed Kpa-clawbot#2407 copy; the branch had
  the pre-review one. AssertReady uses master's primary-key probe
  (SQLite only; Postgres has pgschema.AssertReady).
- Master's update-first observer UPDATE uses lastSeenClampSQL and
  CAST(? AS BIGINT), so it also runs on Postgres.
- users.db: master's repeater_info revision stays v10; the branch's
  rate_limits moves to v11, on SQLite and Postgres. Master's revision
  tests run on both backends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Master's Kpa-clawbot#2407 writes observers with an UPDATE first and the upsert as
its fallback (upsertObserver), so the prepared statements carry five
last_seen clamps, not four, on both backends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The server runs dbschema.AssertReady on both backends. Kpa-clawbot#2407's
primary-key check reads PRAGMA table_info, which Postgres rejects, so a
Postgres server refused to start ("observers.idx (probe error: syntax
error at or near PRAGMA)"). Like the other probes, it now tells the
backends apart through information_schema first: on Postgres observers'
primary key must be exactly idx, read from pg_index (the server's
SELECT-only role sees no keys in information_schema.table_constraints);
SQLite keeps the PRAGMA check.

TestAssertReadyPostgres runs as the owner and as a SELECT-only role; it
fails on the previous code with that error.

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
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>
@zfouts

zfouts commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master (6ab97f52) into the branch (63ebfb71) and pushed two follow-ups:

  1. 63ebfb71: conflicts resolved toward master's reviewed refactor(schema): give observers an explicit idx primary key #2407 code. Master's update-first observer UPDATE uses the portable clamp. Allow mobile clients to manage repeater claims and details #2429's repeater_info.revision is a Postgres accounts migration as well, and this PR's rate_limits step moves to users.db v11.
  2. c429a9f8: the hot-path SQL pin test now counts five last_seen clamps.
  3. 3091b995: a Postgres server no longer refuses to start on refactor(schema): give observers an explicit idx primary key #2407's PRAGMA-based primary-key check in AssertReady. It now reads pg_index there, which the read-only role can see. The regression test runs as a SELECT-only role.

Go (all modules, both backends), test-all.sh, and E2E suites on SQLite and Postgres pass locally; the description lists them.

@n30nex

n30nex commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

I tested a private merge of 5a9bea8cd with #2466 (42e73e488). Keep openAccountStore, deliveryStatus and checkSMTPAtStartup in the Go conflict. Preserve both account/channel configuration notes, the SMTP stats and test-mail entries, and the PostgreSQL backup endpoint’s 501 response.

Eight focused account and mail tests passed on Windows. The four DSN cases failed on the literal /data/users.db expectation. Using filepath.FromSlash("/data/users.db") there made all nine tests pass. Path assertion

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>
efiten pushed a commit that referenced this pull request Nov 28, 2026
## Summary

Answers #2100: *"My node is Rank #X on its Reach page — who is #1?"*

A new **Neighbor Rank** tab on the Analytics page lists every ranked
node by all-time neighbour count. Each row shows the node's placement,
name, role and neighbour count, with a link to its Reach page. The tab
has search, a role filter, paging and deep links. The Reach page's Rank
card now links to it and opens the list at the node's own row.

Inspired by dborup's Reach leaderboard in their fork
(dborup#69). This is a fresh implementation on current master.

## What changed

- **API:** `GET /api/nodes/neighbor-rank?q=&role=&offset=&limit=&focus=`
returns a typed `NeighborRankResponse`: `entries`, `total`, `offset`,
`ranked`, `snapshot_at`. `focus=<pubkey>` returns the page that contains
that node, so a link to a node deep inside a large tie group still lands
on its row.
- **One rank, two views:** the endpoint and the Reach card's Rank use
the same cached rank view, so they always agree.
  - Ties share a placement (1, 1, 3).
  - A search or role filter narrows the list but never renumbers it.
  - Only valid 64-hex pubkeys that have a nodes row are ranked.
- Only edges whose two ends are both valid pubkeys count toward a
degree. The e2e fixture has 55 edges with an empty `node_a`, which used
to show up as a nameless #1.
- **Visibility:** the ranked population follows the `/api/nodes` rule
(blacklist, hidden name prefixes, geo_filter), so hidden nodes are never
listed. The view is rebuilt when the degree snapshot, the visibility
rules or the node cache change. The reach cache key now includes the
visibility generation.
- **Reach card:** shows "Not ranked" instead of `#0 / N`, plus a **View
leaderboard** link.
- **Frontend:** a self-contained `public/neighbor-rank.js` with pure
helpers, unit-tested via `vm`. Search is debounced, only the tbody is
replaced, and stale responses are dropped. A debounced search or a
response that arrives after the user leaves the tab does nothing (it
checks the tab's own rows, not the shared `#analyticsContent`). The tab
has loading, empty, no-match and error-with-Retry states. All colours
are CSS variables (`--link-color`, `--accent-strong`). It fits a 360 px
phone without sideways scrolling.

## Performance

| Operation, 10,000 ranked nodes | Time |
|---|---|
| Build the rank view (once per 60 s snapshot, or on a visibility or
node-cache change) | 5.6 ms |
| Serve a cached page with `q` and `role` filters | 0.15 ms |

`TestNeighborRankCachedPageUnder5msFor10kNodes` asserts the serve time.

## Tests

- **Go:** the 64-character `q` limit counts characters, not bytes
(multi-byte cases at 64 and 65), ties, degree-0 nodes, hidden and
blacklisted nodes excluded from both the list and the card, card ==
list, filters don't renumber, paging, every bad parameter returns 400,
503 without a snapshot, invalid and empty pubkeys, a node without a row
excluded, a rename into a hidden prefix, a stale-view race, and `focus`
across a 130-node tie group.
- **Frontend unit:** `tests/unit/test-neighbor-rank.js` (21 tests),
including the client's 64-character cap on accented text and emoji, in
the URL state and in the search box (code points, not UTF-16 units).
- **E2E:** `tests/e2e/test-neighbor-rank-e2e.js`, added to `deploy.yml`
(shard 1). Step 7 leaves the tab during the debounce and with a held
request; it fails on the code before `5e372f47`. Step 4b pastes 62
letters, 📡 and Z (64 code points) and checks the box keeps all of them
and cuts a 65th. The tab is added to the axe suite (108 cells, 0
violations).

Local runs:
- full `cmd/server` suite, plus `-race` on the new tests
- `test-all.sh`
- all 138 browser suites on the e2e fixture. Failures matched master or
were setup-only: user-management, the split frontend, and the known
flaky `test-issue-1147`.
- screenshots at 1440×900, 390×844 and 360×740, light and dark

## Notes for reviewers

- Review fixes are in `5e372f47`; see the reply comment.

- The Reach card's rank and total change slightly on instances that hide
nodes, because hidden nodes are no longer counted. This is intentional,
so the card and the list agree.
- The Reach response is cached for 5 minutes, so the number on the card
can trail the list by up to that long. The leaderboard link still lands
on the right row, because the server resolves it with `focus`.
- Paging and filters update the URL with `replaceState`, like the other
Analytics tabs. Back does not step through pages.
- If #2396 (Postgres) merges first, its parity test
`pg_store_queries_test.go` must stop reading
`degreeSnapshot.total`/`sortedDesc`, which this PR removed as dead.
That's a one-line change, already done on our integration branch.

- Merging with the other overnight PR: whichever lands second needs a
one-line rebase in `.github/workflows/deploy.yml` (both add a suite line
next to test-node-reach-e2e.js).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
resolveUserManagement builds dbPath with filepath.Join, so on Windows it
is \data\users.db and the four DSN cases failed on the literal
/data/users.db. Found and checked on Windows by n30nex.

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

zfouts commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@n30nex thanks for testing the merge, and for the Windows fix. Sorry for the slow reply.

  1. Windows path assertion (21c41337): TestResolveUserManagementAccountsDSN now compares dbPath with filepath.FromSlash("/data/users.db"), as you suggested (cmd/server/accounts_pg_test.go:163). I could only run it on Linux, where it passes.
  2. Master merge: in progress, following your notes. openAccountStore, deliveryStatus and checkSMTPAtStartup are all kept, as are both configuration notes, the SMTP stats and test-mail entries, and the backup endpoint's 501 on PostgreSQL. The branch is now 37 commits behind. Since your test, master has also gained the push relay (Optional mobile push for watched-node alerts through a push relay #2447) and Pushover (Optional Pushover delivery for watched-node alerts #2455), whose delivery queues live in users.db. The merge will include a full PostgreSQL port of both, so that with accounts in PostgreSQL each notification is delivered once across replicas. I'll post here when it's pushed.

… 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>
@zfouts

zfouts commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master (68b9fe34), following the notes from n30nex, and ported the push relay (#2447) and Pushover (#2455) to Postgres and several replicas. The branch is up to date with master again.

Merge

  1. Conflicts were resolved as n30nex described. Both sides are kept for:
    • openAccountStore, deliveryStatus and checkSMTPAtStartup;
    • the account and channel configuration notes;
    • the SMTP stats and test-mail entries;
    • the backup endpoint's 501 on Postgres.
  2. notify_service.go keeps master's notification destinations. It also keeps this PR's evaluation lock and mail claim; the claim now travels as notifyChanges.claim (cmd/server/notify_destination.go).
  3. users.db now goes to schema v14:
    • v11 and v12 are master's push and Pushover steps;
    • rate_limits moves to v13;
    • v14 holds the shared push relay state and the Pushover connect tokens.

Push relay and Pushover with several replicas

Both features assumed one server process: enrollment state in users.db.push-relay*.json files, pause and disconnect in memory, and every replica draining the same queues. They now work across replicas:

  1. Postgres migrations v11 to v14 are in place. The five SQLite triggers are ported as plpgsql functions, and the parity test now also compares trigger names.
  2. The relay enrollment, its delivery phase and the pending enrollment, including the proof seed, live in the accounts store.
    • Writes are compare-and-set on a revision.
    • Replicas re-read the state per tick, per dispatch pass and per job. A pause on one replica therefore stops another after at most the push in progress.
    • The relay's proof callback and the Pushover connect return work on any replica.
  3. Old state files are imported once at startup. An enrollment file under a manual pushRelay, or made for another public origin, stays on disk with a warning, as master ignored it.
  4. Credentials are sealed with a new userManagement.encryptionKey (CORESCOPE_ACCOUNTS_KEY).
    • The key is required on Postgres.
    • On SQLite without a key, the credential stays inside users.db, which is now set to mode 0600.
    • Users backups blank the relay secrets.
  5. Each queued job is claimed with a 5-minute lease (SKIP LOCKED), and each queue drains under a database lock.
    • Advisory locks use their own connection pool, so lock holders can't starve the accounts store.
    • Device links and the Pushover per-user limit lock the user.
  6. A security review and a code review covered this port. All accepted findings are fixed, with regression tests. Among them:
    • The lock-pool starvation.
    • The import pruning a manual relay's devices.
    • A lease shorter than a send batch.
    • Rate limits on the unauthenticated proof endpoint and on device link/unlink.

Found while integrating

  1. fix(reach): exclude observer TX reports from directional evidence #2486's reach query used IS NOT 'tx', which Postgres rejects. It now uses IS DISTINCT FROM (cmd/server/node_reach.go:804).
  2. docker/server-exec.sh did not pass five variables the server reads, four of them from master's new features: CORESCOPE_PUSHOVER_TOKEN, CORESCOPE_PUSH_RELAY_CREDENTIAL, CORESCOPE_SMTP_PASSWORD and CORESCOPE_URL, plus the new CORESCOPE_ACCOUNTS_KEY. tests/unit/test-server-exec-env.js now fails whenever the server reads one that the script doesn't pass.
  3. corescope-migrate copy-users failed on notification_pushover_sent, which has no key. It now gets a rowid on Postgres, like mail_events. verify-users also redacts credential and seed columns: before this, it printed the relay credential in a difference report.

Testing

Run locally on 68b9fe34:

  • go test for all 17 modules against SQLite and Postgres 17;
  • go vet, also with -tags e2etest;
  • gofmt, eslint and test-all.sh.

E2E was not re-run locally this time; CI runs it on both backends. The PR description is updated to match.

zfouts and others added 2 commits December 1, 2026 19:20
… and the advert reception changes to Postgres

Brings in 10 master commits: Kpa-clawbot#2366 (catalogue key tier), Kpa-clawbot#2497 (regions
count only received adverts), Kpa-clawbot#2498 (archived foreign-advert flags), Kpa-clawbot#2492
(observer comparison), Kpa-clawbot#2511, Kpa-clawbot#2513, Kpa-clawbot#2514, Kpa-clawbot#2517, Kpa-clawbot#2518, Kpa-clawbot#2519.

Conflicts:
- cmd/ingestor/approved_channels.go: both sides added a mutex to
  channelKeySet. One mu now serialises refresh, master's setCatalog and the
  branch's Close, and guards the users.db/Postgres accounts readers as well
  as master's approvedNames and catalogue tier.
- cmd/ingestor/db.go, nodes upsert: master's foreign_advert carry-over on
  top of the branch's qualified columns and lastSeenClampSQL. Master looked
  up the archived flag with ?1, which dbx.Rebind turns into $11 on Postgres;
  it is now a plain ? bound to the public key again, and the EXISTS is
  wrapped in CASE so Postgres stores 0/1 in the BIGINT column.
- cmd/ingestor/db.go, MoveStaleNodes: master's UPDATE that restores an
  archived foreign flag runs before the branch's portable moveStaleNodesSQL
  (not master's INSERT OR REPLACE ... SELECT *), with IS DISTINCT FROM 1
  instead of the SQLite-only IS NOT 1.

Ported to Postgres:
- catalog_keys (Kpa-clawbot#2366): pgschema migration 0004_catalog_keys.sql (same
  columns, CHECKs, defaults and key; LatestVersion 4), the table in
  sqlite_endstate.sql, and the worker's upsert sets updated_at from
  excluded.updated_at instead of strftime('%s','now').
- corescope-migrate copies catalog_keys and verify never prints
  catalog_keys.key_hex (channel secrets), for any store.
- GetNodes region filter (Kpa-clawbot#2497) and the observer comparison (Kpa-clawbot#2492) used
  IS NOT 'tx'; both use IS DISTINCT FROM 'tx'. The comparison's
  ORDER BY label COLLATE NOCASE is lower(<label expression>) on Postgres,
  which folds ASCII only under COLLATE "C", as NOCASE does.
- docs/catalogue-keys.md: the revert SQL on PostgreSQL.

Tests on both backends:
- The catalogue key tests that use a store and the Kpa-clawbot#2498 foreign-advert
  tests run on SQLite and Postgres (onBothStores; insertTx uses RETURNING).
- New dual tests for the observer comparison and the GetNodes region filter.
- pgschema: an upgrade from version 3 with data; the control migration tests
  no longer assume 3 is the latest version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SQLite-only forms master brought in this round (Kpa-clawbot#2492, Kpa-clawbot#2497, Kpa-clawbot#2498,
Kpa-clawbot#2366) and in the last one (Kpa-clawbot#2486) were only caught by Postgres test runs.
The ingestor's portable-SQL guard now also rejects IS NOT with a number,
numbered placeholders (dbx.Rebind turns ?1 into $11) and strftime; the
server gets a guard for IS NOT with a literal and numbered placeholders.
Both scanners have self-tests.

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

zfouts commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged master 144937cd (10 commits: #2366, #2492, #2497, #2498, #2511, #2513, #2514, #2517, #2518, #2519) in e51a03dd, plus a follow-up test commit 894410db.

Conflicts

  • cmd/ingestor/approved_channels.go: both sides added a mutex to channelKeySet. Now one mu covers refresh, master's setCatalog and this branch's Close.
  • cmd/ingestor/db.go, nodes upsert: master's foreign-advert carry-over (Keep historical foreign-advert flags when archived nodes return #2498) now sits on top of this branch's qualified columns and portable last_seen clamp. Master's ?1 is now a plain ?, because dbx.Rebind would turn ?1 into $11. The EXISTS is wrapped in CASE, so Postgres stores 0 or 1 in the BIGINT column.
  • cmd/ingestor/db.go, MoveStaleNodes: master's restore-flag UPDATE now runs before this branch's moveStaleNodesSQL. It uses IS DISTINCT FROM 1, not the SQLite-only IS NOT 1.

Ported to Postgres

  • catalog_keys (feat(#2107): evidence-gated catalogue key tier for channels and regions #2366):
    • new pgschema migration 0004_catalog_keys.sql, with the same columns, CHECKs, defaults and key; the Postgres schema is now at version 4;
    • added to sqlite_endstate.sql;
    • the worker's upsert takes updated_at from excluded.updated_at instead of strftime;
    • corescope-migrate copies the table, and verify never prints key_hex;
    • docs/catalogue-keys.md notes the Postgres form of its revert SQL.
  • Count only received adverts when assigning node regions #2497's GetNodes region filter and Compare observers against a pinned reference #2492's observer comparison used IS NOT 'tx'. Both now use IS DISTINCT FROM 'tx'.
  • The comparison's COLLATE NOCASE order becomes lower(...) on Postgres. Under COLLATE "C", lower() folds ASCII only, the same as NOCASE.
  • 894410db extends the ingestor's portable-SQL guard to reject IS NOT <number>, ?N and strftime, and adds a matching guard for the server.

Tests

  • Master's catalogue-key store tests and Keep historical foreign-advert flags when archived nodes return #2498's foreign-advert tests now run on SQLite and Postgres.
  • New dual-backend tests cover the observer comparison (direction states, NOCASE ties, a non-ASCII label) and the region filter.
  • A new pgschema test upgrades a version-3 database that holds data.
  • Local results:
    • all 17 Go modules pass with Postgres 17, with go vet and gofmt clean;
    • ingestor, server, migrate and dbschema also pass without a Postgres DSN;
    • test-all.sh passes, and eslint reports 0 errors.
  • E2E was not re-run locally; CI runs it on both backends.

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.

3 participants