From 3b9ca7abe6204f70c51382a5a625aeb2322df346 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:43:49 -0500
Subject: [PATCH 01/33] docs: data-revision atomicity; upgrade waits on /ready
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
docs/DEVELOPMENT.md | 19 +++++++++++++++++++
docs/INSTALL.md | 13 ++++++++++++-
planning/roadmap.yaml | 18 ++++++++++++++++++
3 files changed, 49 insertions(+), 1 deletion(-)
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 145bb81c..84c12dd6 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -440,6 +440,25 @@ if absent, add a column only if missing, drop an index only if present, clear a
staging table before recreating it. `flightsite.db.migrations.rebuild` provides the
`has_table` / `has_index` / `has_column` predicates for exactly this.
+### Data-only revisions are atomic; DDL before the first DML may not be
+
+The rule above is about schema revisions. A **data-only revision** (one that only
+inserts, updates or deletes rows) run through `Database.upgrade_to` is atomic: it runs
+inside the `engine.begin()` transaction, so a failure rolls all of it back and
+`alembic_version` still names the older revision. A restart then re-runs it from the
+top over an untouched database. `test_a_failed_run_rolls_back_whole` in
+`tests/db/test_migration_0021_purge_false_rarity_matches.py` proves this for 0021.
+
+The guarantee covers the DML. Any DDL the revision issues before its first DML
+statement may fall outside that transaction (SQLite DDL is not transactional under Alembic). In
+0021 that is only the temp-table drop and create, which is harmless: the revision drops
+any stray table before it creates one, so it can be re-run. A data revision that issues
+other DDL must make that DDL resumable as described above.
+
+A data revision should carry a rollback test like 0021's: make the run fail partway and
+assert that the database is unchanged and `alembic_version` still names the older
+revision.
+
### Rebuilding a table: disable foreign keys, then check them
SQLite cannot alter a `CHECK` (or most constraints) in place, so widening one means
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 4780c0c8..51b01126 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -517,13 +517,24 @@ docker compose logs -f flightsite-backend # optional: watch the migration
until docker compose exec -T flightsite-backend python -c \
"import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=3)" \
2>/dev/null; do sleep 10; done
+docker compose exec -T flightsite-backend python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/ready', timeout=3)" && echo "READY: upgrade complete" || echo "NOT READY: the migration failed, see below"
docker compose up -d # now starts the frontend too
```
+Run the `/ready` check once, after the loop. The backend migrates before it starts
+listening, so while the migration runs, requests get "connection refused" and the loop
+keeps waiting. Once the backend listens, `/api/v1/health` answers whether or not the
+migration succeeded, because a failed migration does not abort startup. So the loop
+ending does not mean the upgrade worked. `/api/v1/ready` answers 200 when the database
+is ready. It answers 503 after a failed migration, and `urlopen` then exits non-zero.
+If you see `NOT READY`, do not run `docker compose up -d`. Read the backend log for
+the error, then restore the backup you took before the upgrade.
+
In the logs, `Found N false rarity alert matches` marks the start of the purge.
`Purged N false rarity alert matches on M sightings` means the purge has finished.
The commit, the integrity check and the analytics rebuild follow. The loop ends when
-the backend answers. Then the upgrade is complete.
+the backend answers. The upgrade is complete only when the `/ready` check above
+prints `READY`.
**Why not a plain `docker compose up -d`:** the backend's health check
(`start_period` 15 s, `interval` 30 s, `retries` 3) marks the container unhealthy
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 2b2bdf63..015e11b0 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3811,6 +3811,24 @@ slices:
risk_level: high
notes: "Follows #360 (fixed by slice 125, PR #363). The owner approved the permanent deletion of this history."
+ - id: "130"
+ title: "Docs: data-revision atomicity; the upgrade waits on /ready"
+ phase: 9
+ branch: "130-migration-atomicity-ready-check"
+ status: merged
+ depends_on: ["126"]
+ objective: "Document that data-only Alembic revisions are atomic while DDL before the first DML may not be, and make the INSTALL.md backend-first upgrade check /api/v1/ready once after the health loop."
+ scope:
+ - "docs/DEVELOPMENT.md: data-only revisions are atomic inside engine.begin(); DDL before the first DML may fall outside; a data revision carries a rollback test like 0021's"
+ - "docs/INSTALL.md section 8.1: keep polling /health (connection refused while migrating), then check /ready once: 200 = done, 503 = migration failed, read the log and restore the backup"
+ required_tests: []
+ expected_artifacts:
+ - docs/DEVELOPMENT.md
+ - docs/INSTALL.md
+ preferred_agent: sonnet
+ risk_level: low
+ notes: "Closes #366."
+
# Parallelization guide (dependency-derived; Fable owns merge order). Slices adding
From 4429b84f9f0aeeac75557a838ccd9cc882e7a528 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:46:13 -0500
Subject: [PATCH 02/33] docs: gate frontend start on /ready, precise DDL
wording, roadmap criteria
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
docs/DEVELOPMENT.md | 9 +++++----
docs/INSTALL.md | 17 ++++++++++++-----
planning/roadmap.yaml | 6 ++++++
3 files changed, 23 insertions(+), 9 deletions(-)
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 84c12dd6..4796c3ab 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -450,10 +450,11 @@ top over an untouched database. `test_a_failed_run_rolls_back_whole` in
`tests/db/test_migration_0021_purge_false_rarity_matches.py` proves this for 0021.
The guarantee covers the DML. Any DDL the revision issues before its first DML
-statement may fall outside that transaction (SQLite DDL is not transactional under Alembic). In
-0021 that is only the temp-table drop and create, which is harmless: the revision drops
-any stray table before it creates one, so it can be re-run. A data revision that issues
-other DDL must make that DDL resumable as described above.
+statement may fall outside that transaction: the sqlite3 driver opens its implicit
+transaction only at the first DML statement. In 0021 that DDL is only the temp-table
+drop and create, which is harmless: the revision drops any stray table before it
+creates one, so it can be re-run. A data revision that issues other DDL must make that
+DDL resumable as described above.
A data revision should carry a rollback test like 0021's: make the run fail partway and
assert that the database is unchanged and `alembic_version` still names the older
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 51b01126..456065c9 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -517,8 +517,13 @@ docker compose logs -f flightsite-backend # optional: watch the migration
until docker compose exec -T flightsite-backend python -c \
"import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=3)" \
2>/dev/null; do sleep 10; done
-docker compose exec -T flightsite-backend python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/ready', timeout=3)" && echo "READY: upgrade complete" || echo "NOT READY: the migration failed, see below"
-docker compose up -d # now starts the frontend too
+if docker compose exec -T flightsite-backend python -c \
+ "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/ready', timeout=3)" \
+ 2>/dev/null; then
+ docker compose up -d # now starts the frontend too
+else
+ echo "NOT READY: the migration or the integrity check failed. Do not start the frontend."
+fi
```
Run the `/ready` check once, after the loop. The backend migrates before it starts
@@ -526,9 +531,11 @@ listening, so while the migration runs, requests get "connection refused" and th
keeps waiting. Once the backend listens, `/api/v1/health` answers whether or not the
migration succeeded, because a failed migration does not abort startup. So the loop
ending does not mean the upgrade worked. `/api/v1/ready` answers 200 when the database
-is ready. It answers 503 after a failed migration, and `urlopen` then exits non-zero.
-If you see `NOT READY`, do not run `docker compose up -d`. Read the backend log for
-the error, then restore the backup you took before the upgrade.
+is ready. It answers 503 after a failed migration or a failed integrity check. `urlopen`
+then raises `HTTPError`, so python exits non-zero and the block does not start the
+frontend. In that case read the backend log for the error. A failed 0021 rolls back
+whole, so restoring the backup you took before the upgrade (see
+[BACKUP.md](BACKUP.md#before-upgrading)) is a precaution, not a repair.
In the logs, `Found N false rarity alert matches` marks the start of the purge.
`Purged N false rarity alert matches on M sightings` means the purge has finished.
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 015e11b0..5f4868ff 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3821,6 +3821,12 @@ slices:
scope:
- "docs/DEVELOPMENT.md: data-only revisions are atomic inside engine.begin(); DDL before the first DML may fall outside; a data revision carries a rollback test like 0021's"
- "docs/INSTALL.md section 8.1: keep polling /health (connection refused while migrating), then check /ready once: 200 = done, 503 = migration failed, read the log and restore the backup"
+ out_of_scope:
+ - "code changes"
+ - "CHANGELOG.md"
+ acceptance_criteria:
+ - "the INSTALL.md section 8.1 block does not start the frontend when /ready answers 503"
+ - "DEVELOPMENT.md names the 0021 rollback test as the expectation for data revisions"
required_tests: []
expected_artifacts:
- docs/DEVELOPMENT.md
From 008408dc46ce1444f6c8d89235d35e59233e38b3 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:47:13 -0500
Subject: [PATCH 03/33] docs: print READY in the upgrade block; split failure
cases
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
docs/INSTALL.md | 9 ++++++---
planning/roadmap.yaml | 2 +-
2 files changed, 7 insertions(+), 4 deletions(-)
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 456065c9..534d6a53 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -521,6 +521,7 @@ if docker compose exec -T flightsite-backend python -c \
"import urllib.request as u; u.urlopen('http://127.0.0.1:8000/api/v1/ready', timeout=3)" \
2>/dev/null; then
docker compose up -d # now starts the frontend too
+ echo "READY: upgrade complete."
else
echo "NOT READY: the migration or the integrity check failed. Do not start the frontend."
fi
@@ -533,9 +534,11 @@ migration succeeded, because a failed migration does not abort startup. So the l
ending does not mean the upgrade worked. `/api/v1/ready` answers 200 when the database
is ready. It answers 503 after a failed migration or a failed integrity check. `urlopen`
then raises `HTTPError`, so python exits non-zero and the block does not start the
-frontend. In that case read the backend log for the error. A failed 0021 rolls back
-whole, so restoring the backup you took before the upgrade (see
-[BACKUP.md](BACKUP.md#before-upgrading)) is a precaution, not a repair.
+frontend. In that case read the backend log for the error. After a failed migration
+the database is unchanged, because a failed 0021 rolls back whole, so restoring the
+backup you took before the upgrade (see [BACKUP.md](BACKUP.md#before-upgrading)) is a
+precaution. After a failed integrity check the migration may already have committed:
+restore the backup.
In the logs, `Found N false rarity alert matches` marks the start of the purge.
`Purged N false rarity alert matches on M sightings` means the purge has finished.
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 5f4868ff..41af8b6b 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3820,7 +3820,7 @@ slices:
objective: "Document that data-only Alembic revisions are atomic while DDL before the first DML may not be, and make the INSTALL.md backend-first upgrade check /api/v1/ready once after the health loop."
scope:
- "docs/DEVELOPMENT.md: data-only revisions are atomic inside engine.begin(); DDL before the first DML may fall outside; a data revision carries a rollback test like 0021's"
- - "docs/INSTALL.md section 8.1: keep polling /health (connection refused while migrating), then check /ready once: 200 = done, 503 = migration failed, read the log and restore the backup"
+ - "docs/INSTALL.md section 8.1: keep polling /health (connection refused while migrating), then check /ready once: 200 = done, 503 = migration or integrity check failed, read the log and restore the backup"
out_of_scope:
- "code changes"
- "CHANGELOG.md"
From 03d103d407bf17586cba21b0d7baf2294a4aa495 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:47:26 -0500
Subject: [PATCH 04/33] feat(map): bring the aircraft into view from every
selection path
Interesting-panel rows and keyboard cycling request focus only when the
aircraft is off screen (the visible area excludes the phone sheet); a
?selected= deep link requests a plain focus. Map-marker clicks stay
select-only.
Refs #362
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
e2e/tests/04-selected-deep-link-focus.spec.ts | 88 +++++++++++++++++++
.../hooks/useSelectionUrlSync.test.tsx | 16 ++++
.../filters/hooks/useSelectionUrlSync.ts | 8 +-
.../interesting/InterestingPanel.test.tsx | 15 ++++
.../features/interesting/InterestingPanel.tsx | 8 +-
.../useFocusSelectedAircraft.test.tsx | 64 ++++++++++++++
.../map/aircraft/useFocusSelectedAircraft.ts | 40 ++++++++-
.../map/store/useMapFocusRequestStore.ts | 29 ++++--
.../shortcuts/useKeyboardShortcuts.test.tsx | 41 +++++++++
.../src/lib/shortcuts/useKeyboardShortcuts.ts | 3 +-
frontend/src/test/maplibreGlMock.ts | 21 ++++-
planning/roadmap.yaml | 31 +++++++
12 files changed, 350 insertions(+), 14 deletions(-)
create mode 100644 e2e/tests/04-selected-deep-link-focus.spec.ts
diff --git a/e2e/tests/04-selected-deep-link-focus.spec.ts b/e2e/tests/04-selected-deep-link-focus.spec.ts
new file mode 100644
index 00000000..65929f9c
--- /dev/null
+++ b/e2e/tests/04-selected-deep-link-focus.spec.ts
@@ -0,0 +1,88 @@
+/**
+ * Flow (d) follow-up — a `?selected=` deep link brings the aircraft
+ * into view (roadmap slice 129, issue #362). Before, the link selected the
+ * aircraft and opened its detail panel but left the camera where it was, so
+ * an aircraft outside the opening view stayed off screen. The mount effect
+ * now goes through `focusAircraftOnMap`, which eases the camera to the
+ * aircraft once the map, its record and a position are there.
+ *
+ * Asserted through the live MapLibre instance (`window.__flightsiteMap`, as
+ * `support/liveMap.ts` does): once the ease settles the aircraft projects
+ * near the centre of the map container. Demo aircraft keep moving, hence a
+ * generous tolerance rather than an exact centre.
+ */
+
+import {
+ browserHasWebGl,
+ fetchPositionedAircraft,
+ pickStableAircraft,
+ waitForAircraftLayer,
+ waitForLiveAircraft,
+} from "./support/liveMap";
+import { expect, test } from "./support/fixtures";
+
+const CENTRE_TOLERANCE_PX = 120;
+
+test.describe("?selected= deep link", () => {
+ test("selects the aircraft and eases the map to it", async ({
+ page,
+ request,
+ }) => {
+ const aircraft = pickStableAircraft(await fetchPositionedAircraft(request));
+
+ await page.goto(`/?selected=${aircraft.icao}`);
+ test.skip(
+ !(await browserHasWebGl(page)),
+ "browser has no WebGL — the map cannot render; the focus request is unit-tested",
+ );
+ await waitForLiveAircraft(page);
+ await waitForAircraftLayer(page);
+
+ await expect(page.getByTestId("aircraft-detail-panel")).toBeVisible();
+
+ // Distance, in pixels, from the aircraft's current projected position to
+ // the centre of the map container. Reads the aircraft's latest position
+ // from the API each poll, so its own movement does not skew the check.
+ await expect
+ .poll(
+ async () => {
+ const current = (await fetchPositionedAircraft(request)).find(
+ (item) => item.icao === aircraft.icao,
+ );
+ if (!current?.position) {
+ return Number.POSITIVE_INFINITY;
+ }
+ return page.evaluate(
+ ({ lat, lon }) => {
+ const map = (
+ window as unknown as {
+ __flightsiteMap?: {
+ project: (ll: [number, number]) => {
+ x: number;
+ y: number;
+ };
+ getContainer: () => {
+ clientWidth: number;
+ clientHeight: number;
+ };
+ };
+ }
+ ).__flightsiteMap;
+ if (!map) {
+ return Number.POSITIVE_INFINITY;
+ }
+ const point = map.project([lon, lat]);
+ const container = map.getContainer();
+ return Math.hypot(
+ point.x - container.clientWidth / 2,
+ point.y - container.clientHeight / 2,
+ );
+ },
+ { lat: current.position.lat, lon: current.position.lon },
+ );
+ },
+ { timeout: 15_000 },
+ )
+ .toBeLessThan(CENTRE_TOLERANCE_PX);
+ });
+});
diff --git a/frontend/src/features/filters/hooks/useSelectionUrlSync.test.tsx b/frontend/src/features/filters/hooks/useSelectionUrlSync.test.tsx
index 64e77266..12aefffe 100644
--- a/frontend/src/features/filters/hooks/useSelectionUrlSync.test.tsx
+++ b/frontend/src/features/filters/hooks/useSelectionUrlSync.test.tsx
@@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import { useSelectionUrlSync } from "@/features/filters/hooks/useSelectionUrlSync";
import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircraftStore";
+import { useMapFocusRequestStore } from "@/features/map/store/useMapFocusRequestStore";
function TestHost() {
useSelectionUrlSync();
@@ -26,6 +27,7 @@ function renderHost(initialPath = "/") {
beforeEach(() => {
useLiveAircraftStore.getState().reset();
+ useMapFocusRequestStore.getState().clearFocus();
});
describe("useSelectionUrlSync", () => {
@@ -34,6 +36,20 @@ describe("useSelectionUrlSync", () => {
expect(useLiveAircraftStore.getState().selectedIcao).toBe("aaaaaa");
});
+ it("asks the map to bring the URL's aircraft into view, always (issue #362)", () => {
+ renderHost("/?selected=aaaaaa");
+ expect(useMapFocusRequestStore.getState()).toMatchObject({
+ icao: "aaaaaa",
+ onlyIfOffscreen: false,
+ });
+ });
+
+ it("makes no focus request for what is already selected", () => {
+ useLiveAircraftStore.getState().selectAircraft("aaaaaa");
+ renderHost("/?selected=aaaaaa");
+ expect(useMapFocusRequestStore.getState().icao).toBeNull();
+ });
+
it("keeps the selection when the aircraft is not (yet) in the live set", () => {
// The store holds the intent even with no matching record — the panel's
// own "no live data" rendering is what covers the rest (R1-09).
diff --git a/frontend/src/features/filters/hooks/useSelectionUrlSync.ts b/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
index f951eda3..32d630dc 100644
--- a/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
+++ b/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
@@ -12,7 +12,9 @@
* Two edges, each one-way, mirroring `useFilterUrlSync`'s own split:
*
* - **URL -> store, mount only.** A `?selected=` present at mount selects
- * that ICAO — restoring a bookmarked or shared link. If the aircraft is
+ * that ICAO and asks the map to bring it into view (issue #362; the focus
+ * request waits for the map, the record and a position) — restoring a
+ * bookmarked or shared link. If the aircraft is
* not (yet) in the live set, the selection is still made: the store holds
* the intent, `AircraftDetailPanel` opens and reads `null` from
* `state.aircraft[selectedIcao]`, rendering "No live data for this
@@ -50,11 +52,11 @@ import {
withSelectedIcaoInSearchParams,
} from "@/features/filters/lib/selectionUrlSync";
import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircraftStore";
+import { focusAircraftOnMap } from "@/features/map/store/useMapFocusRequestStore";
export function useSelectionUrlSync(): void {
const [searchParams, setSearchParams] = useSearchParams();
const selectedIcao = useLiveAircraftStore((state) => state.selectedIcao);
- const selectAircraft = useLiveAircraftStore((state) => state.selectAircraft);
const skipNextWrite = useRef(false);
useEffect(() => {
@@ -64,7 +66,7 @@ export function useSelectionUrlSync(): void {
icaoFromUrl !== useLiveAircraftStore.getState().selectedIcao
) {
skipNextWrite.current = true;
- selectAircraft(icaoFromUrl);
+ focusAircraftOnMap(icaoFromUrl);
}
// Deliberately mount-only — see the module doc comment.
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/frontend/src/features/interesting/InterestingPanel.test.tsx b/frontend/src/features/interesting/InterestingPanel.test.tsx
index d3da8a2b..c9bbcf55 100644
--- a/frontend/src/features/interesting/InterestingPanel.test.tsx
+++ b/frontend/src/features/interesting/InterestingPanel.test.tsx
@@ -7,12 +7,14 @@ import { useFilterStore } from "@/features/filters/store/useFilterStore";
import { DEFAULT_FILTERS } from "@/features/filters/types";
import { InterestingPanel } from "@/features/interesting/InterestingPanel";
import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircraftStore";
+import { useMapFocusRequestStore } from "@/features/map/store/useMapFocusRequestStore";
import type { LiveAircraft } from "@/lib/api/live";
import { makeAircraft } from "@/test/liveAircraftFixtures";
beforeEach(() => {
resetFilteredLiveAircraftCache();
useLiveAircraftStore.getState().reset();
+ useMapFocusRequestStore.getState().clearFocus();
useFilterStore.setState({ filters: DEFAULT_FILTERS });
});
@@ -176,6 +178,19 @@ describe("InterestingPanel", () => {
expect(useLiveAircraftStore.getState().selectedIcao).toBe("cccccc");
});
+ it("also asks the map to bring the aircraft into view when off screen (issue #362)", async () => {
+ seed(demoScenario());
+ render();
+
+ await userEvent.click(screen.getAllByTestId("interesting-row")[0]!);
+
+ // No map is mounted here, so the request stays pending for it.
+ expect(useMapFocusRequestStore.getState()).toMatchObject({
+ icao: "cccccc",
+ onlyIfOffscreen: true,
+ });
+ });
+
it("marks the selected row with aria-current", async () => {
seed(demoScenario());
render();
diff --git a/frontend/src/features/interesting/InterestingPanel.tsx b/frontend/src/features/interesting/InterestingPanel.tsx
index 3306c44f..e50f3b0e 100644
--- a/frontend/src/features/interesting/InterestingPanel.tsx
+++ b/frontend/src/features/interesting/InterestingPanel.tsx
@@ -43,6 +43,7 @@ import {
orderInterestingAircraft,
} from "@/features/interesting/lib/ordering";
import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircraftStore";
+import { focusAircraftOnMap } from "@/features/map/store/useMapFocusRequestStore";
import { cn } from "@/lib/utils";
/** The browser's own wall-clock reading of a `Date.now()` value — what
@@ -84,7 +85,10 @@ export function InterestingPanel() {
const lastUpdate = useLiveAircraftStore((state) => state.lastUpdate);
const receiver = useLiveAircraftStore((state) => state.receiver);
const selectedIcao = useLiveAircraftStore((state) => state.selectedIcao);
- const selectAircraft = useLiveAircraftStore((state) => state.selectAircraft);
+ // Select and bring into view, but only when off screen (issue #362): a
+ // row click for an aircraft already in plain view must not lurch the map.
+ const focusInteresting = (icao: string) =>
+ focusAircraftOnMap(icao, { onlyIfOffscreen: true });
const units = receiver?.units ?? "aviation";
const rows = orderInterestingAircraft(aircraft);
@@ -182,7 +186,7 @@ export function InterestingPanel() {
entry={entry}
units={units}
selected={entry.aircraft.icao === selectedIcao}
- onSelect={selectAircraft}
+ onSelect={focusInteresting}
/>
),
)}
diff --git a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
index e74f5ec0..023c0d46 100644
--- a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
+++ b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
@@ -150,6 +150,70 @@ describe("useFocusSelectedAircraft: review follow-ups", () => {
});
});
+describe("useFocusSelectedAircraft: onlyIfOffscreen (issue #362)", () => {
+ // The mock map's default bounds span lon -123..-121.9, lat 47..47.8.
+ const IN_VIEW = { lat: 47.4, lon: -122.4 };
+ const OFF_SCREEN = { lat: 40.0, lon: -100.0 };
+
+ it("spends the request without moving for an aircraft already in view", () => {
+ const { map } = renderLayer();
+ map.containerHeight = 800;
+ act(() => snapshot(IN_VIEW));
+
+ act(() => focusAircraftOnMap("acc31a", { onlyIfOffscreen: true }));
+
+ expect(map.easeTo).not.toHaveBeenCalled();
+ expect(useMapFocusRequestStore.getState().icao).toBeNull();
+ expect(useLiveAircraftStore.getState().selectedIcao).toBe("acc31a");
+ });
+
+ it("moves for an aircraft outside the viewport", () => {
+ const { map } = renderLayer();
+ map.containerHeight = 800;
+ act(() => snapshot(OFF_SCREEN));
+
+ act(() => focusAircraftOnMap("acc31a", { onlyIfOffscreen: true }));
+
+ expect(map.easeTo).toHaveBeenCalledExactlyOnceWith({
+ center: [-100.0, 40.0],
+ });
+ });
+
+ it("treats the part of the map under the phone sheet as off screen", () => {
+ vi.stubGlobal(
+ "matchMedia",
+ (query: string) =>
+ ({
+ matches: true,
+ media: query,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ }) as unknown as MediaQueryList,
+ );
+ const { map } = renderLayer();
+ map.containerHeight = 800;
+ // Latitude 47.1 projects to y = 700 of 800: on the map, under the sheet.
+ act(() => snapshot({ lat: 47.1, lon: -122.4 }));
+
+ act(() => focusAircraftOnMap("acc31a", { onlyIfOffscreen: true }));
+
+ expect(map.easeTo).toHaveBeenCalledExactlyOnceWith({
+ center: [-122.4, 47.1],
+ offset: [0, -200],
+ });
+ });
+
+ it("always moves for a plain request, even to an aircraft in view", () => {
+ const { map } = renderLayer();
+ map.containerHeight = 800;
+ act(() => snapshot(IN_VIEW));
+
+ act(() => focusAircraftOnMap("acc31a"));
+
+ expect(map.easeTo).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("useFocusSelectedAircraft", () => {
it("eases to a positioned aircraft once and spends the request", () => {
const { map } = renderLayer();
diff --git a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
index 35f2e56e..809b1d88 100644
--- a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
+++ b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
@@ -30,6 +30,11 @@
* receiver in the top half too), surviving the sheet closing and even a
* crossing to the desktop layout. An offset applies to this move only.
*
+ * A request made `onlyIfOffscreen` (keyboard cycling, the Interesting list)
+ * is spent without moving when the aircraft is already inside the visible
+ * map (on the phone, the part above the sheet), so stepping through
+ * aircraft that are in view never lurches the camera.
+ *
* A pending request yields to the user: a pan or zoom they make while waiting
* cancels it, so an aircraft that only decodes a position minutes later does
* not yank a map they have since moved somewhere else. Only user-initiated
@@ -40,7 +45,7 @@
* through `getState()` from subscriptions.
*/
-import type { MapLibreEvent } from "maplibre-gl";
+import type { Map as MapLibreMap, MapLibreEvent } from "maplibre-gl";
import { useEffect, useRef } from "react";
import { useIsMobile } from "@/components/shell/useIsMobile";
@@ -58,6 +63,34 @@ type MoveStartEvent = MapLibreEvent<
* (half) snap — `SNAP_HEIGHT_CLASS.half` in `AircraftDetailPanel`. */
const PHONE_SHEET_SHARE = 0.5;
+/** Pixels kept clear at each edge: an aircraft hugging the border counts as
+ * off screen, since its marker and label would be clipped. */
+const VISIBLE_MARGIN_PX = 24;
+
+/**
+ * Whether `center` is inside the part of the map the user can actually see
+ * (issue #362). On the phone layout the detail sheet covers the bottom
+ * `PHONE_SHEET_SHARE` of the map, so only the upper part counts, the same
+ * region the focus move itself centres within.
+ */
+function isInView(
+ map: MapLibreMap,
+ center: [number, number],
+ isMobile: boolean,
+): boolean {
+ const container = map.getContainer();
+ const width = container.clientWidth;
+ const height = container.clientHeight;
+ const visibleHeight = isMobile ? height * (1 - PHONE_SHEET_SHARE) : height;
+ const point = map.project(center);
+ return (
+ point.x >= VISIBLE_MARGIN_PX &&
+ point.x <= width - VISIBLE_MARGIN_PX &&
+ point.y >= VISIBLE_MARGIN_PX &&
+ point.y <= visibleHeight - VISIBLE_MARGIN_PX
+ );
+}
+
export function useFocusSelectedAircraft(): void {
const { map } = useMapInstance();
const isMobile = useIsMobile();
@@ -107,8 +140,13 @@ export function useFocusSelectedAircraft(): void {
if (target === null) {
return;
}
+ const onlyIfOffscreen =
+ useMapFocusRequestStore.getState().onlyIfOffscreen;
endRequest();
const center: [number, number] = [target.lon, target.lat];
+ if (onlyIfOffscreen && isInView(map, center, isMobileRef.current)) {
+ return;
+ }
if (isMobileRef.current) {
const height = map.getContainer().clientHeight;
map.easeTo({
diff --git a/frontend/src/features/map/store/useMapFocusRequestStore.ts b/frontend/src/features/map/store/useMapFocusRequestStore.ts
index ad93803f..73594dfe 100644
--- a/frontend/src/features/map/store/useMapFocusRequestStore.ts
+++ b/frontend/src/features/map/store/useMapFocusRequestStore.ts
@@ -26,17 +26,33 @@ import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircr
interface MapFocusRequestState {
/** The ICAO the map should bring into view, or `null` for no request. */
icao: string | null;
- requestFocus: (icao: string) => void;
+ /**
+ * `true` for a request that should only move the camera when the aircraft
+ * is outside the visible map (issue #362): keyboard cycling and the
+ * Interesting list, where an always-recentre would lurch the map on every
+ * keypress or click even for an aircraft already in plain view.
+ */
+ onlyIfOffscreen: boolean;
+ requestFocus: (icao: string, options?: FocusRequestOptions) => void;
clearFocus: () => void;
}
+export interface FocusRequestOptions {
+ /** Move the camera only if the aircraft is not already in view. */
+ onlyIfOffscreen?: boolean;
+}
+
export const useMapFocusRequestStore = create((set) => ({
icao: null,
- requestFocus: (icao) => set({ icao }),
+ onlyIfOffscreen: false,
+ requestFocus: (icao, options) =>
+ set({ icao, onlyIfOffscreen: options?.onlyIfOffscreen === true }),
// Returning `state` when there is nothing to clear keeps the map's
// subscription from re-running for a no-op.
clearFocus: () =>
- set((state) => (state.icao === null ? state : { icao: null })),
+ set((state) =>
+ state.icao === null ? state : { icao: null, onlyIfOffscreen: false },
+ ),
}));
/**
@@ -46,7 +62,10 @@ export const useMapFocusRequestStore = create((set) => ({
* anything but the current selection (that is how a request made stale by a
* later click is discarded), so the opposite order would discard this one.
*/
-export function focusAircraftOnMap(icao: string): void {
+export function focusAircraftOnMap(
+ icao: string,
+ options?: FocusRequestOptions,
+): void {
useLiveAircraftStore.getState().selectAircraft(icao);
- useMapFocusRequestStore.getState().requestFocus(icao);
+ useMapFocusRequestStore.getState().requestFocus(icao, options);
}
diff --git a/frontend/src/lib/shortcuts/useKeyboardShortcuts.test.tsx b/frontend/src/lib/shortcuts/useKeyboardShortcuts.test.tsx
index f847510e..0f7f1b68 100644
--- a/frontend/src/lib/shortcuts/useKeyboardShortcuts.test.tsx
+++ b/frontend/src/lib/shortcuts/useKeyboardShortcuts.test.tsx
@@ -214,6 +214,47 @@ describe("useKeyboardShortcuts", () => {
expect(useLiveAircraftStore.getState().selectedIcao).toBe("bbbbbb");
});
+ it("cycling pans only to an aircraft outside the viewport (issue #362)", () => {
+ renderApp("/");
+ const map = getLastMockMap();
+ map.containerHeight = 800;
+ const inView = { lat: 47.4, lon: -122.4 };
+ const offScreen = { lat: 40.0, lon: -100.0 };
+ act(() => {
+ useLiveAircraftStore.getState().applySnapshot(
+ {
+ aircraft: [
+ makeAircraft({
+ icao: "aaaaaa",
+ position: inView,
+ interesting: { severity: "high", reasons: ["Rule: Military"] },
+ }),
+ makeAircraft({
+ icao: "bbbbbb",
+ position: offScreen,
+ interesting: {
+ severity: "critical",
+ reasons: ["Emergency squawk 7700"],
+ },
+ }),
+ ],
+ receiver: null,
+ },
+ Date.now(),
+ );
+ });
+
+ // Critical "bbbbbb" is first and far off screen: the map follows.
+ pressKey("]");
+ expect(useLiveAircraftStore.getState().selectedIcao).toBe("bbbbbb");
+ expect(map.easeTo).toHaveBeenCalledTimes(1);
+
+ // "aaaaaa" is already in view: selected, but no lurch.
+ pressKey("]");
+ expect(useLiveAircraftStore.getState().selectedIcao).toBe("aaaaaa");
+ expect(map.easeTo).toHaveBeenCalledTimes(1);
+ });
+
it("recentres the real Live Map on 'H', end to end through RecenterButton", async () => {
renderApp("/");
// `MapLibreMap` sets the map instance into context synchronously in its
diff --git a/frontend/src/lib/shortcuts/useKeyboardShortcuts.ts b/frontend/src/lib/shortcuts/useKeyboardShortcuts.ts
index 083936c0..60ba95d6 100644
--- a/frontend/src/lib/shortcuts/useKeyboardShortcuts.ts
+++ b/frontend/src/lib/shortcuts/useKeyboardShortcuts.ts
@@ -44,6 +44,7 @@ import { orderInterestingAircraft } from "@/features/interesting/lib/ordering";
import { useLiveAircraftStore } from "@/features/map/aircraft/store/useLiveAircraftStore";
import { useMeasureStore } from "@/features/map/measure/useMeasureStore";
import { useMapCenterRequestStore } from "@/features/map/store/useMapCenterRequestStore";
+import { focusAircraftOnMap } from "@/features/map/store/useMapFocusRequestStore";
import { useMapConfigStore } from "@/features/map/store/useMapConfigStore";
import { useOverlayVisibilityStore } from "@/features/map/store/useOverlayVisibilityStore";
import { useOverheadStore } from "@/features/overhead/useOverheadStore";
@@ -92,7 +93,7 @@ function stepInterestingSelection(direction: 1 | -1): void {
: (currentIndex + direction + rows.length) % rows.length;
const next = rows[nextIndex];
if (next) {
- liveState.selectAircraft(next.aircraft.icao);
+ focusAircraftOnMap(next.aircraft.icao, { onlyIfOffscreen: true });
}
}
diff --git a/frontend/src/test/maplibreGlMock.ts b/frontend/src/test/maplibreGlMock.ts
index a31f0d02..f274995f 100644
--- a/frontend/src/test/maplibreGlMock.ts
+++ b/frontend/src/test/maplibreGlMock.ts
@@ -229,8 +229,25 @@ export class MapLibreMockMap {
* out, so tests that care set this directly. */
containerHeight = 0;
- getContainer(): { clientHeight: number } {
- return { clientHeight: this.containerHeight };
+ /** `getContainer().clientWidth`'s value (issue #362's visibility test). */
+ containerWidth = 1000;
+
+ getContainer(): { clientHeight: number; clientWidth: number } {
+ return {
+ clientHeight: this.containerHeight,
+ clientWidth: this.containerWidth,
+ };
+ }
+
+ /** `project([lon, lat])`: a linear map of `bounds` onto the container, y
+ * growing southwards like real screen pixels (issue #362's visibility
+ * test). Good enough for in/out-of-view decisions. */
+ project(lngLat: [number, number]): { x: number; y: number } {
+ const { west, south, east, north } = this.bounds;
+ return {
+ x: ((lngLat[0] - west) / (east - west)) * this.containerWidth,
+ y: ((north - lngLat[1]) / (north - south)) * this.containerHeight,
+ };
}
isStyleLoaded(): boolean {
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 2b2bdf63..d8f9f17f 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3811,6 +3811,37 @@ slices:
risk_level: high
notes: "Follows #360 (fixed by slice 125, PR #363). The owner approved the permanent deletion of this history."
+ - id: "129"
+ title: "Live Map: every selection path brings the aircraft into view"
+ phase: 9
+ branch: "129-focus-every-selection-path"
+ status: planned
+ depends_on: ["124"]
+ objective: "Make the remaining ways of selecting an aircraft (an Interesting-panel row, keyboard cycling, a ?selected= deep link) bring it into view on the Live Map through slice 124's one-shot focus request, without lurching the camera for an aircraft already in plain view."
+ scope:
+ - "useMapFocusRequestStore: requestFocus/focusAircraftOnMap take an onlyIfOffscreen option; useFocusSelectedAircraft spends such a request without moving when the aircraft projects inside the visible map (the part above the half-open sheet on the phone layout)"
+ - "keyboard cycling ([ and ]) and Interesting-panel rows request focus onlyIfOffscreen; the ?selected= mount effect in useSelectionUrlSync requests a plain focus, skipNextWrite untouched"
+ - "a plain click on a map marker stays select-only"
+ out_of_scope:
+ - "continuous aircraft-follow (deferred, SPEC §79)"
+ - "any change to how slice 124's phone offset or reduced-motion behaviour work"
+ acceptance_criteria:
+ - "selecting an off-screen aircraft from the Interesting list or by keyboard cycling eases the map to it; selecting one already in view does not move the map"
+ - "opening a ?selected= link selects the aircraft and eases the map to it once the map, its record and a position are available"
+ required_tests:
+ - "vitest: useFocusSelectedAircraft onlyIfOffscreen (in view, off screen, phone sheet), InterestingPanel, useKeyboardShortcuts cycling, useSelectionUrlSync"
+ - "e2e (demo data): a ?selected= deep link centres the map on the aircraft"
+ expected_artifacts:
+ - frontend/src/features/map/store/useMapFocusRequestStore.ts
+ - frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
+ - frontend/src/features/interesting/InterestingPanel.tsx
+ - frontend/src/lib/shortcuts/useKeyboardShortcuts.ts
+ - frontend/src/features/filters/hooks/useSelectionUrlSync.ts
+ - e2e/tests/04-selected-deep-link-focus.spec.ts
+ preferred_agent: sonnet
+ risk_level: low
+ notes: "Closes #362. Follow-up to slice 124 (#358)."
+
# Parallelization guide (dependency-derived; Fable owns merge order). Slices adding
From 6dcbdedec3823c18900723dc241a6cc5dd59e933 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:47:30 -0500
Subject: [PATCH 05/33] docs(roadmap): mark slice 129 merged
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
planning/roadmap.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index d8f9f17f..caeb1d01 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3815,7 +3815,7 @@ slices:
title: "Live Map: every selection path brings the aircraft into view"
phase: 9
branch: "129-focus-every-selection-path"
- status: planned
+ status: merged
depends_on: ["124"]
objective: "Make the remaining ways of selecting an aircraft (an Interesting-panel row, keyboard cycling, a ?selected= deep link) bring it into view on the Live Map through slice 124's one-shot focus request, without lurching the camera for an aircraft already in plain view."
scope:
From 1ee063fe0e018c1c2682a773ad97067aafc67273 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:50:27 -0500
Subject: [PATCH 06/33] fix(feeders): read readsb's lossy Beast-output warning
as degraded, not down
readsb's "Bad connection, dropping data (connection lost N% of data)"
warning is logged on an open Beast output, but beast_connected() took every
non-"Connection established" line as a disconnect, so a first read after a
restart reported both ultrafeeder feeds down for days (#369).
Matched lines are now classified from readsb's own wording (net_io.c at
wiedehopf/readsb bc57f2dd): established, closed (remote disconnect, send
error/timeout, heartbeat reconnect, failed or timed-out connect), lossy, or
unrecognised. Only established/closed lines set connected and since; a
lossy line reports N (cumulative since the connection opened) as
detail.adsb_out_loss_pct and degrades the feed while it is at most 15 min
old with N >= 1.0%; an unrecognised line keeps the verdict and is warned
about once.
Refs #369
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
backend/src/flightsite/feeders/ultrafeeder.py | 256 +++++++++++++++---
.../feeders/fixtures/readsb_beast_lines.tsv | 25 ++
.../tests/feeders/fixtures/ultrafeeder.log | 2 +-
backend/tests/feeders/test_vendors.py | 251 +++++++++++++++++
docs/API.md | 8 +
planning/roadmap.yaml | 30 ++
6 files changed, 531 insertions(+), 41 deletions(-)
create mode 100644 backend/tests/feeders/fixtures/readsb_beast_lines.tsv
diff --git a/backend/src/flightsite/feeders/ultrafeeder.py b/backend/src/flightsite/feeders/ultrafeeder.py
index 0605126e..a49e3f4c 100644
--- a/backend/src/flightsite/feeders/ultrafeeder.py
+++ b/backend/src/flightsite/feeders/ultrafeeder.py
@@ -30,15 +30,43 @@
ADS-B out — from ultrafeeder's logs, when the Docker socket is set
-------------------------------------------------------------------
-The Beast output's state is logged only on a transition —
-``BeastReduce TCP output: Connection established: … port `` or a
-disconnect line for the same host and port — so "connected" means "the latest
-line for this host and port says established". The first read goes a long way
-back (:data:`FIRST_READ_TAIL` lines, filtered as they stream) to find the last
-transition; later reads only ask for what is new since the previous one. With
-no socket, ``adsb_out`` is ``null`` and the feeder is judged on MLAT alone.
-The ``/run/adsbexchange-stats`` documents are never read: they carry the
-feeder's UUID.
+readsb logs a Beast output (``BeastReduce TCP output: …``) only when
+something happens to it, and the probe sorts every line naming this host and
+port into one of three kinds (:func:`classify_beast_line`; the wording is
+readsb's ``net_io.c``, wiedehopf/readsb commit
+``bc57f2ddd83016e5628f63012eea1a51155623a5``):
+
+``established``
+ ``Connection established: … port ``: the connection opened.
+``closed``
+ a real close or failure: ``Remote server disconnected``, ``Send Error``,
+ ``Couldn't send any data … disconnecting``, ``send() weirdness``,
+ ``No data or heartbeat received … reconnecting``, ``Socket Error``, and
+ the connect attempts ``Connection to … port failed …`` /
+ ``… timed out.``
+``lossy``
+ `` port : Bad connection, dropping data (connection lost N% of
+ data) (suppress msg for 300 s)``. A warning on a connection that stays
+ open: readsb could not write everything and discards half the output for
+ two seconds. ``N`` is cumulative since the connection opened (bytes
+ queued over bytes offered, both zeroed when the client is created), and
+ the line is printed when dropping starts, at most once per 300 s and
+ never in the connection's first 10 s.
+
+Only ``established`` and ``closed`` lines are state: "connected" means "the
+newest of them says established", and ``since`` is that line's time. A
+``lossy`` line never moves the state; it overlays it. While the connection is
+up and the newest lossy line of *this* connection is at most
+:data:`LOSSY_RECENT_MS` old with ``N`` at least :data:`LOSSY_DEGRADED_PCT`,
+the feeder reads ``degraded`` ("ADS-B output dropping data (N% lost)");
+otherwise it stays ``up``. Either way ``detail.adsb_out_loss_pct`` carries
+``N``. A matched line of none of these kinds moves nothing and is logged as a
+warning, once. The first read goes a long way back (:data:`FIRST_READ_TAIL`
+lines, filtered as they stream) to find the newest state line; with none in
+the tail, ``connected`` is unknown. Later reads only ask for what is new
+since the previous one. With no socket, ``adsb_out`` is ``null`` and the
+feeder is judged on MLAT alone. The ``/run/adsbexchange-stats`` documents
+are never read: they carry the feeder's UUID.
A silent log is not evidence (slice 101, issue #276)
-----------------------------------------------------
@@ -61,7 +89,11 @@
from __future__ import annotations
+import math
+import re
from collections.abc import Callable
+from dataclasses import dataclass
+from enum import StrEnum
from typing import Any, Final
import httpx
@@ -102,10 +134,19 @@
#: would otherwise last until the next restart.
LOG_SILENT_AFTER_MS: Final = 60 * 60 * 1000
+#: A lossy line older than this no longer degrades the feeder. readsb repeats
+#: the warning every 300 s while the trouble lasts, so a persisting problem
+#: always has a line this recent.
+LOSSY_RECENT_MS: Final = 15 * 60 * 1000
+
+#: The cumulative loss (percent of the connection's output) from which a
+#: recent lossy line degrades the feeder. Below it, readsb's routine ``0.0%``
+#: warnings among them, the feeder stays up.
+LOSSY_DEGRADED_PCT: Final = 1.0
+
logger = structlog.get_logger(__name__)
_BEAST_MARKER: Final = "BeastReduce TCP output"
-_ESTABLISHED: Final = "Connection established"
#: Values mlat-client uses for "never" and plausibility floors for epoch values.
_EPOCH_FLOOR_S: Final = 1_000_000_000
@@ -150,9 +191,59 @@ def match(line: str) -> bool:
return match
-def beast_connected(line: str) -> bool:
- """Whether a matched transition line is the connection opening."""
- return _ESTABLISHED in line
+class BeastLineKind(StrEnum):
+ """What one matched Beast-output line says about the connection."""
+
+ ESTABLISHED = "established"
+ CLOSED = "closed"
+ LOSSY = "lossy"
+ UNRECOGNISED = "unrecognised"
+
+
+# readsb's own wording, from net_io.c at wiedehopf/readsb commit
+# bc57f2ddd83016e5628f63012eea1a51155623a5 (2026-11-27): checkServiceConnected,
+# serviceConnect, serviceReconnectCallback, flushClient, dropHalfUntil and
+# readClient. Each line starts ": ".
+_ESTABLISHED: Final = "Connection established:"
+#: Lines printed as an open connection is closed (modesCloseClient follows).
+_CLOSED_MARKERS: Final = (
+ "Remote server disconnected:",
+ "Send Error:",
+ "send() weirdness:",
+ "(Insufficient bandwidth?): disconnecting:",
+ "reconnecting:", # "No data or heartbeat received for N seconds, reconnecting:"
+ "Socket Error:", # --debug net only
+)
+#: A connect attempt that did not open: "failed: …", "failed (n): …",
+#: "failed n times, suppressing …" and "timed out.".
+_CONNECT_FAILED: Final = re.compile(r"Connection to .* port \d+ (?:failed|timed out)")
+#: dropHalfUntil: " port : Bad connection, dropping data
+#: (connection lost %4.1f%% of data) (suppress msg for %d s)".
+_LOSSY: Final = re.compile(r"Bad connection, dropping data \(connection lost\s*([^%)]*)%")
+
+
+def classify_beast_line(line: str) -> tuple[BeastLineKind, float | None]:
+ """The kind of one matched Beast-output line, and its loss % when lossy."""
+ if _ESTABLISHED in line:
+ return BeastLineKind.ESTABLISHED, None
+ lossy = _LOSSY.search(line)
+ if lossy is not None:
+ try:
+ pct = float(lossy.group(1))
+ except ValueError:
+ return BeastLineKind.LOSSY, None
+ return BeastLineKind.LOSSY, pct if math.isfinite(pct) else None
+ if any(marker in line for marker in _CLOSED_MARKERS) or _CONNECT_FAILED.search(line):
+ return BeastLineKind.CLOSED, None
+ return BeastLineKind.UNRECOGNISED, None
+
+
+@dataclass(frozen=True, slots=True)
+class _Loss:
+ """The newest lossy line seen for the current connection."""
+
+ ts_ms: int | None
+ pct: float | None
class UltrafeederProbe:
@@ -167,8 +258,10 @@ class UltrafeederProbe:
"_host",
"_log_cursor_s",
"_log_newest_ms",
+ "_loss",
"_mlat_port",
"_name",
+ "_unrecognised_seen",
"_url",
"_zero_peer_polls",
)
@@ -200,6 +293,10 @@ def __init__(
self._log_cursor_s: int | None = None
#: When the container last logged anything, matched or not.
self._log_newest_ms: int | None = None
+ self._loss: _Loss | None = None
+ #: Unrecognised lines already warned about, by (text, time): the read
+ #: overlap re-reads the previous read's last seconds.
+ self._unrecognised_seen: set[tuple[str, int | None]] = set()
@property
def name(self) -> str:
@@ -255,36 +352,104 @@ async def _read_adsb_out(self, now_ms: int) -> tuple[bool, bool]:
if lines is None:
return False, True
self._log_cursor_s = now_s
- if lines:
- latest = lines[-1]
- since = latest.ts_ms
- current = self._adsb_out
- applied = (
- current is None
- or since is None
- or current.since_ms is None
- or (since >= current.since_ms)
- )
- if applied:
- self._adsb_out = AdsbOutStatus(
- connected=beast_connected(latest.text), since_ms=since
- )
- # The evidence behind every verdict, on the record (issue #276).
- logger.info(
- "feeder_adsb_out_transition",
- feeder=self._name,
- container=self._container,
- read="first" if first else "incremental",
- matched=len(lines),
- line_ts_ms=since,
- line=latest.text,
- connected=beast_connected(latest.text),
- applied=applied,
- )
+ state_line: LogLine | None = None
+ lossy_line: tuple[LogLine, float | None] | None = None
+ seen: set[tuple[str, int | None]] = set()
+ for line in lines:
+ kind, pct = classify_beast_line(line.text)
+ if kind is BeastLineKind.LOSSY:
+ lossy_line = (line, pct)
+ elif kind is BeastLineKind.UNRECOGNISED:
+ key = (line.text, line.ts_ms)
+ if key not in self._unrecognised_seen:
+ logger.warning(
+ "feeder_adsb_out_unrecognised_line",
+ feeder=self._name,
+ container=self._container,
+ line_ts_ms=line.ts_ms,
+ line=line.text,
+ )
+ seen.add(key)
+ else:
+ state_line = line
+ # A lossy line before a state line belongs to an earlier connection.
+ lossy_line = None
+ self._unrecognised_seen = seen
+ if state_line is not None:
+ self._apply_state_line(state_line, first=first, matched=len(lines))
elif self._adsb_out is None:
self._adsb_out = AdsbOutStatus(connected=None, since_ms=None)
+ if lossy_line is not None:
+ self._apply_lossy_line(*lossy_line, first=first, matched=len(lines))
return True, False
+ def _apply_state_line(self, line: LogLine, *, first: bool, matched: int) -> None:
+ """Take an established/closed line as the state unless an applied one is newer."""
+ since = line.ts_ms
+ connected = classify_beast_line(line.text)[0] is BeastLineKind.ESTABLISHED
+ current = self._adsb_out
+ applied = (
+ current is None
+ or since is None
+ or current.since_ms is None
+ or (since >= current.since_ms)
+ )
+ if applied:
+ self._adsb_out = AdsbOutStatus(connected=connected, since_ms=since)
+ loss = self._loss
+ if loss is not None and (since is None or loss.ts_ms is None or loss.ts_ms < since):
+ # That loss figure was the previous connection's.
+ self._loss = None
+ # The evidence behind every verdict, on the record (issue #276).
+ logger.info(
+ "feeder_adsb_out_transition",
+ feeder=self._name,
+ container=self._container,
+ read="first" if first else "incremental",
+ matched=matched,
+ kind=str(BeastLineKind.ESTABLISHED if connected else BeastLineKind.CLOSED),
+ line_ts_ms=since,
+ line=line.text,
+ connected=connected,
+ applied=applied,
+ )
+
+ def _apply_lossy_line(
+ self, line: LogLine, pct: float | None, *, first: bool, matched: int
+ ) -> None:
+ """Note a lossy line of the current connection; it never moves the state."""
+ ts = line.ts_ms
+ current = self._adsb_out
+ since = current.since_ms if current is not None else None
+ held = self._loss
+ applied = (since is None or ts is None or ts >= since) and (
+ held is None or held.ts_ms is None or ts is None or ts >= held.ts_ms
+ )
+ if applied:
+ self._loss = _Loss(ts_ms=ts, pct=pct)
+ logger.info(
+ "feeder_adsb_out_transition",
+ feeder=self._name,
+ container=self._container,
+ read="first" if first else "incremental",
+ matched=matched,
+ kind=str(BeastLineKind.LOSSY),
+ line_ts_ms=ts,
+ line=line.text,
+ loss_pct=pct,
+ applied=applied,
+ )
+
+ def _loss_overlay(self, now_ms: int, connected: bool | None) -> tuple[float | None, str | None]:
+ """The current connection's loss %, and the degraded note when it counts."""
+ loss = self._loss
+ if connected is not True or loss is None:
+ return None, None
+ recent = loss.ts_ms is not None and now_ms - loss.ts_ms <= LOSSY_RECENT_MS
+ if recent and loss.pct is not None and loss.pct >= LOSSY_DEGRADED_PCT:
+ return loss.pct, f"ADS-B output dropping data ({loss.pct:.1f}% lost)"
+ return loss.pct, None
+
def _reported_adsb_out(self, now_ms: int) -> tuple[AdsbOutStatus | None, str | None]:
"""The ADS-B out state to offer, and a note when it cannot be one.
@@ -308,11 +473,14 @@ async def probe(self, now_ms: int) -> ProbeResult:
via_docker, docker_failed = await self._read_adsb_out(now_ms)
adsb_out, silent_note = self._reported_adsb_out(now_ms) if via_docker else (None, None)
connected = adsb_out.connected if adsb_out is not None else None
+ loss_pct, lossy_note = self._loss_overlay(now_ms, connected)
detail: dict[str, DetailValue] = {
"host": self._host,
"outlier_pct": outliers,
}
+ if loss_pct is not None:
+ detail["adsb_out_loss_pct"] = loss_pct
metrics: dict[str, MetricValue] = {
"mlat_peers": mlat.peers if mlat is not None else None,
"good_sync_pct": mlat.good_sync_pct if mlat is not None else None,
@@ -332,6 +500,11 @@ async def probe(self, now_ms: int) -> ProbeResult:
state, message = FeederState.DEGRADED, mlat_message
else:
state, message = mlat_state, mlat_message
+ if lossy_note is not None:
+ # Lossy degrades, never downs: the connection is open (issue #369).
+ if state is FeederState.UP:
+ state = FeederState.DEGRADED
+ message = lossy_note if message is None else f"{message}; {lossy_note}"
if docker_failed and message is None:
message = "Docker socket unreachable; ADS-B output not observed"
if silent_note is not None:
@@ -359,12 +532,15 @@ async def probe(self, now_ms: int) -> ProbeResult:
__all__ = [
"FIRST_READ_TAIL",
"LOG_SILENT_AFTER_MS",
+ "LOSSY_DEGRADED_PCT",
+ "LOSSY_RECENT_MS",
"MLAT_STALE_AFTER_MS",
"NEXT_READ_TAIL",
"ZERO_PEER_TOLERANCE",
+ "BeastLineKind",
"UltrafeederProbe",
- "beast_connected",
"beast_line_matcher",
+ "classify_beast_line",
"mlat_stats_path",
"parse_mlat_stats",
]
diff --git a/backend/tests/feeders/fixtures/readsb_beast_lines.tsv b/backend/tests/feeders/fixtures/readsb_beast_lines.tsv
new file mode 100644
index 00000000..c8b45663
--- /dev/null
+++ b/backend/tests/feeders/fixtures/readsb_beast_lines.tsv
@@ -0,0 +1,25 @@
+# readsb Beast-output log lines, one per kind the ultrafeeder probe tells apart (issue #369).
+# Format: .
+# Wording from readsb net_io.c at wiedehopf/readsb commit bc57f2ddd83016e5628f63012eea1a51155623a5
+# (2026-11-27): checkServiceConnected, serviceConnect, serviceReconnectCallback, flushClient,
+# dropHalfUntil, readClient. The first lossy line is verbatim from the reference install's
+# ultrafeeder log (2026-11-28); the first established line has the shape it logged that day.
+established [2026-11-28 13:48:02.113][readsb] BeastReduce TCP output: Connection established: feed.adsbexchange.com (1.2.3.4) port 30004
+established [readsb] BeastReduce TCP output: Connection established: feed.adsbexchange.com (1.2.3.4) port 30004 (sent UUID)
+established [readsb] BeastReduce TCP output: Connection established: feed.adsbexchange.com port 30004
+closed [readsb] BeastReduce TCP output: Remote server disconnected: feed.adsbexchange.com port 30004 (fd 12, SendQ 0, RecvQ 0)
+closed [readsb] BeastReduce TCP output: Send Error: Connection reset by peer: feed.adsbexchange.com port 30004 (fd 12, SendQ 1024, RecvQ 0)
+closed [readsb] BeastReduce TCP output: Couldn't send any data for 5.00s (Insufficient bandwidth?): disconnecting: feed.adsbexchange.com port 30004 (fd 12, SendQ 65536)
+closed [readsb] BeastReduce TCP output: send() weirdness: bytesWritten > toWrite: Success: feed.adsbexchange.com port 30004 (fd 12, SendQ 10, RecvQ 0)
+closed [readsb] BeastReduce TCP output: No data or heartbeat received for 60 seconds, reconnecting: feed.adsbexchange.com port 30004
+closed [readsb] BeastReduce TCP output: Socket Error: Connection timed out: feed.adsbexchange.com port 30004 (fd 12, SendQ 0, RecvQ 0)
+closed [readsb] BeastReduce TCP output: Connection to feed.adsbexchange.com (1.2.3.4) port 30004 failed (1): 111 (Connection refused)
+closed [readsb] BeastReduce TCP output: Connection to feed.adsbexchange.com (1.2.3.4) port 30004 failed: Network is unreachable
+closed [readsb] BeastReduce TCP output: Connection to feed.adsbexchange.com (1.2.3.4) port 30004 timed out.
+closed [readsb] BeastReduce TCP output: Connection to feed.adsbexchange.com port 30004 failed 10 times, suppressing most error messages until connection succeeds
+lossy [2026-11-28 20:33:43.689][readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Bad connection, dropping data (connection lost 0.0% of data) (suppress msg for 300 s)
+lossy [readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Bad connection, dropping data (connection lost 12.5% of data) (suppress msg for 300 s)
+lossy [readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Bad connection, dropping data (connection lost 100.0% of data) (suppress msg for 300 s)
+unrecognised [readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Ignoring this DNS reply: 0.0.0.0
+unrecognised [readsb] BeastReduce TCP output: Attempting connection to feed.adsbexchange.com (1.2.3.4) port 30004 ...
+unrecognised [readsb] BeastReduce TCP output: Unable to set keepalive: connection to feed.adsbexchange.com port 30004 ...
diff --git a/backend/tests/feeders/fixtures/ultrafeeder.log b/backend/tests/feeders/fixtures/ultrafeeder.log
index 4cb4f1b8..c8d3c085 100644
--- a/backend/tests/feeders/fixtures/ultrafeeder.log
+++ b/backend/tests/feeders/fixtures/ultrafeeder.log
@@ -2,5 +2,5 @@
2026-09-20T09:00:01.500000000Z [readsb] BeastReduce TCP output: Connection established: feed.aerodatabox.com (5.6.7.8) port 30004
2026-09-20T09:00:02.000000000Z [mlat-client][feed.adsbexchange.com] peer_count: 14
2026-09-21T12:10:00.000000000Z [readsb] BeastReduce TCP output: Remote server disconnected: feed.aerodatabox.com (5.6.7.8) port 30004
-2026-09-21T12:10:30.000000000Z [readsb] BeastReduce TCP output: Connection refused: feed.aerodatabox.com (5.6.7.8) port 30004
+2026-09-21T12:10:30.000000000Z [readsb] BeastReduce TCP output: Connection to feed.aerodatabox.com (5.6.7.8) port 30004 failed (1): 111 (Connection refused)
2026-09-21T13:40:00.000000000Z [readsb] stats: 31234 messages in the last minute
diff --git a/backend/tests/feeders/test_vendors.py b/backend/tests/feeders/test_vendors.py
index 4c2a5f1f..5c7052ee 100644
--- a/backend/tests/feeders/test_vendors.py
+++ b/backend/tests/feeders/test_vendors.py
@@ -30,8 +30,13 @@
from flightsite.feeders.readsb import ReadsbProbe
from flightsite.feeders.ultrafeeder import (
LOG_SILENT_AFTER_MS,
+ LOSSY_DEGRADED_PCT,
+ LOSSY_RECENT_MS,
ZERO_PEER_TOLERANCE,
+ BeastLineKind,
UltrafeederProbe,
+ beast_line_matcher,
+ classify_beast_line,
mlat_stats_path,
parse_mlat_stats,
)
@@ -610,6 +615,252 @@ async def test_every_transition_acted_on_is_logged_with_its_evidence(
assert events[1]["matched"] == 1
+# ------------------------------------- ultrafeeder: kinds of Beast-output line
+
+
+def beast_fixture() -> list[tuple[BeastLineKind, str]]:
+ """readsb's own wording per kind, from ``readsb_beast_lines.tsv`` (issue #369)."""
+ rows = []
+ for row in load_lines("readsb_beast_lines.tsv"):
+ if row and not row.startswith("#"):
+ kind, text = row.split("\t", 1)
+ rows.append((BeastLineKind(kind), text))
+ return rows
+
+
+@pytest.mark.parametrize(("kind", "text"), beast_fixture())
+def test_each_readsb_line_is_classified_by_its_kind(kind: BeastLineKind, text: str) -> None:
+ assert beast_line_matcher(ADSBX, 30004)(text)
+ assert classify_beast_line(text)[0] is kind
+
+
+def test_the_loss_percentage_is_read_from_a_lossy_line() -> None:
+ lossy = [text for kind, text in beast_fixture() if kind is BeastLineKind.LOSSY]
+
+ assert [classify_beast_line(text)[1] for text in lossy] == [0.0, 12.5, 100.0]
+ assert classify_beast_line(lossy[0].replace(" 0.0%", "-nan%")) == (BeastLineKind.LOSSY, None)
+
+
+def lossy_line(host: str, pct: float) -> str:
+ return (
+ f"[readsb] BeastReduce TCP output: {host} port 30004: Bad connection, dropping data"
+ f" (connection lost {pct:4.1f}% of data) (suppress msg for 300 s)"
+ )
+
+
+def at(iso: str, text: str) -> str:
+ """A log line Docker stamped at an absolute UTC instant."""
+ return f"{iso.removesuffix('Z')}000000Z {text}"
+
+
+def ms(iso: str) -> int:
+ from datetime import datetime
+
+ return int(datetime.fromisoformat(iso).timestamp() * 1000)
+
+
+#: The reference install's log at the v0.17.0 upgrade (issue #369): each output
+#: opened on 2026-11-28, warned once that evening at 0.0% and stayed open; the
+#: backend restarted on 2026-11-30 and its first read took the warning for a close.
+FERMI_NOW = "2026-11-30T13:25:39.000Z"
+FERMI_LOG = [
+ at(
+ "2026-11-28T13:48:02.113Z",
+ "[2026-11-28 13:48:02.113][readsb] "
+ + ESTABLISHED.format(host=ADSBX).removeprefix("[readsb] "),
+ ),
+ at("2026-11-28T13:48:02.540Z", ESTABLISHED.format(host=ADB)),
+ at(
+ "2026-11-28T20:33:43.689Z",
+ "[2026-11-28 20:33:43.689][readsb] BeastReduce TCP output:"
+ " feed.adsbexchange.com port 30004: Bad connection, dropping data"
+ " (connection lost 0.0% of data) (suppress msg for 300 s)",
+ ),
+ at("2026-11-28T20:41:07.002Z", lossy_line(ADB, 0.0)),
+ at("2026-11-30T13:25:30.000Z", f"[mlat-client][{ADSBX}] peer_count: 12"),
+]
+
+
+@pytest.mark.parametrize(
+ ("host", "established_at"),
+ [(ADSBX, "2026-11-28T13:48:02.113Z"), (ADB, "2026-11-28T13:48:02.540Z")],
+)
+async def test_the_reference_install_restart_reads_its_open_outputs_as_up(
+ host: str, established_at: str, transition_log: RecordingLogger
+) -> None:
+ """Issue #369 replayed: a first read whose newest matched line is the
+ 0.0% warning. Both feeds are up, on both sides of a restart, and no
+ "Feed offline" follows (that self-alert is raised by ``down`` only)."""
+ now_ms = ms(FERMI_NOW)
+ documents = {"/" + mlat_stats_path(host, 31090): mlat_doc(now=now_ms // 1000)}
+
+ for _restart in range(2):
+ probe = ultrafeeder(host, documents, docker_with_logs(FERMI_LOG))
+ result = await probe.probe(now_ms)
+
+ assert result.state is FeederState.UP
+ assert result.message is None
+ assert result.adsb_out is not None
+ assert result.adsb_out.connected is True
+ assert result.adsb_out.since_ms == ms(established_at)
+ assert result.detail["adsb_out_loss_pct"] == 0.0
+ assert result.metrics["adsb_out_connected"] == 1
+ assert result.last_data_sent_ms == now_ms
+
+ kinds = [f["kind"] for e, f in transition_log.events if e == "feeder_adsb_out_transition"]
+ assert kinds == ["established", "lossy"] * 2
+
+
+def chatty_mlat(clock: dict[str, int], host: str) -> dict[str, Any]:
+ return {
+ "/" + mlat_stats_path(host, 31090): lambda request: httpx.Response(
+ 200, json=mlat_doc(now=clock["now_s"])
+ )
+ }
+
+
+async def test_a_recent_lossy_line_degrades_an_open_output_until_it_ages() -> None:
+ """disconnect → established → lossy (12.5%, a minute ago): degraded, not
+ down, the connection's time unchanged; 15 minutes on with no repeat, up."""
+ chatter = f"[mlat-client][{ADSBX}] peer_count: 12"
+ docker = docker_with_reads(
+ [
+ [
+ stamped(-600, DISCONNECTED.format(host=ADSBX)),
+ stamped(-590, ESTABLISHED.format(host=ADSBX)),
+ stamped(-60, lossy_line(ADSBX, 12.5)),
+ ],
+ [stamped(LOSSY_RECENT_MS // 1000, chatter)],
+ ]
+ )
+ clock = {"now_s": FIXTURE_NOW_S}
+ probe = ultrafeeder(ADSBX, chatty_mlat(clock, ADSBX), docker)
+
+ lossy = await probe.probe(FIXTURE_NOW_MS)
+ clock["now_s"] += LOSSY_RECENT_MS // 1000 + 1
+ aged = await probe.probe(FIXTURE_NOW_MS + LOSSY_RECENT_MS + 1000)
+
+ assert lossy.state is FeederState.DEGRADED
+ assert lossy.message == "ADS-B output dropping data (12.5% lost)"
+ assert lossy.adsb_out is not None and lossy.adsb_out.connected is True
+ assert lossy.adsb_out.since_ms == FIXTURE_NOW_MS - 590_000
+ assert lossy.detail["adsb_out_loss_pct"] == 12.5
+ assert lossy.metrics["adsb_out_connected"] == 1
+ assert lossy.last_data_sent_ms == FIXTURE_NOW_MS
+ assert aged.state is FeederState.UP
+ assert aged.message is None
+ assert aged.detail["adsb_out_loss_pct"] == 12.5
+
+
+async def test_a_recent_loss_under_the_threshold_leaves_the_feed_up() -> None:
+ below = LOSSY_DEGRADED_PCT - 0.1
+ docker = docker_with_reads(
+ [[stamped(-600, ESTABLISHED.format(host=ADSBX)), stamped(-30, lossy_line(ADSBX, below))]]
+ )
+ probe = ultrafeeder(ADSBX, {"/" + mlat_stats_path(ADSBX, 31090): mlat_doc()}, docker)
+
+ result = await probe.probe(FIXTURE_NOW_MS)
+
+ assert result.state is FeederState.UP
+ assert result.detail["adsb_out_loss_pct"] == pytest.approx(below)
+
+
+async def test_a_lossy_only_tail_leaves_the_state_unknown() -> None:
+ """With no established/closed line in the tail, a lossy one does not
+ infer "up": the feeder is judged on MLAT, with no loss overlay."""
+ docker = docker_with_reads([[stamped(-30, lossy_line(ADSBX, 50.0))]])
+ probe = ultrafeeder(ADSBX, {"/" + mlat_stats_path(ADSBX, 31090): mlat_doc()}, docker)
+
+ result = await probe.probe(FIXTURE_NOW_MS)
+
+ assert result.state is FeederState.UP
+ assert result.adsb_out is not None
+ assert result.adsb_out.connected is None
+ assert result.adsb_out.since_ms is None
+ assert "adsb_out_loss_pct" not in result.detail
+ assert result.message is None
+
+
+async def test_lossy_with_mlat_unwell_is_degraded_with_both_reasons() -> None:
+ docker = docker_with_reads(
+ [[stamped(-600, ESTABLISHED.format(host=ADSBX)), stamped(-30, lossy_line(ADSBX, 5.0))]]
+ )
+ probe = ultrafeeder(ADSBX, {}, docker)
+
+ result = await probe.probe(FIXTURE_NOW_MS)
+
+ assert result.state is FeederState.DEGRADED
+ assert result.message is not None
+ assert result.message.endswith("; ADS-B output dropping data (5.0% lost)")
+
+
+async def test_a_loss_figure_does_not_outlive_its_connection() -> None:
+ """N is cumulative per connection: a close and a reopen start it again."""
+ docker = docker_with_reads(
+ [
+ [stamped(-600, ESTABLISHED.format(host=ADSBX)), stamped(-30, lossy_line(ADSBX, 40.0))],
+ [stamped(5, DISCONNECTED.format(host=ADSBX))],
+ [stamped(20, ESTABLISHED.format(host=ADSBX))],
+ ]
+ )
+ clock = {"now_s": FIXTURE_NOW_S}
+ probe = ultrafeeder(ADSBX, chatty_mlat(clock, ADSBX), docker)
+
+ results = []
+ for offset_s in (0, 15, 30):
+ clock["now_s"] = FIXTURE_NOW_S + offset_s
+ results.append(await probe.probe(FIXTURE_NOW_MS + offset_s * 1000))
+ lossy, closed, reopened = results
+
+ assert lossy.state is FeederState.DEGRADED
+ assert closed.state is FeederState.DOWN
+ assert closed.message == "ADS-B output disconnected"
+ assert "adsb_out_loss_pct" not in closed.detail
+ assert reopened.state is FeederState.UP
+ assert "adsb_out_loss_pct" not in reopened.detail
+
+
+async def test_an_unrecognised_line_keeps_the_verdict_and_is_warned_once(
+ transition_log: RecordingLogger,
+) -> None:
+ odd = "[readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Something new"
+ docker = docker_with_reads(
+ [
+ [stamped(-60, ESTABLISHED.format(host=ADSBX)), stamped(-2, odd)],
+ # The read overlap hands the same line back once more.
+ [stamped(-2, odd)],
+ [stamped(14, odd)],
+ ]
+ )
+ clock = {"now_s": FIXTURE_NOW_S}
+ probe = ultrafeeder(ADSBX, chatty_mlat(clock, ADSBX), docker)
+
+ results = []
+ for offset_s in (0, 15, 30):
+ clock["now_s"] = FIXTURE_NOW_S + offset_s
+ results.append(await probe.probe(FIXTURE_NOW_MS + offset_s * 1000))
+
+ assert all(r.state is FeederState.UP for r in results)
+ assert all(r.adsb_out is not None and r.adsb_out.connected is True for r in results)
+ assert all(
+ r.adsb_out is not None and r.adsb_out.since_ms == FIXTURE_NOW_MS - 60_000 for r in results
+ )
+ warnings = [f for e, f in transition_log.events if e == "feeder_adsb_out_unrecognised_line"]
+ assert [w["line_ts_ms"] for w in warnings] == [FIXTURE_NOW_MS - 2_000, FIXTURE_NOW_MS + 14_000]
+ assert all(w["line"] == odd for w in warnings)
+
+
+async def test_an_unrecognised_line_alone_does_not_set_a_state() -> None:
+ odd = "[readsb] BeastReduce TCP output: feed.adsbexchange.com port 30004: Something new"
+ docker = docker_with_reads([[stamped(-2, odd)]])
+ probe = ultrafeeder(ADSBX, {"/" + mlat_stats_path(ADSBX, 31090): mlat_doc()}, docker)
+
+ result = await probe.probe(FIXTURE_NOW_MS)
+
+ assert result.adsb_out is not None and result.adsb_out.connected is None
+ assert result.state is FeederState.UP
+
+
async def test_unreachable_socket_falls_back_to_mlat_and_says_so() -> None:
def refuse(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("no socket", request=request)
diff --git a/docs/API.md b/docs/API.md
index da8f25f0..c730fe4d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1443,6 +1443,14 @@ feeders configured answers `200` with an empty `feeders` list, never `404`.
(slice 101 — a months-old "disconnected" or "established" line is not the state when
ultrafeeder's `LOGLEVEL` stops it logging the next one). The feeder is then judged
on MLAT and `message` says so; `since` keeps the last transition's time.
+ Only readsb's "Connection established" and its real close/failure lines (remote
+ disconnect, send error or timeout, failed or timed-out connect) set `connected` and
+ `since`; any other matched line leaves them as they were. readsb's periodic
+ "Bad connection, dropping data (connection lost N% of data)" warning is on an open
+ connection and never makes the feed `down` (slice 127, issue #369): `N` — cumulative
+ since that connection opened — is reported as `detail.adsb_out_loss_pct`, and the
+ feeder reads `degraded` ("ADS-B output dropping data (N% lost)") while such a line
+ is at most 15 minutes old and `N` is at least 1.0.
An MLAT client with zero peers reads `degraded` only after three consecutive polls,
and never `down`. `mlat.good_sync_pct` is a percentage, 0–100, over the client's
last hour.
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 2b2bdf63..578fd6e9 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3810,6 +3810,36 @@ slices:
preferred_agent: opus
risk_level: high
notes: "Follows #360 (fixed by slice 125, PR #363). The owner approved the permanent deletion of this history."
+ - id: "127"
+ title: "Feeders: Beast-output verdict from readsb log lines"
+ phase: 9
+ branch: "127-beast-output-lossy-lines"
+ status: in_progress
+ depends_on: []
+ objective: "Stop readsb's periodic 'Bad connection, dropping data (connection lost N% of data)' warning, logged on an open Beast output, from marking an ultrafeeder feed down (#369): only established and real close/failure lines set the state; a recent lossy line with N >= 1.0% degrades the feed, never downs it."
+ scope:
+ - "feeders/ultrafeeder.py: classify_beast_line sorts matched lines into established / closed / lossy / unrecognised, using readsb's own wording (net_io.c at wiedehopf/readsb bc57f2dd, cited in the code and the fixture)"
+ - "only established and closed lines set adsb_out.connected and since; a first read with no such line in the tail leaves connected unknown"
+ - "lossy overlay: N (cumulative since the connection opened) in detail.adsb_out_loss_pct while connected; degraded with 'ADS-B output dropping data (N% lost)' when the newest lossy line of the current connection is at most 15 min old and N >= 1.0%; a loss figure is dropped when its connection closes"
+ - "an unrecognised matched line keeps the verdict and is logged once at warning (deduplicated on text and time across the read overlap); the feeder_adsb_out_transition evidence log carries the kind"
+ - "docs: the module docstring and docs/API.md feeder states"
+ out_of_scope:
+ - "the silent-log rule of slice 101 (#276), unchanged"
+ - "any change to the AdsbOutStatus API shape or the stored metrics"
+ acceptance_criteria:
+ - "the reference install's log at the v0.17.0 upgrade (established, then a 0.0% lossy warning) reads up on a first read, before and after a restart, and raises no Feed offline"
+ - "a recent lossy line at or above 1.0% reads degraded with the loss in the message and detail, and up again once it is older than 15 minutes"
+ - "every readsb close/failure wording reads disconnected; an unrecognised line never flips the state"
+ required_tests: [tests/feeders/test_vendors.py, ruff, mypy]
+ expected_artifacts:
+ - backend/src/flightsite/feeders/ultrafeeder.py
+ - backend/tests/feeders/test_vendors.py
+ - backend/tests/feeders/fixtures/readsb_beast_lines.tsv
+ - backend/tests/feeders/fixtures/ultrafeeder.log
+ - docs/API.md
+ preferred_agent: opus
+ risk_level: low
+ notes: "Issue #369. Fable plan review rulings 1-4 (v0.18.0 plan) applied."
From 97cb9efc1026f28266e46028d36ed748504f8dda Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:50:41 -0500
Subject: [PATCH 07/33] feat(api): map read-pool exhaustion on /api/v1 to 503
read_pool_exhausted
An /api/v1 HTTP request now waits at most 5 s for a read connection
(bounded_read_checkout, set by a pure-ASGI middleware as a context
variable) and is answered 503 read_pool_exhausted with Retry-After
instead of hanging for SQLAlchemy's 30 s pool_timeout and surfacing as
an unmapped 500. Background readers, the WebSocket and /api/internal
keep the pool's long wait. Introduces the app's first exception handler;
counts each event in read_pool_exhaustions (health + diagnostics).
ADR-0020 amended (decision 9, Consequences); API.md and CONFIGURATION.md
document the code and counter.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
backend/src/flightsite/api/read_pool.py | 133 +++++++++++++++
backend/src/flightsite/api/v1.py | 4 +-
backend/src/flightsite/app.py | 15 +-
backend/src/flightsite/counters.py | 7 +
backend/src/flightsite/db/__init__.py | 4 +
backend/src/flightsite/db/engine.py | 84 +++++++++-
backend/tests/api/test_read_pool_api.py | 170 ++++++++++++++++++++
backend/tests/db/test_read_pool_checkout.py | 110 +++++++++++++
docs/API.md | 31 +++-
docs/CONFIGURATION.md | 5 +
docs/adr/0020-read-statement-budget.md | 41 ++++-
docs/adr/README.md | 2 +-
12 files changed, 594 insertions(+), 12 deletions(-)
create mode 100644 backend/src/flightsite/api/read_pool.py
create mode 100644 backend/tests/api/test_read_pool_api.py
create mode 100644 backend/tests/db/test_read_pool_checkout.py
diff --git a/backend/src/flightsite/api/read_pool.py b/backend/src/flightsite/api/read_pool.py
new file mode 100644
index 00000000..34f55022
--- /dev/null
+++ b/backend/src/flightsite/api/read_pool.py
@@ -0,0 +1,133 @@
+"""Read-pool exhaustion on ``/api/v1``: ``503 read_pool_exhausted`` (slice 123).
+
+The read pool is a handful of connections with no overflow, shared by API
+requests and every background reader (:mod:`flightsite.db.engine`). When all
+of them stay busy, SQLAlchemy makes a new session wait up to its
+``pool_timeout`` (30 s) and then raises an unmapped ``TimeoutError``, which a
+client used to see as a bare ``500``.
+
+This module gives ``/api/v1`` HTTP requests a short wait of their own and a
+documented answer when it runs out (ADR-0020, amended by slice 123):
+
+* :class:`ApiReadCheckoutMiddleware` opens
+ :func:`~flightsite.db.bounded_read_checkout` around every HTTP request whose
+ path is under ``/api/v1/``. Every read session that request opens checks its
+ connection out within :data:`API_READ_CHECKOUT_TIMEOUT_S` or raises
+ :exc:`~flightsite.db.ReadPoolExhausted`. The WebSocket, ``/api/internal``,
+ the lifespan and every background reader keep the pool's long wait.
+* :func:`read_pool_exhausted_handler` is the app's exception handler for that
+ error. It is the first app-level exception handler FlightSite has; the
+ exception can only be raised inside the middleware's bound, so it only ever
+ answers ``/api/v1`` requests. It counts the event in
+ ``read_pool_exhaustions``, logs one ``warning`` (method, path and wait, never
+ the query string, which can carry user input), and answers ``503`` in the
+ §2.5 envelope with ``Retry-After``. Unlike ``query_budget_exceeded`` this is
+ transient: the same request succeeds once a connection is free.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Final
+
+import structlog
+from fastapi import Request, status
+from fastapi.responses import JSONResponse, Response
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+from flightsite.counters import READ_POOL_EXHAUSTIONS, counters
+from flightsite.db import ReadPoolExhausted, bounded_read_checkout
+
+logger = structlog.get_logger(__name__)
+
+#: How long an ``/api/v1`` request waits for a free read connection.
+#:
+#: A read normally checks out in well under a millisecond, so any wait at all
+#: means the pool is saturated. What holds a connection longest is a budgeted
+#: list query (``history.query_budget_s``, default 10 s, ADR-0020), so half
+#: that default keeps a waiting request from outliving a running one by much:
+#: the worst case is about 5 s of waiting plus the query's own budget. Long
+#: enough to ride out a burst (a rollup pass, a page opening several cards at
+#: once), short enough that a client sees a clear 503 instead of hanging for
+#: SQLAlchemy's 30 s. Not a setting: the right value follows the budget and
+#: the pool size, and neither has a measurement saying it should differ.
+API_READ_CHECKOUT_TIMEOUT_S: Final = 5.0
+
+#: The path prefix the bound applies to.
+API_V1_PREFIX: Final = "/api/v1/"
+
+#: §2.5's slug for a request that found every read connection busy.
+READ_POOL_EXHAUSTED: Final = "read_pool_exhausted"
+
+#: The fixed text of that error. It names nothing about the request.
+READ_POOL_EXHAUSTED_MESSAGE: Final = (
+ "The server is busy reading the database. Try again in a few seconds."
+)
+
+#: ``Retry-After`` on the answer, in seconds: one checkout bound.
+RETRY_AFTER_S: Final = 5
+
+#: The OpenAPI entry the ``/api/v1`` router declares for every route.
+READ_POOL_RESPONSES: Final[dict[int | str, dict[str, Any]]] = {
+ 503: {
+ "description": (
+ "Every read connection stayed busy for the request's checkout bound: "
+ "`read_pool_exhausted` in the §2.5 envelope, with `Retry-After`. "
+ "Transient; the same request succeeds once a connection is free."
+ ),
+ "content": {
+ "application/json": {
+ "example": {
+ "error": {
+ "code": READ_POOL_EXHAUSTED,
+ "message": READ_POOL_EXHAUSTED_MESSAGE,
+ "detail": None,
+ }
+ }
+ }
+ },
+ }
+}
+
+
+class ApiReadCheckoutMiddleware:
+ """Bound the read-pool checkout of every ``/api/v1`` HTTP request.
+
+ Pure ASGI, so the request runs in the same task that set the bound and the
+ context variable reaches every read session it opens. Only ``http`` scopes
+ are bounded: a WebSocket connection is long-lived and its reads are not a
+ request a client is waiting on in the same way.
+ """
+
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] == "http" and str(scope.get("path", "")).startswith(API_V1_PREFIX):
+ with bounded_read_checkout(API_READ_CHECKOUT_TIMEOUT_S):
+ await self.app(scope, receive, send)
+ return
+ await self.app(scope, receive, send)
+
+
+async def read_pool_exhausted_handler(request: Request, exc: Exception) -> Response:
+ """Answer a request that found every read connection busy (§2.5)."""
+ waited_s = exc.waited_s if isinstance(exc, ReadPoolExhausted) else None
+ counters.increment(READ_POOL_EXHAUSTIONS)
+ logger.warning(
+ "read_pool_exhausted",
+ method=request.method,
+ path=request.url.path,
+ waited_s=None if waited_s is None else round(waited_s, 3),
+ timeout_s=API_READ_CHECKOUT_TIMEOUT_S,
+ )
+ return JSONResponse(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ content={
+ "error": {
+ "code": READ_POOL_EXHAUSTED,
+ "message": READ_POOL_EXHAUSTED_MESSAGE,
+ "detail": None,
+ }
+ },
+ headers={"Retry-After": str(RETRY_AFTER_S)},
+ )
diff --git a/backend/src/flightsite/api/v1.py b/backend/src/flightsite/api/v1.py
index 8ba7039f..57fdcf22 100644
--- a/backend/src/flightsite/api/v1.py
+++ b/backend/src/flightsite/api/v1.py
@@ -153,7 +153,9 @@
"description": (
"The request ran past its read-statement budget (`history.query_budget_s`) "
"and was stopped: `query_budget_exceeded` in the §2.5 envelope. Not "
- "transient; retrying the same request will fail the same way."
+ "transient; retrying the same request will fail the same way. Like every "
+ "/api/v1 route, it can also answer `read_pool_exhausted` (transient, with "
+ "`Retry-After`) when no read connection is free."
),
"content": {
"application/json": {
diff --git a/backend/src/flightsite/app.py b/backend/src/flightsite/app.py
index 1317cb2d..2a260ff5 100644
--- a/backend/src/flightsite/app.py
+++ b/backend/src/flightsite/app.py
@@ -38,11 +38,16 @@
from flightsite.api.context import LiveApiContext
from flightsite.api.ingestion import decoder_endpoint, start_decoder_ingestion
from flightsite.api.internal import router as internal_router
+from flightsite.api.read_pool import (
+ READ_POOL_RESPONSES,
+ ApiReadCheckoutMiddleware,
+ read_pool_exhausted_handler,
+)
from flightsite.api.serializers import activity_event_payload
from flightsite.api.v1 import router as v1_router
from flightsite.api.ws import LiveBroadcaster
from flightsite.config import ConfigStore, Settings
-from flightsite.db import Database, database_path, initialize_database
+from flightsite.db import Database, ReadPoolExhausted, database_path, initialize_database
from flightsite.db.clock import utc_now_ms
from flightsite.db.startup import DATABASE_SUBSYSTEM
from flightsite.demo import DEFAULT_CENTER, DemoAdapter, demo_enabled
@@ -1228,7 +1233,13 @@ def create_app(data_dir: str | os.PathLike[str] | None = None) -> FastAPI:
app.state.api_context = LiveApiContext(app)
app.state.broadcaster = LiveBroadcaster(context=app.state.api_context)
- app.include_router(v1_router, prefix="/api/v1")
+ app.include_router(v1_router, prefix="/api/v1", responses=READ_POOL_RESPONSES)
+ # Slice 123: an /api/v1 HTTP request waits only briefly for a read
+ # connection, and a saturated pool answers `503 read_pool_exhausted`
+ # instead of an unmapped 500. The middleware sets the bound; the handler
+ # (the app's first exception handler) answers the error it raises.
+ app.add_middleware(ApiReadCheckoutMiddleware)
+ app.add_exception_handler(ReadPoolExhausted, read_pool_exhausted_handler)
# /api/internal is an unsupported, unversioned surface (ADR-0007) and is
# kept out of the OpenAPI schema published for /api/v1. One flag here
# covers every internal endpoint, now and in later slices.
diff --git a/backend/src/flightsite/counters.py b/backend/src/flightsite/counters.py
index 5cbff5c8..c8b5cfc6 100644
--- a/backend/src/flightsite/counters.py
+++ b/backend/src/flightsite/counters.py
@@ -41,6 +41,12 @@
#: the statement and its parameters are recorded nowhere.
QUERY_BUDGET_ABORTS: Final = "query_budget_aborts"
+#: ``/api/v1`` requests that found every read connection busy for their whole
+#: checkout bound and were answered with ``503 read_pool_exhausted`` (slice
+#: 123, ADR-0020 as amended). A rising value means the read pool is saturated;
+#: the warning log line names the method, path and wait.
+READ_POOL_EXHAUSTIONS: Final = "read_pool_exhaustions"
+
KNOWN_COUNTERS: Final[tuple[str, ...]] = (
"ingestion_failures",
"db_errors",
@@ -49,6 +55,7 @@
LIVE_EVENTS_DROPPED,
FEEDER_POLL_FAILURES,
QUERY_BUDGET_ABORTS,
+ READ_POOL_EXHAUSTIONS,
)
diff --git a/backend/src/flightsite/db/__init__.py b/backend/src/flightsite/db/__init__.py
index 43369086..02581b37 100644
--- a/backend/src/flightsite/db/__init__.py
+++ b/backend/src/flightsite/db/__init__.py
@@ -15,6 +15,8 @@
QUICK_CHECK_OK,
Database,
QueryBudgetExceeded,
+ ReadPoolExhausted,
+ bounded_read_checkout,
create_sqlite_engine,
database_path,
sqlite_url,
@@ -104,6 +106,7 @@
"QueryBudgetExceeded",
"RangeByBearingBandDaily",
"RangeByBearingDaily",
+ "ReadPoolExhausted",
"ReceiverMetricDaily",
"ReceiverMetricHourly",
"ReceiverMetricRaw",
@@ -117,6 +120,7 @@
"TypeStats",
"Watchlist",
"WatchlistEntry",
+ "bounded_read_checkout",
"create_sqlite_engine",
"database_path",
"from_epoch_ms",
diff --git a/backend/src/flightsite/db/engine.py b/backend/src/flightsite/db/engine.py
index 8b2832f5..70b292f4 100644
--- a/backend/src/flightsite/db/engine.py
+++ b/backend/src/flightsite/db/engine.py
@@ -63,22 +63,38 @@
(ADR-0020). Only the list endpoints ADR-0020 names ask for a budget. Every
other read session, and the writer engine, runs unbudgeted, and the handler is
never installed on connect, because every reader shares the read pool.
+
+Read-pool checkout bound
+------------------------
+
+The read pool is :data:`READ_POOL_SIZE` connections with no overflow, shared by
+API requests and by every background reader (analytics rollups, maintenance,
+metadata, alerts). When all of them are busy a new session waits for one to
+come back. Background readers keep SQLAlchemy's long wait (``pool_timeout``,
+30 s): they have no client waiting on them, and failing one early would fail
+work that waiting would have finished. An API request should not wait that
+long, so :func:`bounded_read_checkout` lets a caller (the ``/api/v1`` HTTP
+middleware, slice 123) bound the checkout of every read session opened within
+it. Past the bound the session raises :exc:`ReadPoolExhausted`, which the API
+answers with ``503 read_pool_exhausted`` (ADR-0020, amended).
"""
from __future__ import annotations
import asyncio
import contextlib
+import contextvars
import sqlite3
import time
-from collections.abc import AsyncIterator, Sequence
-from contextlib import asynccontextmanager
+from collections.abc import AsyncIterator, Iterator, Sequence
+from contextlib import asynccontextmanager, contextmanager
from pathlib import Path
from typing import Any
from sqlalchemy import event
from sqlalchemy.engine.interfaces import DBAPIConnection
from sqlalchemy.exc import OperationalError
+from sqlalchemy.exc import TimeoutError as PoolTimeoutError
from sqlalchemy.ext.asyncio import (
AsyncConnection,
AsyncEngine,
@@ -124,6 +140,63 @@ def __init__(self, *, budget_s: float, elapsed_s: float) -> None:
self.elapsed_s = elapsed_s
+class ReadPoolExhausted(Exception):
+ """Every read connection stayed busy for the whole checkout bound.
+
+ Raised by :meth:`Database.read_session` only inside
+ :func:`bounded_read_checkout`; an unbounded caller keeps waiting on the
+ pool's own timeout instead. Carries the bound and how long the session
+ waited, nothing about any statement.
+ """
+
+ def __init__(self, *, timeout_s: float, waited_s: float) -> None:
+ super().__init__(f"no read connection free within {timeout_s:g} s")
+ self.timeout_s = timeout_s
+ self.waited_s = waited_s
+
+
+#: The checkout bound for read sessions opened in the current context, or
+#: ``None`` for the pool's own (long) wait. Set only through
+#: :func:`bounded_read_checkout`.
+_checkout_timeout_s: contextvars.ContextVar[float | None] = contextvars.ContextVar(
+ "flightsite_read_checkout_timeout_s", default=None
+)
+
+
+@contextmanager
+def bounded_read_checkout(timeout_s: float) -> Iterator[None]:
+ """Bound the read-pool checkout of every read session opened in this context.
+
+ A context variable, so it follows the current task and nothing else. A task
+ created inside the block copies the context and inherits the bound: open it
+ only around work that answers a client (an ``/api/v1`` request), never
+ around code that starts a long-lived background task.
+ """
+ token = _checkout_timeout_s.set(timeout_s)
+ try:
+ yield
+ finally:
+ _checkout_timeout_s.reset(token)
+
+
+async def _checkout_within(session: AsyncSession, timeout_s: float) -> None:
+ """Check ``session``'s read connection out now, waiting at most ``timeout_s``.
+
+ A full pool hands connections back through an :class:`asyncio.Queue`, and
+ a cancelled ``Queue.get`` gives up its place without losing a connection,
+ so bounding the wait with :func:`asyncio.timeout` leaves the pool intact.
+ A pool with room opens a new connection instead, which takes milliseconds;
+ if even that is cancelled, the pool's own handler gives the slot back. The
+ engine's own ``pool_timeout`` (30 s) is far longer and is caught as well.
+ """
+ started = time.monotonic()
+ try:
+ async with asyncio.timeout(timeout_s):
+ await session.connection()
+ except (TimeoutError, PoolTimeoutError):
+ raise ReadPoolExhausted(timeout_s=timeout_s, waited_s=time.monotonic() - started) from None
+
+
class _Deadline:
"""The one value the progress handler reads: a monotonic deadline.
@@ -344,8 +417,15 @@ async def read_session(self, *, budget_s: float | None = None) -> AsyncIterator[
:exc:`QueryBudgetExceeded`; any other database error propagates
unchanged. ``None``, the default for every caller except the
list endpoints ADR-0020 names, runs unbudgeted.
+
+ Inside :func:`bounded_read_checkout` the session checks its connection
+ out at once and raises :exc:`ReadPoolExhausted` if none is free within
+ the bound. Elsewhere it waits on the pool as before.
"""
async with self._read_sessions() as session:
+ checkout_timeout_s = _checkout_timeout_s.get()
+ if checkout_timeout_s is not None:
+ await _checkout_within(session, checkout_timeout_s)
if budget_s is None:
yield session
return
diff --git a/backend/tests/api/test_read_pool_api.py b/backend/tests/api/test_read_pool_api.py
new file mode 100644
index 00000000..718c7dfa
--- /dev/null
+++ b/backend/tests/api/test_read_pool_api.py
@@ -0,0 +1,170 @@
+"""``503 read_pool_exhausted`` on ``/api/v1`` (slice 123, ADR-0020 as amended).
+
+The exhaustion is real: the test checks out every read connection itself and
+holds them, so an API request finds the pool empty whatever the machine. The
+request's checkout bound is shortened so the test does not wait the
+production 5 s. The test's own sessions are not inside an ``/api/v1`` request,
+so they take the pool's long wait, exactly as a background reader does.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import AsyncExitStack
+from typing import Any
+
+import pytest
+from httpx import ASGITransport, AsyncClient
+from starlette.types import Receive, Scope, Send
+
+from flightsite.api import read_pool as read_pool_module
+from flightsite.api.read_pool import ApiReadCheckoutMiddleware
+from flightsite.counters import READ_POOL_EXHAUSTIONS, counters
+from flightsite.db import engine as engine_module
+from flightsite.db.engine import READ_POOL_SIZE
+
+from ..analytics.test_api import Harness, build_harness, seed
+
+TEST_BOUND_S = 0.1
+
+#: Reads of several shapes: a detail, a budgeted list, an analytics card.
+READS = [
+ "/api/v1/aircraft/a00001",
+ "/api/v1/sightings?preset=t0",
+ "/api/v1/analytics/summary?preset=t0",
+]
+
+
+class RecordingLogger:
+ """Stands in for the module logger (see ``test_query_budget_api``)."""
+
+ def __init__(self) -> None:
+ self.events: list[tuple[str, str, dict[str, Any]]] = []
+
+ def warning(self, event: str, **fields: Any) -> None:
+ self.events.append(("warning", event, fields))
+
+
+@pytest.fixture
+async def harness(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[Harness]:
+ monkeypatch.setattr(read_pool_module, "API_READ_CHECKOUT_TIMEOUT_S", TEST_BOUND_S)
+ async for value in build_harness(monkeypatch):
+ await seed(value)
+ yield value
+
+
+@pytest.fixture
+async def rest(harness: Harness) -> AsyncIterator[AsyncClient]:
+ async with AsyncClient(
+ transport=ASGITransport(app=harness.app), base_url="http://testserver"
+ ) as client:
+ yield client
+
+
+async def _hold_every_read_connection(harness: Harness, stack: AsyncExitStack) -> None:
+ for _ in range(READ_POOL_SIZE):
+ session = await stack.enter_async_context(harness.database.read_session())
+ await session.connection()
+
+
+@pytest.mark.parametrize("path", READS)
+async def test_a_request_that_finds_the_pool_exhausted_answers_503_in_the_envelope(
+ harness: Harness, rest: AsyncClient, monkeypatch: pytest.MonkeyPatch, path: str
+) -> None:
+ log = RecordingLogger()
+ monkeypatch.setattr(read_pool_module, "logger", log)
+ counters.reset()
+
+ async with AsyncExitStack() as stack:
+ await _hold_every_read_connection(harness, stack)
+ response = await rest.get(path)
+
+ assert response.status_code == 503
+ assert response.headers["retry-after"] == str(read_pool_module.RETRY_AFTER_S)
+ assert response.json() == {
+ "error": {
+ "code": "read_pool_exhausted",
+ "message": read_pool_module.READ_POOL_EXHAUSTED_MESSAGE,
+ "detail": None,
+ }
+ }
+ assert counters.snapshot()[READ_POOL_EXHAUSTIONS] == 1
+ [(level, event, fields)] = log.events
+ assert (level, event) == ("warning", "read_pool_exhausted")
+ assert fields["method"] == "GET"
+ # The path only: the query string can carry user input (`q`).
+ assert fields["path"] == path.split("?")[0]
+ assert fields["timeout_s"] == TEST_BOUND_S
+
+
+async def test_the_same_request_succeeds_once_a_connection_is_free(
+ harness: Harness, rest: AsyncClient
+) -> None:
+ async with AsyncExitStack() as stack:
+ await _hold_every_read_connection(harness, stack)
+ assert (await rest.get(READS[0])).status_code == 503
+
+ assert (await rest.get(READS[0])).status_code == 200
+
+
+async def test_an_unexhausted_pool_counts_nothing(rest: AsyncClient) -> None:
+ counters.reset()
+ for path in READS:
+ assert (await rest.get(path)).status_code == 200
+ assert counters.snapshot()[READ_POOL_EXHAUSTIONS] == 0
+
+
+async def test_the_counter_is_published_by_health_and_diagnostics(rest: AsyncClient) -> None:
+ health = (await rest.get("/api/v1/health")).json()
+ diagnostics = (await rest.get("/api/v1/diagnostics")).json()
+
+ assert READ_POOL_EXHAUSTIONS in health["counters"]
+ assert READ_POOL_EXHAUSTIONS in diagnostics["counters"]
+
+
+async def test_every_v1_operation_declares_the_503(rest: AsyncClient) -> None:
+ schema = (await rest.get("/api/v1/openapi.json")).json()
+ for path, operations in schema["paths"].items():
+ for method, operation in operations.items():
+ assert "read_pool_exhausted" in str(operation["responses"].get("503")), (
+ method,
+ path,
+ )
+
+
+async def _bound_seen_by(scope: Scope) -> float | None:
+ seen: list[float | None] = []
+
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
+ seen.append(engine_module._checkout_timeout_s.get())
+
+ async def receive() -> dict[str, Any]: # pragma: no cover - never called
+ return {}
+
+ async def send(message: Any) -> None: # pragma: no cover - never called
+ return None
+
+ await ApiReadCheckoutMiddleware(app)(scope, receive, send)
+ [bound] = seen
+ return bound
+
+
+@pytest.mark.parametrize(
+ ("scope_type", "path", "bounded"),
+ [
+ ("http", "/api/v1/aircraft", True),
+ ("http", "/api/v1/health", True),
+ ("http", "/api/internal/config", False),
+ ("http", "/api/v1x", False),
+ ("http", "/", False),
+ ("websocket", "/api/v1/ws/live", False),
+ ],
+)
+async def test_only_v1_http_requests_are_bounded(
+ monkeypatch: pytest.MonkeyPatch, scope_type: str, path: str, bounded: bool
+) -> None:
+ monkeypatch.setattr(read_pool_module, "API_READ_CHECKOUT_TIMEOUT_S", TEST_BOUND_S)
+ bound = await _bound_seen_by({"type": scope_type, "path": path})
+ assert bound == (TEST_BOUND_S if bounded else None)
+ # And the bound does not outlive the request.
+ assert engine_module._checkout_timeout_s.get() is None
diff --git a/backend/tests/db/test_read_pool_checkout.py b/backend/tests/db/test_read_pool_checkout.py
new file mode 100644
index 00000000..3f96103e
--- /dev/null
+++ b/backend/tests/db/test_read_pool_checkout.py
@@ -0,0 +1,110 @@
+"""The read-pool checkout bound on :meth:`Database.read_session` (slice 123).
+
+Each test holds every read connection of a one-connection pool, so "the pool
+is exhausted" is a fact of the test, not a timing accident. Nothing asserts
+how quickly a bound fires, only that it fired (or did not) and what the pool
+looks like afterwards.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from contextlib import AsyncExitStack
+from pathlib import Path
+
+import pytest
+from sqlalchemy import text
+
+from flightsite.db import Database, ReadPoolExhausted, bounded_read_checkout
+from flightsite.db import engine as engine_module
+
+SHORT_BOUND_S = 0.05
+
+
+@pytest.fixture
+async def single_reader(db_path: Path) -> AsyncIterator[Database]:
+ """A database whose read pool holds exactly one connection."""
+ instance = Database(db_path, read_pool_size=1)
+ try:
+ yield instance
+ finally:
+ await instance.dispose()
+
+
+async def _hold_every_connection(database: Database, stack: AsyncExitStack) -> None:
+ session = await stack.enter_async_context(database.read_session())
+ await session.connection()
+
+
+async def test_a_bounded_session_raises_when_every_connection_is_busy(
+ single_reader: Database,
+) -> None:
+ async with AsyncExitStack() as stack:
+ await _hold_every_connection(single_reader, stack)
+
+ with pytest.raises(ReadPoolExhausted) as raised, bounded_read_checkout(SHORT_BOUND_S):
+ async with single_reader.read_session():
+ pytest.fail("the session must not open") # pragma: no cover
+
+ assert raised.value.timeout_s == SHORT_BOUND_S
+ # Not `>= SHORT_BOUND_S`: the loop clock and `time.monotonic` tick at ~15 ms
+ # on Windows, so the measured wait can read a tick short of the bound.
+ assert raised.value.waited_s > 0
+ assert raised.value.__cause__ is None
+ assert raised.value.__suppress_context__ is True
+
+
+async def test_an_unbounded_background_reader_keeps_waiting_and_is_not_failed(
+ single_reader: Database,
+) -> None:
+ # Ruling 14: the short bound is the API's, never a background reader's.
+ stack = AsyncExitStack()
+ await _hold_every_connection(single_reader, stack)
+
+ async def background_read() -> int:
+ async with single_reader.read_session() as session:
+ return int(await session.scalar(text("SELECT 7")) or 0)
+
+ background = asyncio.create_task(background_read())
+ with pytest.raises(ReadPoolExhausted), bounded_read_checkout(SHORT_BOUND_S):
+ async with single_reader.read_session():
+ pytest.fail("the session must not open") # pragma: no cover
+
+ # The API-bounded session has given up; the background one is still waiting.
+ await asyncio.sleep(SHORT_BOUND_S)
+ assert not background.done()
+
+ await stack.aclose()
+ assert await asyncio.wait_for(background, timeout=10) == 7
+
+
+async def test_the_pool_is_intact_after_an_exhausted_checkout(single_reader: Database) -> None:
+ async with AsyncExitStack() as stack:
+ await _hold_every_connection(single_reader, stack)
+ with pytest.raises(ReadPoolExhausted), bounded_read_checkout(SHORT_BOUND_S):
+ async with single_reader.read_session():
+ pytest.fail("the session must not open") # pragma: no cover
+
+ # The one connection came back and the timed-out waiter took nothing with it.
+ with bounded_read_checkout(SHORT_BOUND_S):
+ async with single_reader.read_session() as session:
+ assert await session.scalar(text("SELECT 1")) == 1
+
+
+async def test_the_bound_also_maps_the_pools_own_timeout(single_reader: Database) -> None:
+ # Should the engine's `pool_timeout` ever be shorter than the bound, its
+ # sqlalchemy TimeoutError is the same condition and maps the same way.
+ single_reader._read_engine.pool._timeout = 0.01 # type: ignore[attr-defined]
+ async with AsyncExitStack() as stack:
+ await _hold_every_connection(single_reader, stack)
+ with pytest.raises(ReadPoolExhausted), bounded_read_checkout(10.0):
+ async with single_reader.read_session():
+ pytest.fail("the session must not open") # pragma: no cover
+
+
+async def test_the_bound_is_scoped_to_its_block() -> None:
+ assert engine_module._checkout_timeout_s.get() is None
+ with bounded_read_checkout(SHORT_BOUND_S):
+ assert engine_module._checkout_timeout_s.get() == SHORT_BOUND_S
+ assert engine_module._checkout_timeout_s.get() is None
diff --git a/docs/API.md b/docs/API.md
index da8f25f0..a304da9f 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -121,7 +121,7 @@ Non-2xx responses use a single shape:
`code` is a stable machine-readable slug (`bad_request`, `not_found`,
`validation_error`, `conflict`, `unavailable`, `internal_error`,
-`query_budget_exceeded`). Validation errors put field details in `detail`. Secrets
+`query_budget_exceeded`, `read_pool_exhausted`). Validation errors put field details in `detail`. Secrets
never appear in error output.
**`503 query_budget_exceeded`** (slice 122, [ADR-0020](adr/0020-read-statement-budget.md)).
@@ -147,6 +147,28 @@ sort such as `started_at`, a narrower `q`). Read `code`; the `message` is fixed
text and may be reworded. Each abort is counted in `counters.query_budget_aborts` (§3.1,
§3.11). No other endpoint is budgeted.
+**`503 read_pool_exhausted`** (slice 123, [ADR-0020](adr/0020-read-statement-budget.md)
+as amended). Every `/api/v1` HTTP endpoint that reads the database shares a small pool of
+read connections with FlightSite's background work. A request waits at most 5 s for a
+free one; if every connection stays busy that long, it is answered with:
+
+```json
+{
+ "error": {
+ "code": "read_pool_exhausted",
+ "message": "The server is busy reading the database. Try again in a few seconds.",
+ "detail": null
+ }
+}
+```
+
+and a `Retry-After: 5` header. Unlike `query_budget_exceeded` it is transient: the same
+request succeeds once a connection is free, so clients keep their normal retry. Read
+`code`; the `message` may be reworded. Each one is counted in
+`counters.read_pool_exhaustions` (§3.1, §3.11). The WebSocket (§4) and background work
+are not bounded this way; they wait for a connection as long as the pool allows. Before
+slice 123 a saturated pool surfaced, after 30 s, as an unmapped `500`.
+
### 2.6 Provenance representation
Objects that carry enriched/derived fields include a `provenance` map naming the
@@ -266,7 +288,8 @@ schema. Delivered incrementally starting with slice 010.
"ws_disconnects": 0,
"live_events_dropped": 0,
"feeder_poll_failures": 0,
- "query_budget_aborts": 0
+ "query_budget_aborts": 0,
+ "read_pool_exhaustions": 0
},
"demo": false
}
@@ -1179,6 +1202,10 @@ Two contract details worth knowing:
`503 query_budget_exceeded` (§2.5). It is a count only: which list and sort was slow
is in the warning log line (endpoint, sort key, elapsed time), and the statement and
its parameters are recorded nowhere.
+- `counters.read_pool_exhaustions` (slice 123) counts the `/api/v1` requests answered
+ `503 read_pool_exhausted` (§2.5) because every read connection stayed busy for the
+ request's 5 s checkout bound. A rising value means the read pool is saturated; the
+ warning log line names the method, the path (never the query string) and the wait.
- `self_alerts` (slice 088) reports each receiver self-alert condition and what is
active now — thresholds, states and timestamps only:
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index b210da74..7353511f 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -274,6 +274,11 @@ no Settings-page control. The default leaves fermi's slowest list (2.6 s on a Pi
~380k sightings) a wide margin. Raise it only if slow storage makes ordinary sorts hit
it; `query_budget_aborts` in the diagnostics counters says how often that happens.
+Separately, an `/api/v1` request waits at most 5 s for a free read connection and is
+otherwise answered `503 read_pool_exhausted` (slice 123, [API.md §2.5](API.md)). That
+wait is fixed, not a setting; `read_pool_exhaustions` in the diagnostics counters says
+how often it runs out.
+
### `map`
| Key | Type | Default | Notes |
diff --git a/docs/adr/0020-read-statement-budget.md b/docs/adr/0020-read-statement-budget.md
index acb103ef..55b9b525 100644
--- a/docs/adr/0020-read-statement-budget.md
+++ b/docs/adr/0020-read-statement-budget.md
@@ -1,7 +1,9 @@
# ADR-0020: Read-statement budget for list queries
**Status:** Accepted (2026-11-29; decision by Fable on issue
-[#321](https://github.com/stevenpickles/flightsite/issues/321), implemented in slice 122.)
+[#321](https://github.com/stevenpickles/flightsite/issues/321), implemented in slice 122;
+amended 2026-11-30 with decision 9, read-pool checkout, implemented in slice 123, by
+Fable's ruling on the v0.18.0 plan.)
## Context
@@ -89,13 +91,44 @@ key kept on `aircraft`.
slow response whatever its elapsed time: auto-refresh pauses until the request
changes or a manual refresh answers in time. They show an inline message chosen from
`error.code`, never from the message text.
+9. **Read-pool checkout** (*amended 2026-11-30, slice 123*). The budget bounds how long
+ a request *holds* a read connection; this bounds how long one *waits* for it.
+ - **API requests only.** An ASGI middleware opens `bounded_read_checkout(5 s)` around
+ every HTTP request under `/api/v1/`. It is a context variable, so every
+ `read_session` the request opens, at any depth, sees it without a parameter at
+ about a hundred call sites. Such a session checks its connection out at once under
+ `asyncio.timeout`, and past the bound raises the domain `ReadPoolExhausted`
+ (bound and wait only, chained `from None`). A cancelled wait on the pool's
+ `asyncio.Queue` gives its place up without losing a connection.
+ - **Background readers keep the long wait.** About a hundred background readers
+ share the pool (rollups, maintenance, metadata, alerts), and a bound shorter than
+ `query_budget_s` would fail them when waiting would succeed, with no client to tell.
+ So there is no engine-wide short `pool_timeout`: everything outside an `/api/v1`
+ HTTP request, the WebSocket and `/api/internal` included, keeps SQLAlchemy's 30 s.
+ - **Why 5 s.** A read normally checks out in well under a millisecond, so any wait
+ means saturation. The longest hold is a budgeted list query (default 10 s); half
+ that keeps a waiting request from outliving a running one by much (worst case
+ about 5 s of waiting plus the budget), rides out a burst, and answers well before
+ SQLAlchemy's 30 s. It is a constant, not a setting: it follows the budget and the
+ pool size, and nothing measured says it should differ.
+ - **The answer.** The app's first exception handler maps `ReadPoolExhausted` to
+ `503` with the §2.5 envelope, code `read_pool_exhausted`, a fixed message and
+ `Retry-After: 5`. It is distinct from `query_budget_exceeded`: exhaustion is
+ transient, so clients keep their default retry and the pages need no special UI.
+ The handler increments `read_pool_exhaustions` (published by `/api/v1/health` and
+ `/api/v1/diagnostics`) and logs one `warning` with the method, the path (never the
+ query string) and the wait. Every `/api/v1` operation declares the `503` in
+ OpenAPI.
## Consequences
- No single list request can hold a read connection for more than about the budget.
- Five concurrent worst-case requests still fill the pool for that long; the pool's
- checkout behaviour (`max_overflow=0`, SQLAlchemy's 30 s `pool_timeout`, exhaustion
- surfacing as an unmapped 500) is a separate roadmap item (slice 123).
+ Five concurrent worst-case requests still fill the pool (`READ_POOL_SIZE`,
+ `max_overflow=0`) for that long. Since slice 123 (decision 9) an `/api/v1` request
+ that arrives then waits at most 5 s and is answered `503 read_pool_exhausted`, a
+ counted, transient error, rather than hanging for 30 s and surfacing as an unmapped
+ `500`. Background readers still wait the pool's 30 s and are never failed by the API's
+ bound. The pool size is unchanged; changing it needs a measurement.
- On fermi today (Pi 5, ~379k sightings) the slowest budgeted request measures 2.6 s,
well inside the default. The budget is the bound for larger histories and slower
hardware. No Pi 4 was measured; the budget bounds the worst case on any hardware.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index a058cb63..39e9ee57 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -37,4 +37,4 @@ Trivial implementation details do not get ADRs.
| [0017](0017-feeder-status-sources.md) | Feeder status sources and the opt-in Docker socket | Accepted (amended 2026-11-28, slice 107) |
| [0018](0018-host-sdr-watchdog.md) | Ultrafeeder hot-plug and an optional host-side SDR watchdog | Accepted (amended 2026-11-28, slice 107) |
| [0019](0019-alert-webhook.md) | One optional out-of-browser channel — a generic alert webhook | Accepted |
-| [0020](0020-read-statement-budget.md) | Read-statement budget for list queries | Accepted |
+| [0020](0020-read-statement-budget.md) | Read-statement budget for list queries | Accepted (amended 2026-11-30, slice 123) |
From 0d788b81b8292143b044fa65a912e2fe3ea9ba65 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:50:43 -0500
Subject: [PATCH 08/33] chore(roadmap): mark slice 127 merged
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
planning/roadmap.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 578fd6e9..4f63899b 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3814,7 +3814,7 @@ slices:
title: "Feeders: Beast-output verdict from readsb log lines"
phase: 9
branch: "127-beast-output-lossy-lines"
- status: in_progress
+ status: merged
depends_on: []
objective: "Stop readsb's periodic 'Bad connection, dropping data (connection lost N% of data)' warning, logged on an open Beast output, from marking an ultrafeeder feed down (#369): only established and real close/failure lines set the state; a recent lossy line with N >= 1.0% degrades the feed, never downs it."
scope:
From 9aa3439d331379cf18ea2b73c0dc2f4f2602d9aa Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:50:53 -0500
Subject: [PATCH 09/33] chore(roadmap): mark slice 123 merged
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
planning/roadmap.yaml | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index 2b2bdf63..b81e1604 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3692,7 +3692,7 @@ slices:
title: "Read-pool checkout timeout and exhaustion mapping"
phase: 9
branch: "123-read-pool-exhaustion"
- status: planned
+ status: merged
depends_on: ["122"]
objective: "Decide what happens when every read connection is busy. The read pool is five connections with max_overflow=0 and SQLAlchemy's default 30 s pool_timeout, and exhaustion surfaces as an unmapped 500 (sqlalchemy.exc.TimeoutError). Slice 122 bounds each list request, but five concurrent worst-case requests still fill the pool."
scope:
@@ -3705,10 +3705,14 @@ slices:
required_tests: [backend unit and API tests for pool exhaustion]
expected_artifacts:
- backend/src/flightsite/db/engine.py
+ - backend/src/flightsite/api/read_pool.py
- backend/src/flightsite/api/v1.py
+ - backend/src/flightsite/app.py
+ - backend/src/flightsite/counters.py
+ - docs/adr/0020-read-statement-budget.md
preferred_agent: opus
risk_level: medium
- notes: "Discovered in slice 122 (#321). Not started."
+ notes: "Discovered in slice 122 (#321). Per Fable's v0.18.0 plan rulings 12-15: new code read_pool_exhausted (503, Retry-After, transient), a 5 s checkout bound for /api/v1 HTTP requests only via a context variable read by read_session; background readers keep the pool's 30 s wait; the app's first exception handler; counter read_pool_exhaustions; ADR-0020 amended (decision 9)."
- id: "124"
title: "Notification click: fly to the selected aircraft, last known position when it has none"
From 718e574e5f4ebb214c3c8ec1ae96da6ce0cfc40c Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:52:15 -0500
Subject: [PATCH 10/33] fix(map): keep the deep-link focus from being undone by
the receiver recentre
The one-time receiver recentre now yields when the camera already left
its construction centre or is moving, and onlyIfOffscreen no longer
skips while a camera move is in flight. The e2e deep-link test picks an
outlier aircraft and fails clearly if it drops out of the positioned set.
Refs #362
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
e2e/tests/04-selected-deep-link-focus.spec.ts | 31 ++++++++-
.../filters/hooks/useSelectionUrlSync.ts | 10 +--
.../src/features/map/MapLibreMap.test.tsx | 67 +++++++++++++++++++
frontend/src/features/map/MapLibreMap.tsx | 16 +++++
.../useFocusSelectedAircraft.test.tsx | 11 +++
.../map/aircraft/useFocusSelectedAircraft.ts | 8 ++-
frontend/src/test/maplibreGlMock.ts | 17 +++++
planning/roadmap.yaml | 1 +
8 files changed, 152 insertions(+), 9 deletions(-)
diff --git a/e2e/tests/04-selected-deep-link-focus.spec.ts b/e2e/tests/04-selected-deep-link-focus.spec.ts
index 65929f9c..f366bcbe 100644
--- a/e2e/tests/04-selected-deep-link-focus.spec.ts
+++ b/e2e/tests/04-selected-deep-link-focus.spec.ts
@@ -14,8 +14,8 @@
import {
browserHasWebGl,
+ type CurrentAircraft,
fetchPositionedAircraft,
- pickStableAircraft,
waitForAircraftLayer,
waitForLiveAircraft,
} from "./support/liveMap";
@@ -23,12 +23,35 @@ import { expect, test } from "./support/fixtures";
const CENTRE_TOLERANCE_PX = 120;
+/** The live, positioned aircraft farthest from the traffic's centroid, so the
+ * map's opening view (centred on the receiver) is unlikely to have it near
+ * the centre already and the test proves a move rather than a coincidence. */
+function pickOutlier(items: CurrentAircraft[]): CurrentAircraft {
+ const positioned = items.filter(
+ (item) => item.position !== null && item.state === "live",
+ );
+ if (positioned.length === 0) {
+ throw new Error("no positioned, live aircraft available to select");
+ }
+ const lat =
+ positioned.reduce((sum, item) => sum + item.position!.lat, 0) /
+ positioned.length;
+ const lon =
+ positioned.reduce((sum, item) => sum + item.position!.lon, 0) /
+ positioned.length;
+ const distance = (item: CurrentAircraft) =>
+ Math.hypot(item.position!.lat - lat, item.position!.lon - lon);
+ return positioned.reduce((far, item) =>
+ distance(item) > distance(far) ? item : far,
+ );
+}
+
test.describe("?selected= deep link", () => {
test("selects the aircraft and eases the map to it", async ({
page,
request,
}) => {
- const aircraft = pickStableAircraft(await fetchPositionedAircraft(request));
+ const aircraft = pickOutlier(await fetchPositionedAircraft(request));
await page.goto(`/?selected=${aircraft.icao}`);
test.skip(
@@ -50,7 +73,9 @@ test.describe("?selected= deep link", () => {
(item) => item.icao === aircraft.icao,
);
if (!current?.position) {
- return Number.POSITIVE_INFINITY;
+ throw new Error(
+ `aircraft ${aircraft.icao} dropped out of the positioned set while waiting for the map to centre on it`,
+ );
}
return page.evaluate(
({ lat, lon }) => {
diff --git a/frontend/src/features/filters/hooks/useSelectionUrlSync.ts b/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
index 32d630dc..81748f93 100644
--- a/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
+++ b/frontend/src/features/filters/hooks/useSelectionUrlSync.ts
@@ -12,11 +12,11 @@
* Two edges, each one-way, mirroring `useFilterUrlSync`'s own split:
*
* - **URL -> store, mount only.** A `?selected=` present at mount selects
- * that ICAO and asks the map to bring it into view (issue #362; the focus
- * request waits for the map, the record and a position) — restoring a
- * bookmarked or shared link. If the aircraft is
- * not (yet) in the live set, the selection is still made: the store holds
- * the intent, `AircraftDetailPanel` opens and reads `null` from
+ * that ICAO and asks the map to bring it into view (issue #362; the
+ * focus request waits for the map, the record and a position) —
+ * restoring a bookmarked or shared link. If the aircraft is not (yet) in
+ * the live set, the selection is still made: the store
+ * holds the intent, `AircraftDetailPanel` opens and reads `null` from
* `state.aircraft[selectedIcao]`, rendering "No live data for this
* aircraft" until a snapshot or delta actually supplies a record — at
* which point the same reactive read picks it up with no extra
diff --git a/frontend/src/features/map/MapLibreMap.test.tsx b/frontend/src/features/map/MapLibreMap.test.tsx
index 57761fe1..3b20fe92 100644
--- a/frontend/src/features/map/MapLibreMap.test.tsx
+++ b/frontend/src/features/map/MapLibreMap.test.tsx
@@ -143,6 +143,73 @@ describe("MapLibreMap", () => {
});
});
+ describe("a camera that moved before the real config arrived (issue #362)", () => {
+ const realConfig = {
+ ...config,
+ receiver: { lat: 47.6205, lon: -122.3493, label: "Rooftop Pi" },
+ };
+
+ it("yields the one-time recentre when the camera already left the construction centre", () => {
+ // Order A: the first snapshot wins the race, the deep link's focus
+ // eases the camera away, then the real config arrives.
+ const { rerender } = render(
+ ,
+ );
+ const map = getLastMockMap();
+ map.center = [-100, 40];
+
+ act(() => {
+ rerender();
+ });
+
+ expect(map.jumpTo).not.toHaveBeenCalled();
+
+ // ...and it is spent: a later config edit does not recentre either.
+ map.center = null;
+ act(() => {
+ rerender(
+ ,
+ );
+ });
+ expect(map.jumpTo).not.toHaveBeenCalled();
+ });
+
+ it("yields while a camera move is in flight", () => {
+ const { rerender } = render(
+ ,
+ );
+ const map = getLastMockMap();
+ map.moving = true;
+
+ act(() => {
+ rerender();
+ });
+
+ expect(map.jumpTo).not.toHaveBeenCalled();
+ });
+
+ it("still recentres when the config wins the race (camera untouched)", () => {
+ // Order B: the config arrives first; the recentre jumps, and a focus
+ // request made afterwards is not undone by anything.
+ const { rerender } = render(
+ ,
+ );
+ const map = getLastMockMap();
+
+ act(() => {
+ rerender();
+ });
+
+ expect(map.jumpTo).toHaveBeenCalledTimes(1);
+ });
+ });
+
it("never recenters a second time (a later config edit must not fight the user's pan/zoom)", () => {
const { rerender } = render(
,
diff --git a/frontend/src/features/map/MapLibreMap.tsx b/frontend/src/features/map/MapLibreMap.tsx
index 7c492f6e..71fd5a63 100644
--- a/frontend/src/features/map/MapLibreMap.tsx
+++ b/frontend/src/features/map/MapLibreMap.tsx
@@ -103,6 +103,10 @@ const NOTICE_SLOT_CLASSES =
* only the basemap imagery/vector tiles are affected, and a small
* non-blocking indicator surfaces that state.
*/
+/** Degrees of drift from the construction centre that count as "the camera
+ * has been moved" (float round-trip tolerance, far below any real move). */
+const CAMERA_MOVED_EPSILON = 1e-6;
+
export function MapLibreMap({
config,
basemap,
@@ -387,6 +391,18 @@ export function MapLibreMap({
return;
}
hasRecenteredOnceRef.current = true;
+ // Yield when the camera already left where it was constructed, or is
+ // mid-move (issue #362): a deep link's focus request can be consumed
+ // before the real config arrives, and snapping back to the receiver
+ // would undo it. The recentre is spent either way.
+ const camera = map.getCenter();
+ if (
+ map.isMoving() ||
+ Math.abs(camera.lat - constructionCenter.lat) > CAMERA_MOVED_EPSILON ||
+ Math.abs(camera.lng - constructionCenter.lon) > CAMERA_MOVED_EPSILON
+ ) {
+ return;
+ }
map.jumpTo({ center: [config.receiver.lon, config.receiver.lat] });
}, [config]);
diff --git a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
index 023c0d46..24344914 100644
--- a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
+++ b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx
@@ -203,6 +203,17 @@ describe("useFocusSelectedAircraft: onlyIfOffscreen (issue #362)", () => {
});
});
+ it("does not skip while a camera move is in flight", () => {
+ const { map } = renderLayer();
+ map.containerHeight = 800;
+ map.moving = true;
+ act(() => snapshot(IN_VIEW));
+
+ act(() => focusAircraftOnMap("acc31a", { onlyIfOffscreen: true }));
+
+ expect(map.easeTo).toHaveBeenCalledTimes(1);
+ });
+
it("always moves for a plain request, even to an aircraft in view", () => {
const { map } = renderLayer();
map.containerHeight = 800;
diff --git a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
index 809b1d88..45ba0356 100644
--- a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
+++ b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.ts
@@ -144,7 +144,13 @@ export function useFocusSelectedAircraft(): void {
useMapFocusRequestStore.getState().onlyIfOffscreen;
endRequest();
const center: [number, number] = [target.lon, target.lat];
- if (onlyIfOffscreen && isInView(map, center, isMobileRef.current)) {
+ // An in-flight move counts as not in view: the aircraft may project
+ // inside the current transform yet be carried off screen by the ease.
+ if (
+ onlyIfOffscreen &&
+ !map.isMoving() &&
+ isInView(map, center, isMobileRef.current)
+ ) {
return;
}
if (isMobileRef.current) {
diff --git a/frontend/src/test/maplibreGlMock.ts b/frontend/src/test/maplibreGlMock.ts
index f274995f..d19f901b 100644
--- a/frontend/src/test/maplibreGlMock.ts
+++ b/frontend/src/test/maplibreGlMock.ts
@@ -78,6 +78,23 @@ export class MapLibreMockMap {
this.emit("style.load");
});
jumpTo = vi.fn();
+ /** `isMoving()`'s value: true while a camera transition is in flight.
+ * Tests set it to simulate one (issue #362). */
+ moving = false;
+
+ isMoving(): boolean {
+ return this.moving;
+ }
+
+ /** `getCenter()`'s value, seeded from the construction options; tests
+ * assign `center` to simulate the camera having moved (issue #362). */
+ center: [number, number] | null = null;
+
+ getCenter(): { lng: number; lat: number } {
+ const [lng, lat] = this.center ??
+ (this.options.center as [number, number] | undefined) ?? [0, 0];
+ return { lng, lat };
+ }
fitBounds = vi.fn();
/** `RecenterButton` (roadmap slice 082's `H` shortcut) calls this on a
* recentre request. */
diff --git a/planning/roadmap.yaml b/planning/roadmap.yaml
index caeb1d01..39dac0aa 100644
--- a/planning/roadmap.yaml
+++ b/planning/roadmap.yaml
@@ -3830,6 +3830,7 @@ slices:
- "opening a ?selected= link selects the aircraft and eases the map to it once the map, its record and a position are available"
required_tests:
- "vitest: useFocusSelectedAircraft onlyIfOffscreen (in view, off screen, phone sheet), InterestingPanel, useKeyboardShortcuts cycling, useSelectionUrlSync"
+ - "vitest: MapLibreMap yields its one-time receiver recentre when the camera already moved or is moving (both arrival orders); onlyIfOffscreen does not skip during an in-flight move"
- "e2e (demo data): a ?selected= deep link centres the map on the aircraft"
expected_artifacts:
- frontend/src/features/map/store/useMapFocusRequestStore.ts
From 4028453b335b1a40167838160e9cf9a6e6ffd1f8 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:53:01 -0500
Subject: [PATCH 11/33] feat(metadata): scheduled metadata updates every 30
days
Move the update single-flight from the endpoint into MetadataService
(start_update / cancel_update) so the button and the new scheduler share it.
MetadataAutoUpdater ticks hourly after a 30-minute startup grace and runs
every source due (per-source clock, never-succeeded sources stay manual,
24 h / 7 d back-off keyed on last_attempt_ms) as one run; a free-space guard
skips a scheduled run with an Activity reason. metadata.auto_update_days
(default 30, 0 = off, 7-365) is read live. Not started in demo mode or on a
database that failed to migrate. The status endpoint reports the schedule.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
backend/src/flightsite/activity/facts.py | 4 +
backend/src/flightsite/activity/producers.py | 6 +
backend/src/flightsite/activity/service.py | 2 +
backend/src/flightsite/api/internal.py | 103 ++--
backend/src/flightsite/app.py | 84 +++-
backend/src/flightsite/config/models.py | 16 +
backend/src/flightsite/metadata/autoupdate.py | 368 ++++++++++++++
backend/src/flightsite/metadata/importer.py | 11 +
backend/src/flightsite/metadata/service.py | 183 ++++++-
backend/tests/activity/test_producers.py | 22 +
backend/tests/api/test_metadata_api.py | 91 +++-
backend/tests/metadata/test_autoupdate.py | 453 ++++++++++++++++++
backend/tests/test_config_api.py | 2 +
config.example.yaml | 7 +
14 files changed, 1258 insertions(+), 94 deletions(-)
create mode 100644 backend/src/flightsite/metadata/autoupdate.py
create mode 100644 backend/tests/metadata/test_autoupdate.py
diff --git a/backend/src/flightsite/activity/facts.py b/backend/src/flightsite/activity/facts.py
index c87a5a37..51c3a060 100644
--- a/backend/src/flightsite/activity/facts.py
+++ b/backend/src/flightsite/activity/facts.py
@@ -135,6 +135,10 @@ class ImportOutcome:
rows_rejected: int = 0
dataset_version: str | None = None
error: str | None = None
+ #: The scheduler started the run, not a person (slice 131, ADR-0021).
+ automatic: bool = False
+ #: The automatic run was skipped before it began; ``error`` says why.
+ skipped: bool = False
@dataclass(frozen=True, slots=True)
diff --git a/backend/src/flightsite/activity/producers.py b/backend/src/flightsite/activity/producers.py
index 0e94af50..b2c6d27d 100644
--- a/backend/src/flightsite/activity/producers.py
+++ b/backend/src/flightsite/activity/producers.py
@@ -539,6 +539,10 @@ def import_events(outcomes: Iterable[ImportOutcome]) -> ActivityBatch:
``interesting`` rather than ``info`` so the feed can lift it, and the
``error`` carried is the importer's own short reason — these sources are
unauthenticated public datasets, so it holds no credential to leak.
+
+ Slice 131 adds ``automatic`` — the scheduler started the run (ADR-0021) —
+ and ``skipped``: an automatic run that was due but did not start, with
+ the reason in ``error`` and ``ok`` false. Additive per ``docs/API.md`` §6.
"""
events: list[NewActivityEvent] = []
for outcome in outcomes:
@@ -557,6 +561,8 @@ def import_events(outcomes: Iterable[ImportOutcome]) -> ActivityBatch:
"rows_rejected": outcome.rows_rejected,
"dataset_version": outcome.dataset_version,
"error": outcome.error,
+ "automatic": outcome.automatic,
+ "skipped": outcome.skipped,
},
)
)
diff --git a/backend/src/flightsite/activity/service.py b/backend/src/flightsite/activity/service.py
index 1aeb3d69..f615dbd3 100644
--- a/backend/src/flightsite/activity/service.py
+++ b/backend/src/flightsite/activity/service.py
@@ -355,6 +355,8 @@ async def record_import(self, run: ImportRun) -> None:
rows_rejected=result.rows_rejected,
dataset_version=result.dataset_version,
error=result.error,
+ automatic=run.automatic,
+ skipped=run.skipped,
)
)
diff --git a/backend/src/flightsite/api/internal.py b/backend/src/flightsite/api/internal.py
index 464b6fda..ed0aadec 100644
--- a/backend/src/flightsite/api/internal.py
+++ b/backend/src/flightsite/api/internal.py
@@ -65,7 +65,6 @@
from __future__ import annotations
-import asyncio
import inspect
from collections.abc import Sequence
from typing import Annotated, Any
@@ -90,7 +89,8 @@
from flightsite.enrichment.service import build_economy, build_provider
from flightsite.ingest import ConnectionTestResult, DecoderEndpoint, Position, check_connection
from flightsite.live import LiveStore
-from flightsite.metadata import ImportRun, MetadataService
+from flightsite.metadata import MetadataService
+from flightsite.metadata.autoupdate import MetadataAutoUpdater
from flightsite.metadata.registry import SourceStatus, SourceStatusRecord
from flightsite.watchlists import (
DuplicateEntryError,
@@ -457,7 +457,9 @@ async def test_decoder_connection(
}
-def _metadata_source_payload(record: SourceStatusRecord) -> dict[str, Any]:
+def _metadata_source_payload(
+ record: SourceStatusRecord, next_auto_update_ms: int | None
+) -> dict[str, Any]:
"""One source's status row as ``GET /metadata/status`` reports it.
``running`` — read from the registry's in-flight state, not the durable
@@ -475,6 +477,7 @@ def _metadata_source_payload(record: SourceStatusRecord) -> dict[str, Any]:
"dataset_version": record.dataset_version,
"row_count": record.row_count,
"last_error": record.last_error,
+ "next_auto_update_ms": next_auto_update_ms,
}
@@ -492,27 +495,43 @@ async def get_metadata_status(request: Request) -> dict[str, Any]:
"""
metadata: MetadataService = request.app.state.metadata
statuses = await metadata.statuses()
- return {"sources": [_metadata_source_payload(record) for record in statuses]}
+ auto_update, next_by_source = _auto_update_payload(request, statuses)
+ return {
+ "sources": [
+ _metadata_source_payload(record, next_by_source.get(record.source))
+ for record in statuses
+ ],
+ "auto_update": auto_update,
+ }
-def _log_update_task_result(task: asyncio.Task[ImportRun]) -> None:
- """Consume a finished background run's exception, if any, into the log.
+def _auto_update_payload(
+ request: Request, statuses: Sequence[SourceStatusRecord]
+) -> tuple[dict[str, Any], dict[str, int | None]]:
+ """The scheduled-update block of ``GET /metadata/status``, and each source's next run.
- Nothing ``await``s this task directly — the HTTP request that started it
- has already returned, which is the entire point of running it in the
- background — so nothing else would ever retrieve an exception it raised.
- Without this callback, a bug here would only surface as asyncio's "Task
- exception was never retrieved" warning at the next garbage collection,
- with no context to debug it, instead of a clean log line naming what
- happened. This is distinct from a source failing its own import: that is
- caught inside :meth:`~flightsite.metadata.MetadataImporter.run` and
- reported through ``GET /metadata/status`` as a result, never raised here.
+ Slice 131, ADR-0021. ``enabled`` is the truth about this process, not only
+ the setting: it is false when ``metadata.auto_update_days`` is ``0`` *and*
+ when the updater was never started — demo mode, or a database that failed
+ to migrate — so the Settings card never promises an update nothing will
+ run. ``next_ms`` is the earliest source's next due time (past the startup
+ grace), or ``null`` when no source will be updated automatically: off, or
+ no source has ever been imported (the first import stays manual).
"""
- if task.cancelled():
- return
- exc = task.exception()
- if exc is not None:
- logger.error("metadata_update_task_failed", error=str(exc), error_type=type(exc).__name__)
+ settings: Settings = request.app.state.settings
+ interval_days = settings.metadata.auto_update_days
+ updater: MetadataAutoUpdater | None = getattr(request.app.state, "metadata_auto_update", None)
+ per_source: dict[str, int | None] = {}
+ enabled = interval_days > 0 and updater is not None and updater.running
+ if enabled and updater is not None:
+ per_source = {entry.source: entry.next_ms for entry in updater.schedule(statuses)}
+ upcoming = [value for value in per_source.values() if value is not None]
+ payload: dict[str, Any] = {
+ "enabled": enabled,
+ "interval_days": interval_days,
+ "next_ms": min(upcoming) if upcoming else None,
+ }
+ return payload, per_source
@router.post("/metadata/update", status_code=status.HTTP_202_ACCEPTED)
@@ -521,37 +540,23 @@ async def trigger_metadata_update(request: Request) -> dict[str, Any]:
Downloading and staging a snapshot per source is seconds to minutes of
network and disk I/O — nothing an HTTP client should hold a connection
- open for — so this schedules :meth:`~flightsite.metadata.MetadataService.update`
- as a background task and returns 202 the instant it is scheduled.
- Progress and outcome are read back from ``GET /metadata/status``, which
- the Settings UI polls until every source has settled.
-
- A trigger that arrives while an earlier one is still running does not
- start a second run: ``MetadataImporter`` imports its sources one at a
- time, and two overlapping runs would race each other over the same
- staging rows for whichever source is current. Instead this reports the
- in-progress run's own ``started_ms``, which is what lets a double-clicked
- button or a second open tab coalesce onto the run already happening
- instead of racing it. The check-and-schedule below never ``await``s in
- between, so two requests arriving back to back on the same event loop
- cannot both observe "not running" and both schedule a run.
+ open for — so this starts the run in the background through
+ :meth:`~flightsite.metadata.MetadataService.start_update` and returns 202
+ the instant it is scheduled. Progress and outcome are read back from
+ ``GET /metadata/status``, which the Settings UI polls until every source
+ has settled.
+
+ A trigger that arrives while a run is in flight — another click, another
+ tab, or a scheduled run (ADR-0021) — does not start a second one: the
+ service is single-flight, and this reports the in-progress run's own
+ ``started_ms`` so the caller coalesces onto it instead of racing it.
"""
- task: asyncio.Task[ImportRun] | None = request.app.state.metadata_update_task
- if task is not None and not task.done():
- return {
- "started": False,
- "already_running": True,
- "started_ms": request.app.state.metadata_update_started_ms,
- }
-
metadata: MetadataService = request.app.state.metadata
- started_ms = utc_now_ms()
- new_task = asyncio.create_task(metadata.update(), name="metadata-update")
- new_task.add_done_callback(_log_update_task_result)
- request.app.state.metadata_update_task = new_task
- request.app.state.metadata_update_started_ms = started_ms
- logger.info("metadata_update_triggered", started_ms=started_ms)
- return {"started": True, "already_running": False, "started_ms": started_ms}
+ ticket = metadata.start_update()
+ if not ticket.started:
+ return {"started": False, "already_running": True, "started_ms": ticket.started_ms}
+ logger.info("metadata_update_triggered", started_ms=ticket.started_ms)
+ return {"started": True, "already_running": False, "started_ms": ticket.started_ms}
# --------------------------------------------------------- watchlists (slice 037)
diff --git a/backend/src/flightsite/app.py b/backend/src/flightsite/app.py
index 1317cb2d..bbfbff89 100644
--- a/backend/src/flightsite/app.py
+++ b/backend/src/flightsite/app.py
@@ -2,11 +2,10 @@
from __future__ import annotations
-import asyncio
import os
import time
from collections.abc import AsyncIterator, Callable, Sequence
-from contextlib import asynccontextmanager, suppress
+from contextlib import asynccontextmanager
from typing import Any
import structlog
@@ -67,6 +66,7 @@
from flightsite.logging import DEFAULT_LOG_DIR, configure_logging, install_error_capture
from flightsite.maintenance import MaintenanceService, RouteCachePruner
from flightsite.metadata import ImportListener, ImportRun, MetadataService
+from flightsite.metadata.autoupdate import MetadataAutoUpdater
from flightsite.metadata.registry import SourceRegistry
from flightsite.metadata.sources import (
FaaRegistryProvider,
@@ -318,6 +318,21 @@ def probe() -> str:
return probe
+def _auto_update_days(app: FastAPI) -> Callable[[], int]:
+ """Read ``metadata.auto_update_days`` at the moment the updater ticks (ADR-0021).
+
+ Late for the same reason as :func:`_alert_radius`: a saved interval — or a
+ ``0`` that switches scheduled updates off — applies on the next tick, with
+ no restart.
+ """
+
+ def probe() -> int:
+ settings: Settings = app.state.settings
+ return settings.metadata.auto_update_days
+
+ return probe
+
+
def _alert_radius(app: FastAPI) -> Callable[[], float | None]:
"""Read the configured alert radius at the moment a cycle needs it (SPEC §66).
@@ -769,6 +784,21 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
# subsystem so its first cycle — an hour away — cannot overlap the
# backfills and recoveries startup is still running.
await maintenance.start()
+ # Scheduled metadata updates (slice 131, ADR-0021): same condition, and
+ # not in demo mode at all. It reads `metadata_sources`, which the
+ # failed migration may not have created, and a demo must never start a
+ # download nobody asked for. Built here rather than in `create_app` so
+ # it drives whichever `app.state.metadata` the lifespan was handed, and
+ # its first tick waits out a 30-minute grace, so starting it last costs
+ # startup nothing.
+ if not demo_enabled():
+ auto_update = MetadataAutoUpdater(
+ service=metadata,
+ interval_days=_auto_update_days(app),
+ data_dir=app.state.config_store.data_dir,
+ )
+ await auto_update.start()
+ app.state.metadata_auto_update = auto_update
# The alert webhook needs no database: it only consumes what the activity
# service publishes, and with the webhook disabled it is one idle task.
@@ -798,6 +828,11 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
# here means no housekeeping statement is holding the writer lock when
# the persistence worker takes its final transactions.
await maintenance.stop()
+ # The metadata update schedule beside it, for the same reason: a tick
+ # is a decision, and losing one loses nothing.
+ auto_update_service: MetadataAutoUpdater | None = app.state.metadata_auto_update
+ if auto_update_service is not None:
+ await auto_update_service.stop()
# Shut down along the direction of data flow, so each stage has
# already stopped producing before its consumer stops: ingestion, then
# the live store's sweep, then its two consumers — the WebSocket
@@ -809,17 +844,12 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
await service.stop()
await live.stop()
await broadcaster.stop()
- # A slice-025 update run outlives the request that triggered it
- # (that is the whole point of running it in the background), so one
- # can still be in flight at shutdown. Cancelling it here rather than
- # abandoning it means the writer session it holds rolls back
- # cleanly (``Database.writer_session`` catches ``BaseException``)
- # instead of racing the engines disposing under it.
- update_task: asyncio.Task[ImportRun] | None = app.state.metadata_update_task
- if update_task is not None and not update_task.done():
- update_task.cancel()
- with suppress(asyncio.CancelledError):
- await update_task
+ # A metadata update run outlives the request (or the scheduled tick)
+ # that started it — that is the whole point of running it in the
+ # background — so one can still be in flight at shutdown. Cancelling
+ # it here rather than abandoning it means the writer session it holds
+ # rolls back cleanly instead of racing the engines disposing under it.
+ await metadata.cancel_update()
# Before the persistence worker, so no consumer of the live stream is
# still resolving against the database while the worker takes its final
# writer transactions. Enrichment goes first of the two: it applies
@@ -908,11 +938,15 @@ def create_app(data_dir: str | os.PathLike[str] | None = None) -> FastAPI:
cache that keeps SQLite off the live path (``docs/ARCHITECTURE.md`` §3.3).
Startup attaches the cache to the live event stream on a healthy schema,
and shutdown detaches it before the writer takes its last transaction.
- ``docs/API.md`` §5's ``/api/internal/metadata/*`` (slice 025) calls
- :meth:`~flightsite.metadata.MetadataService.update` from a background
- task tracked as ``app.state.metadata_update_task``, so a run outlives the
- request that started it; shutdown cancels one still in flight before the
- cache and the writer stop underneath it.
+ ``docs/API.md`` §5's ``/api/internal/metadata/*`` (slice 025) starts a run
+ through :meth:`~flightsite.metadata.MetadataService.start_update`, whose
+ single background task outlives the request that started it; shutdown
+ cancels one still in flight before the cache and the writer stop
+ underneath it. Slice 131's scheduled updater
+ (:class:`~flightsite.metadata.autoupdate.MetadataAutoUpdater`, ADR-0021)
+ starts runs through the same method, so the two can never overlap; it is
+ built by the lifespan hook and held as ``app.state.metadata_auto_update``,
+ which stays ``None`` in demo mode and on a database that failed to migrate.
User-defined watchlists (SPEC §42) are constructed as
``app.state.watchlists``. Startup loads its in-memory match index from the
@@ -1205,14 +1239,12 @@ def create_app(data_dir: str | os.PathLike[str] | None = None) -> FastAPI:
alert_radius=_alert_radius(app),
)
app.state.alerts.engine.subscribe(_record_alert_matches(app))
- # Slice 025's update-in-progress coordinator: the background task the
- # current "Update Aircraft Metadata" run is executing in, and when it
- # started. ``None`` means no run has ever been triggered on this process.
- # Read and written only from ``POST /api/internal/metadata/update``
- # handlers, which never ``await`` between checking and replacing it, so
- # two overlapping requests on the same event loop cannot both start a run.
- app.state.metadata_update_task = None
- app.state.metadata_update_started_ms = None
+ # Slice 131's scheduled metadata updater, once the lifespan builds it.
+ # Stays ``None`` in demo mode and when the database failed to migrate, which
+ # is also how ``GET /api/internal/metadata/status`` knows to report
+ # automatic updates as off. (The update-in-progress task that used to sit
+ # beside it here now belongs to `MetadataService.start_update`.)
+ app.state.metadata_auto_update = None
app.state.start_time = time.monotonic()
# Read once at app-construction time, not per-request: demo mode is a
# process-level run mode (FLIGHTSITE_DEMO), not something that changes
diff --git a/backend/src/flightsite/config/models.py b/backend/src/flightsite/config/models.py
index 577670b1..cbc295a0 100644
--- a/backend/src/flightsite/config/models.py
+++ b/backend/src/flightsite/config/models.py
@@ -272,6 +272,22 @@ class MetadataSettings(_ConfigModel):
opensky_enabled: bool = False
source_url_overrides: dict[str, HttpUrl] = Field(default_factory=dict)
+ #: Days between automatic updates of a source (SPEC §27 owner amendment of
+ #: 2026-11-30, ADR-0021). ``0`` switches automatic updates off; otherwise
+ #: 7-365. Unlike the two fields above it is read late — by
+ #: :class:`~flightsite.metadata.autoupdate.MetadataAutoUpdater` on every
+ #: hourly tick and by ``GET /api/internal/metadata/status`` — so a change
+ #: applies on save, with no restart. The bounds are spelled here as
+ #: literals rather than imported from that module, which imports this one;
+ #: a test asserts the two agree.
+ auto_update_days: int = 30
+
+ @field_validator("auto_update_days")
+ @classmethod
+ def _auto_update_range(cls, value: int) -> int:
+ if value == 0 or 7 <= value <= 365:
+ return value
+ raise ValueError("metadata.auto_update_days must be 0 (off) or between 7 and 365")
@field_validator("source_url_overrides")
@classmethod
diff --git a/backend/src/flightsite/metadata/autoupdate.py b/backend/src/flightsite/metadata/autoupdate.py
new file mode 100644
index 00000000..5744d3ea
--- /dev/null
+++ b/backend/src/flightsite/metadata/autoupdate.py
@@ -0,0 +1,368 @@
+"""Scheduled metadata updates (SPEC §27 owner amendment of 2026-11-30, ADR-0021).
+
+The owner, verbatim: *"I want metadata sources to be automatically updated
+every 30 days."* This module is that, and nothing more: the same import the
+"Update Aircraft Metadata" button runs, started by a clock instead of a click.
+
+Two halves, deliberately separable:
+
+* :func:`next_due_ms` / :func:`plan_auto_update` — the **decision**, a pure
+ function of the stored ``metadata_sources`` rows, the configured interval and
+ the time. Everything ADR-0021 rules on (interval, never-succeeded sources,
+ back-off, escalation) lives here, so the tests can state it as a table.
+* :class:`MetadataAutoUpdater` — the **clock**: a 30-minute startup grace, then
+ an hourly tick that asks the decision what is due and hands the due sources
+ to :meth:`~flightsite.metadata.service.MetadataService.start_update` as one
+ run. That is the service's single-flight entrypoint, the same one the
+ Settings button goes through, so a scheduled run and a manual one can never
+ overlap.
+
+The rules, in the order the decision applies them:
+
+1. ``metadata.auto_update_days`` of ``0`` means off. It is read on every tick
+ (and by the status endpoint), never captured, so a change applies on save.
+2. A source that has **never succeeded** is never run automatically: the first
+ import of every source stays a manual act (ADR-0021; Fable's ruling 21,
+ adopted pending the owner's confirmation). Nobody gets a 300 MB download
+ they did not ask for on an install that has never imported anything.
+3. Otherwise a source is due ``interval`` after its ``last_success_ms``. Per
+ source, not per run: a manual run that refreshed only some sources resets
+ only their clocks, and one scheduled run takes every source due at that
+ tick.
+4. A source whose last attempt did not succeed (``last_attempt_ms`` newer than
+ ``last_success_ms``) waits out a back-off from that attempt before it is
+ tried again: 24 h for the first week it is overdue, then 7 days. Keyed on
+ ``last_attempt_ms`` because the importer writes it when an attempt
+ *starts* — so an attempt that took the process down with it (an OOM on a
+ Pi mid-download) still counts, and a restart loop cannot turn into a
+ download loop.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import shutil
+from collections.abc import Callable, Iterable
+from contextlib import suppress
+from dataclasses import dataclass
+from enum import StrEnum
+from pathlib import Path
+from typing import Final
+
+import structlog
+
+from flightsite.db import utc_now_ms
+from flightsite.metadata.importer import ClockFn
+from flightsite.metadata.registry import SourceStatusRecord
+from flightsite.metadata.service import MetadataService
+
+logger = structlog.get_logger(__name__)
+
+_MS_PER_HOUR: Final = 3_600_000
+_MS_PER_DAY: Final = 24 * _MS_PER_HOUR
+
+#: ``metadata.auto_update_days``: the default, and the bounds of a non-zero
+#: value. :class:`~flightsite.config.models.MetadataSettings` spells the same
+#: numbers as literals (it cannot import this module); a test asserts they agree.
+DEFAULT_AUTO_UPDATE_DAYS: Final = 30
+MIN_AUTO_UPDATE_DAYS: Final = 7
+MAX_AUTO_UPDATE_DAYS: Final = 365
+
+#: How long after startup the first tick waits. An upgrade or a restart is
+#: the moment the owner is watching the Pi come back; a 300 MB download
+#: starting under them would slow exactly that.
+STARTUP_GRACE_S: Final = 30 * 60
+
+#: How often the updater asks what is due. An hour is nothing against a
+#: 30-day interval and keeps an idle tick to one small read an hour.
+TICK_INTERVAL_S: Final = 60 * 60
+
+#: Back-off after a failed (or interrupted) attempt, and the longer one a
+#: source moves to once it has been overdue for :data:`ESCALATE_AFTER_MS`.
+RETRY_BACKOFF_MS: Final = _MS_PER_DAY
+ESCALATED_BACKOFF_MS: Final = 7 * _MS_PER_DAY
+ESCALATE_AFTER_MS: Final = 7 * _MS_PER_DAY
+
+#: Free bytes the data volume must have before a *scheduled* run starts.
+#: An import stages a second copy of the source's rows beside the live ones
+#: and the swap grows the WAL by about that much again, on top of the download
+#: itself (ADR-0021 "Unattended risks"). 2 GiB covers the largest source
+#: (Mictronics, ~620k airframes, a few hundred MB through the pipeline) with
+#: room to spare on a Pi's SD card. A manual run is not guarded: the owner is
+#: there to see it fail.
+MIN_FREE_BYTES: Final = 2 * 1024**3
+
+#: After a skipped run is recorded in the Activity feed, how long before
+#: another skip is recorded. The guard is re-checked every tick; the feed is
+#: not told about it every hour.
+SKIP_NOTICE_INTERVAL_MS: Final = _MS_PER_DAY
+
+#: Reads the configured interval in days, live.
+IntervalFn = Callable[[], int]
+#: Free bytes on the filesystem holding a directory, or ``None`` if unknown.
+FreeSpaceFn = Callable[[Path], int | None]
+
+
+def _free_space(directory: Path) -> int | None:
+ try:
+ return shutil.disk_usage(directory).free
+ except OSError:
+ return None
+
+
+def next_due_ms(record: SourceStatusRecord, *, interval_days: int) -> int | None:
+ """When ``record``'s source is next due an automatic update, or ``None``.
+
+ ``None`` means never automatically: automatic updates are off
+ (``interval_days`` is ``0``) or the source has never succeeded. The
+ result can be in the past — that is a source already due.
+ """
+ if interval_days <= 0 or record.last_success_ms is None:
+ return None
+ due_ms = record.last_success_ms + interval_days * _MS_PER_DAY
+ attempt_ms = record.last_attempt_ms
+ if attempt_ms is not None and attempt_ms > record.last_success_ms:
+ # The newest attempt did not succeed: it failed, or it never finished.
+ overdue_ms = attempt_ms - due_ms
+ backoff_ms = ESCALATED_BACKOFF_MS if overdue_ms >= ESCALATE_AFTER_MS else RETRY_BACKOFF_MS
+ due_ms = max(due_ms, attempt_ms + backoff_ms)
+ return due_ms
+
+
+@dataclass(frozen=True, slots=True)
+class SourceSchedule:
+ """One source's place in the automatic-update schedule."""
+
+ source: str
+ #: When it is next due (see :func:`next_due_ms`); ``None`` = never automatically.
+ next_ms: int | None
+ #: Due now: ``next_ms`` has passed and the source is not already running.
+ due: bool
+
+
+def plan_auto_update(
+ statuses: Iterable[SourceStatusRecord],
+ *,
+ registered: Iterable[str],
+ interval_days: int,
+ now_ms: int,
+) -> tuple[SourceSchedule, ...]:
+ """The schedule for every registered source, in ``statuses`` order.
+
+ A stored row for a source this build no longer registers is left out: there
+ is nothing to run it with.
+ """
+ names = frozenset(registered)
+ plan: list[SourceSchedule] = []
+ for record in statuses:
+ if record.source not in names:
+ continue
+ next_ms = next_due_ms(record, interval_days=interval_days)
+ due = next_ms is not None and now_ms >= next_ms and not record.run.running
+ plan.append(SourceSchedule(source=record.source, next_ms=next_ms, due=due))
+ return tuple(plan)
+
+
+class TickOutcome(StrEnum):
+ """What one tick did — returned for tests and logged for operators."""
+
+ OFF = "off"
+ NOTHING_DUE = "nothing_due"
+ BUSY = "busy"
+ SKIPPED_LOW_DISK = "skipped_low_disk"
+ STARTED = "started"
+
+
+class MetadataAutoUpdater:
+ """The clock behind scheduled metadata updates.
+
+ Started by the lifespan hook only on a healthy schema and never in demo
+ mode (ADR-0021): it reads ``metadata_sources``, which a failed migration
+ may not have created, and a demo has no business downloading anything.
+
+ Args:
+ service: the metadata service whose single-flight run it starts.
+ interval_days: reads ``metadata.auto_update_days`` — live, every tick.
+ data_dir: the data volume the free-space guard measures.
+ clock: UTC epoch milliseconds, injected for tests.
+ free_space: free bytes under a directory, injected for tests.
+ grace_s: delay before the first tick.
+ tick_s: delay between ticks.
+ min_free_bytes: the free-space guard's threshold.
+ """
+
+ __slots__ = (
+ "_clock",
+ "_data_dir",
+ "_free_space",
+ "_grace_s",
+ "_interval_days",
+ "_min_free_bytes",
+ "_not_before_ms",
+ "_service",
+ "_skip_notice_until_ms",
+ "_task",
+ "_tick_s",
+ )
+
+ def __init__(
+ self,
+ *,
+ service: MetadataService,
+ interval_days: IntervalFn,
+ data_dir: Path,
+ clock: ClockFn = utc_now_ms,
+ free_space: FreeSpaceFn = _free_space,
+ grace_s: float = STARTUP_GRACE_S,
+ tick_s: float = TICK_INTERVAL_S,
+ min_free_bytes: int = MIN_FREE_BYTES,
+ ) -> None:
+ self._service = service
+ self._interval_days = interval_days
+ self._data_dir = Path(data_dir)
+ self._clock = clock
+ self._free_space = free_space
+ self._grace_s = grace_s
+ self._tick_s = tick_s
+ self._min_free_bytes = min_free_bytes
+ self._task: asyncio.Task[None] | None = None
+ self._not_before_ms: int | None = None
+ self._skip_notice_until_ms = 0
+
+ @property
+ def running(self) -> bool:
+ """True between :meth:`start` and :meth:`stop`."""
+ return self._task is not None and not self._task.done()
+
+ def interval_days(self) -> int:
+ """The configured interval, read now; ``0`` = off."""
+ return self._interval_days()
+
+ async def start(self) -> None:
+ """Start the tick loop. Idempotent."""
+ if self.running:
+ return
+ self._not_before_ms = self._clock() + int(self._grace_s * 1000)
+ self._task = asyncio.create_task(self._loop(), name="metadata-auto-update")
+ logger.info(
+ "metadata_auto_update_started",
+ interval_days=self._interval_days(),
+ grace_s=self._grace_s,
+ )
+
+ async def stop(self) -> None:
+ """Stop the tick loop. Idempotent, and safe before start.
+
+ Only the loop: a run it started is the service's, and the service's
+ :meth:`~flightsite.metadata.service.MetadataService.cancel_update` is
+ what shutdown calls for that.
+ """
+ task = self._task
+ self._task = None
+ if task is None or task.done():
+ return
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+
+ def schedule(self, statuses: Iterable[SourceStatusRecord]) -> tuple[SourceSchedule, ...]:
+ """The current schedule over ``statuses``, for ``GET /metadata/status``.
+
+ Each ``next_ms`` is moved past the startup grace when it falls inside
+ it, because that is the earliest a run can actually start; the hourly
+ tick means it starts within the hour after that.
+ """
+ plan = plan_auto_update(
+ statuses,
+ registered=self._service.registry.names,
+ interval_days=self._interval_days(),
+ now_ms=self._clock(),
+ )
+ floor = self._not_before_ms
+ if floor is None:
+ return plan
+ return tuple(
+ entry
+ if entry.next_ms is None or entry.next_ms >= floor
+ else SourceSchedule(source=entry.source, next_ms=floor, due=entry.due)
+ for entry in plan
+ )
+
+ async def tick(self) -> TickOutcome:
+ """Decide once, and start a run of every due source if there are any."""
+ interval_days = self._interval_days()
+ if interval_days <= 0:
+ return TickOutcome.OFF
+ if self._service.updating:
+ # A run is already in flight — manual or an earlier tick's. Its
+ # sources' rows change when it ends; the next tick decides afresh.
+ return TickOutcome.BUSY
+ now_ms = self._clock()
+ plan = plan_auto_update(
+ await self._service.statuses(),
+ registered=self._service.registry.names,
+ interval_days=interval_days,
+ now_ms=now_ms,
+ )
+ due = tuple(entry.source for entry in plan if entry.due)
+ if not due:
+ return TickOutcome.NOTHING_DUE
+
+ free = self._free_space(self._data_dir)
+ if free is not None and free < self._min_free_bytes:
+ reason = (
+ f"Automatic update skipped: {_gib(free)} free on the data volume, "
+ f"at least {_gib(self._min_free_bytes)} needed"
+ )
+ logger.warning(
+ "metadata_auto_update_skipped",
+ reason="low_disk",
+ free_bytes=free,
+ required_bytes=self._min_free_bytes,
+ sources=list(due),
+ )
+ if now_ms >= self._skip_notice_until_ms:
+ self._skip_notice_until_ms = now_ms + SKIP_NOTICE_INTERVAL_MS
+ await self._service.record_skipped(due, reason=reason)
+ return TickOutcome.SKIPPED_LOW_DISK
+
+ ticket = self._service.start_update(due, automatic=True)
+ return TickOutcome.STARTED if ticket.started else TickOutcome.BUSY
+
+ async def _loop(self) -> None:
+ await asyncio.sleep(self._grace_s)
+ while True:
+ try:
+ outcome = await self.tick()
+ logger.debug("metadata_auto_update_tick", outcome=outcome.value)
+ except Exception as exc:
+ # A tick that fails (a locked read, a bug) must not end the
+ # schedule; the next tick decides afresh.
+ logger.error(
+ "metadata_auto_update_tick_failed",
+ error=str(exc),
+ error_type=type(exc).__name__,
+ )
+ await asyncio.sleep(self._tick_s)
+
+
+def _gib(value: int) -> str:
+ return f"{value / 1024**3:.1f} GiB"
+
+
+__all__ = [
+ "DEFAULT_AUTO_UPDATE_DAYS",
+ "ESCALATED_BACKOFF_MS",
+ "ESCALATE_AFTER_MS",
+ "MAX_AUTO_UPDATE_DAYS",
+ "MIN_AUTO_UPDATE_DAYS",
+ "MIN_FREE_BYTES",
+ "RETRY_BACKOFF_MS",
+ "STARTUP_GRACE_S",
+ "TICK_INTERVAL_S",
+ "MetadataAutoUpdater",
+ "SourceSchedule",
+ "TickOutcome",
+ "next_due_ms",
+ "plan_auto_update",
+]
diff --git a/backend/src/flightsite/metadata/importer.py b/backend/src/flightsite/metadata/importer.py
index 30f69404..bee854fa 100644
--- a/backend/src/flightsite/metadata/importer.py
+++ b/backend/src/flightsite/metadata/importer.py
@@ -127,6 +127,17 @@ class ImportRun:
results: tuple[SourceImportResult, ...] = ()
started_ms: int = 0
finished_ms: int = 0
+ #: True when the scheduler started this run rather than a person (SPEC §27
+ #: owner amendment of 2026-11-30, ADR-0021). Set by
+ #: :class:`~flightsite.metadata.service.MetadataService`; the importer
+ #: itself neither knows nor cares who asked.
+ automatic: bool = False
+ #: True when this "run" never ran: an automatic update that was due but
+ #: was skipped before downloading anything (ADR-0021's free-space guard).
+ #: Every result is then a failure whose ``error`` is the reason, no
+ #: ``metadata_sources`` row was touched, and the listeners see it only so
+ #: the Activity feed can say why the update did not happen.
+ skipped: bool = False
@property
def succeeded(self) -> tuple[str, ...]:
diff --git a/backend/src/flightsite/metadata/service.py b/backend/src/flightsite/metadata/service.py
index 2716eab8..d0d1055a 100644
--- a/backend/src/flightsite/metadata/service.py
+++ b/backend/src/flightsite/metadata/service.py
@@ -28,12 +28,22 @@
repopulation for no new data — which is why the two are no longer one branch.
A listener that only cares about fresh data still guards on ``run.succeeded``,
exactly as the airport index rebuild does.
+
+Slice 131 moves the **single-flight** rule in here too. It used to live in the
+``POST /api/internal/metadata/update`` handler as ``app.state.metadata_update_task``,
+which was enough while that handler was the only thing that could start a run.
+The scheduled updater of ADR-0021 is a second caller, and two callers each
+guarding their own task would race each other over the same staging rows — so
+the in-flight task is the service's, and :meth:`MetadataService.start_update`
+is the one way either caller starts a background run.
"""
from __future__ import annotations
+import asyncio
from collections.abc import Awaitable, Callable, Sequence
-from dataclasses import replace
+from contextlib import suppress
+from dataclasses import dataclass, replace
from pathlib import Path
import structlog
@@ -42,8 +52,13 @@
from flightsite.db import Database, utc_now_ms
from flightsite.live.store import LiveStore
from flightsite.metadata.cache import AircraftMetadataView, MetadataCache, OnResolvedFn
-from flightsite.metadata.importer import ClockFn, ImportRun, MetadataImporter
-from flightsite.metadata.registry import SourceRegistry, SourceStatusRecord
+from flightsite.metadata.importer import (
+ ClockFn,
+ ImportRun,
+ MetadataImporter,
+ SourceImportResult,
+)
+from flightsite.metadata.registry import ImportPhase, SourceRegistry, SourceStatusRecord
from flightsite.metadata.repository import MetadataRepository
logger = structlog.get_logger(__name__)
@@ -55,6 +70,20 @@
ImportListener = Callable[[ImportRun], Awaitable[None]]
+@dataclass(frozen=True, slots=True)
+class UpdateTicket:
+ """What :meth:`MetadataService.start_update` did.
+
+ ``started`` is false when a run was already in flight and the call
+ coalesced onto it; ``started_ms`` and ``task`` are then that run's, so a
+ second trigger can report the same start the first one did.
+ """
+
+ started: bool
+ started_ms: int
+ task: asyncio.Task[ImportRun]
+
+
class MetadataService:
"""Import orchestration plus the live metadata cache.
@@ -74,7 +103,16 @@ class MetadataService:
Slice 037 wires the watchlist matcher's index update in here.
"""
- __slots__ = ("_cache", "_importer", "_listeners", "_registry", "_repository")
+ __slots__ = (
+ "_cache",
+ "_clock",
+ "_importer",
+ "_listeners",
+ "_registry",
+ "_repository",
+ "_update_started_ms",
+ "_update_task",
+ )
def __init__(
self,
@@ -94,6 +132,9 @@ def __init__(
)
self._cache = MetadataCache(database=database, live=live, on_resolved=on_resolved)
self._listeners = tuple(listeners)
+ self._clock = clock
+ self._update_task: asyncio.Task[ImportRun] | None = None
+ self._update_started_ms: int | None = None
@property
def cache(self) -> MetadataCache:
@@ -157,20 +198,122 @@ async def lookup(self, icao24: str) -> AircraftMetadataView | None:
classification=classify(evidence),
)
- async def update(self, sources: Sequence[str] | None = None) -> ImportRun:
+ async def update(
+ self, sources: Sequence[str] | None = None, *, automatic: bool = False
+ ) -> ImportRun:
"""Run an import over ``sources`` and refresh the cache if it changed.
- The entrypoint behind slice 025's "Update Aircraft Metadata" action.
- Returns per-source results — including failures, which are results
- rather than exceptions because the user needs to see which sources
- worked (SPEC §27).
+ The import itself, awaited in place. Returns per-source results —
+ including failures, which are results rather than exceptions because
+ the user needs to see which sources worked (SPEC §27). ``automatic``
+ marks a run the scheduler started (ADR-0021), which the Activity feed
+ says.
+
+ **Not single-flight.** This is the run, not the guard around it: the
+ "Update Aircraft Metadata" action and the scheduled updater both go
+ through :meth:`start_update`, which is. Calling this directly while a
+ background run is in flight would race it over the staging rows.
"""
run = await self._importer.run(sources)
+ if automatic:
+ run = replace(run, automatic=True)
if run.changed_data:
await self._cache.invalidate()
await self._notify(run)
return run
+ @property
+ def update_task(self) -> asyncio.Task[ImportRun] | None:
+ """The background run :meth:`start_update` last started, if any."""
+ return self._update_task
+
+ @property
+ def updating(self) -> bool:
+ """True while a background run started by :meth:`start_update` is in flight."""
+ return self._update_task is not None and not self._update_task.done()
+
+ def start_update(
+ self, sources: Sequence[str] | None = None, *, automatic: bool = False
+ ) -> UpdateTicket:
+ """Start :meth:`update` as a background task, or join the one in flight.
+
+ The single-flight rule for every caller (slice 025's endpoint and
+ ADR-0021's scheduler). ``MetadataImporter`` imports its sources one at
+ a time, and two overlapping runs would race each other over the same
+ staging rows; so a call that arrives while a run is in flight starts
+ nothing and returns that run's ticket. Synchronous on purpose: there
+ is no ``await`` between checking for a run and recording the new one,
+ so two callers on the same event loop cannot both observe "not
+ running" and both start one.
+
+ A coalesced call does not widen the running one: a manual trigger that
+ lands during an automatic run of one stale source gets that run, not a
+ run of every source. That is the same answer a second click has always
+ had, and the user can press the button again when it finishes.
+ """
+ task = self._update_task
+ if task is not None and not task.done():
+ started_ms = self._update_started_ms
+ return UpdateTicket(
+ started=False,
+ started_ms=started_ms if started_ms is not None else self._clock(),
+ task=task,
+ )
+ started_ms = self._clock()
+ task = asyncio.create_task(
+ self.update(sources, automatic=automatic), name="metadata-update"
+ )
+ task.add_done_callback(_log_update_task_result)
+ self._update_task = task
+ self._update_started_ms = started_ms
+ logger.info(
+ "metadata_update_started",
+ started_ms=started_ms,
+ automatic=automatic,
+ sources=None if sources is None else list(sources),
+ )
+ return UpdateTicket(started=True, started_ms=started_ms, task=task)
+
+ async def cancel_update(self) -> None:
+ """Cancel a background run still in flight, and wait for it to unwind.
+
+ Called at shutdown: a run outlives the request (or the tick) that
+ started it, so one can still be in flight when the process stops.
+ Cancelling it rather than abandoning it means the writer session it
+ holds rolls back cleanly (``Database.writer_session`` catches
+ ``BaseException``) instead of racing the engines disposing under it.
+ """
+ task = self._update_task
+ if task is None or task.done():
+ return
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+
+ async def record_skipped(self, sources: Sequence[str], *, reason: str) -> ImportRun:
+ """Tell the listeners an automatic update of ``sources`` was skipped.
+
+ No import ran and no ``metadata_sources`` row changes — a skip is not
+ an attempt, so it must not start a back-off or mark a source failed on
+ the Health page. It exists so the Activity feed can say why a due
+ update did not happen (ADR-0021's free-space guard): each source gets a
+ failed result whose error is ``reason``, on a run marked ``automatic``
+ and ``skipped``.
+ """
+ at_ms = self._clock()
+ run = ImportRun(
+ results=tuple(
+ SourceImportResult(source=name, ok=False, phase=ImportPhase.DOWNLOAD, error=reason)
+ for name in sources
+ ),
+ started_ms=at_ms,
+ finished_ms=at_ms,
+ automatic=True,
+ skipped=True,
+ )
+ await self._notify(run)
+ return run
+
async def _notify(self, run: ImportRun) -> None:
"""Run the post-import listeners, surviving any of them failing.
@@ -212,4 +355,24 @@ def _with_run(record: SourceStatusRecord, registry: SourceRegistry) -> SourceSta
return replace(record, run=registry.run_state(record.source))
-__all__ = ["ImportListener", "MetadataService"]
+def _log_update_task_result(task: asyncio.Task[ImportRun]) -> None:
+ """Consume a finished background run's exception, if any, into the log.
+
+ Nothing ``await``s this task directly — the request or tick that started
+ it has already moved on, which is the entire point of running it in the
+ background — so nothing else would ever retrieve an exception it raised.
+ Without this callback, a bug here would only surface as asyncio's "Task
+ exception was never retrieved" warning at the next garbage collection,
+ with no context to debug it, instead of a clean log line naming what
+ happened. This is distinct from a source failing its own import: that is
+ caught inside :meth:`~flightsite.metadata.MetadataImporter.run` and
+ reported through ``GET /metadata/status`` as a result, never raised here.
+ """
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.error("metadata_update_task_failed", error=str(exc), error_type=type(exc).__name__)
+
+
+__all__ = ["ImportListener", "MetadataService", "UpdateTicket"]
diff --git a/backend/tests/activity/test_producers.py b/backend/tests/activity/test_producers.py
index 6679b93d..63b5fc24 100644
--- a/backend/tests/activity/test_producers.py
+++ b/backend/tests/activity/test_producers.py
@@ -461,6 +461,28 @@ def test_each_source_of_a_run_gets_its_own_event() -> None:
assert batch.events[1].payload["error"] == "ConnectError: timed out"
+def test_an_automatic_or_skipped_run_says_so() -> None:
+ """Slice 131: the feed tells a scheduled run, and a skipped one, from a click."""
+ batch = import_events(
+ [
+ ImportOutcome(source="faa", ok=True, finished_ms=NOW_MS),
+ ImportOutcome(source="mictronics", ok=True, finished_ms=NOW_MS, automatic=True),
+ ImportOutcome(
+ source="routes",
+ ok=False,
+ finished_ms=NOW_MS,
+ error="Automatic update skipped: 0.1 GiB free on the data volume",
+ automatic=True,
+ skipped=True,
+ ),
+ ]
+ )
+
+ flags = [(event.payload["automatic"], event.payload["skipped"]) for event in batch.events]
+ assert flags == [(False, False), (True, False), (True, True)]
+ assert batch.events[2].severity is Severity.INTERESTING
+
+
def test_two_runs_of_the_same_source_are_two_events() -> None:
"""Updating metadata twice is two results, and the key says so."""
first = import_events([ImportOutcome(source="faa", ok=True, finished_ms=NOW_MS)])
diff --git a/backend/tests/api/test_metadata_api.py b/backend/tests/api/test_metadata_api.py
index b87941f9..153a2c68 100644
--- a/backend/tests/api/test_metadata_api.py
+++ b/backend/tests/api/test_metadata_api.py
@@ -20,12 +20,13 @@
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
-from flightsite.api.internal import _log_update_task_result
from flightsite.app import create_app
from flightsite.live import LiveStore
from flightsite.logging import configure_logging
from flightsite.metadata import ImportRun, MetadataService, SourceRegistry
+from flightsite.metadata.autoupdate import MetadataAutoUpdater
from flightsite.metadata.registry import ImportPhase
+from flightsite.metadata.service import _log_update_task_result
from ..metadata.conftest import record
from ..metadata.provider import InMemoryMetadataProvider
@@ -83,6 +84,14 @@ async def _wait_started(provider: InMemoryMetadataProvider) -> None:
await provider.started.wait()
+def _update_task(app: FastAPI) -> asyncio.Task[ImportRun]:
+ """The background run the last trigger started — the service's, since slice 131."""
+ metadata: MetadataService = app.state.metadata
+ task = metadata.update_task
+ assert task is not None
+ return task
+
+
async def _status_by_name(client: AsyncClient) -> dict[str, dict[str, object]]:
response = await client.get(METADATA_STATUS_PATH)
assert response.status_code == 200
@@ -115,7 +124,7 @@ async def test_trigger_returns_before_the_run_completes(
assert statuses["mictronics"]["status"] == "running"
hold.set()
- await app.state.metadata_update_task
+ await _update_task(app)
statuses = await _status_by_name(client)
assert statuses["mictronics"]["status"] == "ok"
@@ -150,7 +159,7 @@ async def test_concurrent_trigger_coalesces_onto_the_running_run(
assert provider.downloads == 1
hold.set()
- await app.state.metadata_update_task
+ await _update_task(app)
assert provider.downloads == 1
@@ -161,14 +170,14 @@ async def test_a_second_trigger_after_completion_starts_a_new_run(
registry.register("mictronics", provider)
first = await client.post(METADATA_UPDATE_PATH)
- await app.state.metadata_update_task
+ await _update_task(app)
assert first.json()["started"] is True
second = await client.post(METADATA_UPDATE_PATH)
assert second.json()["started"] is True
assert second.json()["already_running"] is False
- await app.state.metadata_update_task
+ await _update_task(app)
assert provider.downloads == 2
@@ -189,6 +198,8 @@ async def test_status_reports_never_run_for_a_fresh_source(
"dataset_version": None,
"row_count": None,
"last_error": None,
+ # Never succeeded, so never updated automatically (ADR-0021).
+ "next_auto_update_ms": None,
}
@@ -204,7 +215,7 @@ async def test_one_source_failing_does_not_affect_the_others_status(
response = await client.post(METADATA_UPDATE_PATH)
assert response.status_code == 202
- await app.state.metadata_update_task
+ await _update_task(app)
statuses = await _status_by_name(client)
@@ -226,11 +237,11 @@ async def test_a_later_failure_leaves_an_earlier_success_reported_intact(
registry.register("mictronics", provider)
await client.post(METADATA_UPDATE_PATH)
- await app.state.metadata_update_task
+ await _update_task(app)
provider.fail_at = ImportPhase.DOWNLOAD
await client.post(METADATA_UPDATE_PATH)
- await app.state.metadata_update_task
+ await _update_task(app)
statuses = await _status_by_name(client)
assert statuses["mictronics"]["status"] == "failed"
@@ -268,7 +279,7 @@ async def test_shutdown_cancels_an_in_flight_update_task(isolated_data_dir: Path
response = await async_client.post(METADATA_UPDATE_PATH)
assert response.status_code == 202
await _wait_started(provider)
- task = application.state.metadata_update_task
+ task = application.state.metadata.update_task
assert task is not None
assert task.cancelled()
@@ -309,3 +320,65 @@ async def _boom() -> ImportRun:
output = captured.out + captured.err
assert "metadata_update_task_failed" in output
assert "cache invalidation exploded" in output
+
+
+# ------------------------------------------------- scheduled updates (slice 131)
+
+
+async def test_status_reports_the_automatic_update_schedule(
+ app: FastAPI, client: AsyncClient, registry: SourceRegistry
+) -> None:
+ registry.register("mictronics", InMemoryMetadataProvider([RECORD_A]))
+ registry.register("faa", InMemoryMetadataProvider([RECORD_A]))
+ updater: MetadataAutoUpdater | None = app.state.metadata_auto_update
+ assert updater is not None
+ assert updater.running is True
+
+ before = (await client.get(METADATA_STATUS_PATH)).json()
+ assert before["auto_update"] == {"enabled": True, "interval_days": 30, "next_ms": None}
+
+ await app.state.metadata.start_update(["mictronics"]).task
+
+ body = (await client.get(METADATA_STATUS_PATH)).json()
+ by_name = {entry["name"]: entry for entry in body["sources"]}
+ expected = by_name["mictronics"]["last_success_ms"] + 30 * 86_400_000
+ assert by_name["mictronics"]["next_auto_update_ms"] == expected
+ assert by_name["faa"]["next_auto_update_ms"] is None
+ assert body["auto_update"] == {"enabled": True, "interval_days": 30, "next_ms": expected}
+
+
+async def test_status_reports_automatic_updates_off_when_set_to_zero(
+ app: FastAPI, client: AsyncClient, registry: SourceRegistry
+) -> None:
+ registry.register("mictronics", InMemoryMetadataProvider([RECORD_A]))
+ await app.state.metadata.start_update().task
+
+ saved = await client.put("/api/internal/config", json={"metadata": {"auto_update_days": 0}})
+ assert saved.status_code == 200
+
+ body = (await client.get(METADATA_STATUS_PATH)).json()
+ assert body["auto_update"] == {"enabled": False, "interval_days": 0, "next_ms": None}
+ assert body["sources"][0]["next_auto_update_ms"] is None
+
+
+async def test_an_out_of_range_interval_is_rejected(client: AsyncClient) -> None:
+ response = await client.put("/api/internal/config", json={"metadata": {"auto_update_days": 3}})
+
+ assert response.status_code == 422
+
+
+async def test_demo_mode_never_starts_the_scheduler(
+ isolated_data_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("FLIGHTSITE_DEMO", "1")
+ application = create_app(isolated_data_dir)
+
+ async with application.router.lifespan_context(application):
+ assert application.state.metadata_auto_update is None
+ async with AsyncClient(
+ transport=ASGITransport(app=application), base_url="http://testserver"
+ ) as async_client:
+ body = (await async_client.get(METADATA_STATUS_PATH)).json()
+
+ assert body["auto_update"]["enabled"] is False
+ assert body["auto_update"]["next_ms"] is None
diff --git a/backend/tests/metadata/test_autoupdate.py b/backend/tests/metadata/test_autoupdate.py
new file mode 100644
index 00000000..1e9825a4
--- /dev/null
+++ b/backend/tests/metadata/test_autoupdate.py
@@ -0,0 +1,453 @@
+"""Scheduled metadata updates (slice 131, SPEC §27 owner amendment, ADR-0021).
+
+Two layers, tested separately. The decision — :func:`next_due_ms` and
+:func:`plan_auto_update` — is a pure function of the stored source rows, the
+interval and the time, so its rules are stated as a table. The clock —
+:class:`MetadataAutoUpdater` — is driven tick by tick against a real
+:class:`~flightsite.metadata.MetadataService` over in-memory providers and a
+hand-moved clock, so what is asserted is the real import path (the same
+single-flight run the Settings button uses), not a stand-in. Nothing here
+touches the network.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+
+from flightsite.config.models import MetadataSettings
+from flightsite.db import Database
+from flightsite.live import LiveStore
+from flightsite.metadata import ImportRun, MetadataService, SourceRegistry
+from flightsite.metadata.autoupdate import (
+ DEFAULT_AUTO_UPDATE_DAYS,
+ ESCALATED_BACKOFF_MS,
+ MAX_AUTO_UPDATE_DAYS,
+ MIN_AUTO_UPDATE_DAYS,
+ RETRY_BACKOFF_MS,
+ MetadataAutoUpdater,
+ TickOutcome,
+ next_due_ms,
+ plan_auto_update,
+)
+from flightsite.metadata.registry import (
+ ImportPhase,
+ SourceRunState,
+ SourceStatus,
+ SourceStatusRecord,
+)
+
+from .conftest import IMPORT_MS, record
+from .provider import InMemoryMetadataProvider
+
+DAY_MS = 86_400_000
+HOUR_MS = 3_600_000
+T0 = IMPORT_MS
+
+RECORD_A = record("a00001", registration="N1AA", type_code="B738")
+RECORD_B = record("a00002", registration="N2BB", type_code="A320")
+
+
+def status(
+ source: str = "mictronics",
+ *,
+ last_success_ms: int | None = T0,
+ last_attempt_ms: int | None = None,
+ running: bool = False,
+) -> SourceStatusRecord:
+ return SourceStatusRecord(
+ source=source,
+ status=SourceStatus.OK if last_success_ms is not None else SourceStatus.NEVER_RUN,
+ last_success_ms=last_success_ms,
+ last_attempt_ms=last_attempt_ms if last_attempt_ms is not None else last_success_ms,
+ run=SourceRunState(running=running),
+ )
+
+
+# ------------------------------------------------------------------ decision
+
+
+def test_a_source_is_due_one_interval_after_its_last_success() -> None:
+ assert next_due_ms(status(), interval_days=30) == T0 + 30 * DAY_MS
+
+
+def test_zero_days_is_off() -> None:
+ assert next_due_ms(status(), interval_days=0) is None
+
+
+def test_a_source_that_never_succeeded_is_never_run_automatically() -> None:
+ """Ruling 21: the first import of a source stays a manual act."""
+ never_run = status(last_success_ms=None)
+ failed_only = status(last_success_ms=None, last_attempt_ms=T0)
+
+ assert next_due_ms(never_run, interval_days=30) is None
+ assert next_due_ms(failed_only, interval_days=30) is None
+
+
+def test_a_failed_attempt_backs_off_a_day_from_the_attempt() -> None:
+ due = T0 + 30 * DAY_MS
+ failed = status(last_attempt_ms=due + HOUR_MS)
+
+ assert next_due_ms(failed, interval_days=30) == due + HOUR_MS + RETRY_BACKOFF_MS
+
+
+def test_an_attempt_that_never_finished_backs_off_too() -> None:
+ """``last_attempt_ms`` is written when an attempt starts: a crash counts."""
+ due = T0 + 30 * DAY_MS
+ interrupted = SourceStatusRecord(
+ source="mictronics",
+ status=SourceStatus.OK, # the crash never got to record a failure
+ last_success_ms=T0,
+ last_attempt_ms=due,
+ )
+
+ assert next_due_ms(interrupted, interval_days=30) == due + RETRY_BACKOFF_MS
+
+
+def test_a_source_failing_for_a_week_backs_off_a_week() -> None:
+ due = T0 + 30 * DAY_MS
+ week_overdue = status(last_attempt_ms=due + 7 * DAY_MS)
+
+ assert next_due_ms(week_overdue, interval_days=30) == due + 7 * DAY_MS + ESCALATED_BACKOFF_MS
+
+
+def test_a_manual_failure_before_the_due_date_does_not_move_it() -> None:
+ failed_early = status(last_attempt_ms=T0 + 2 * DAY_MS)
+
+ assert next_due_ms(failed_early, interval_days=30) == T0 + 30 * DAY_MS
+
+
+def test_the_plan_is_per_source() -> None:
+ """Ruling 19: each source keeps its own clock; one run takes all that are due."""
+ plan = plan_auto_update(
+ [
+ status("faa", last_success_ms=T0),
+ status("mictronics", last_success_ms=T0 + 10 * DAY_MS),
+ status("airports", last_success_ms=None),
+ status("routes", last_success_ms=T0, running=True),
+ status("retired", last_success_ms=T0),
+ ],
+ registered=["faa", "mictronics", "airports", "routes"],
+ interval_days=30,
+ now_ms=T0 + 31 * DAY_MS,
+ )
+
+ assert [(entry.source, entry.due) for entry in plan] == [
+ ("faa", True),
+ ("mictronics", False),
+ ("airports", False),
+ ("routes", False), # already running
+ ]
+ assert plan[1].next_ms == T0 + 40 * DAY_MS
+ assert plan[2].next_ms is None
+
+
+# --------------------------------------------------------------- the setting
+
+
+def test_the_setting_defaults_to_thirty_days() -> None:
+ assert MetadataSettings().auto_update_days == DEFAULT_AUTO_UPDATE_DAYS == 30
+
+
+@pytest.mark.parametrize("value", [0, MIN_AUTO_UPDATE_DAYS, 30, MAX_AUTO_UPDATE_DAYS])
+def test_the_setting_accepts_zero_or_the_range(value: int) -> None:
+ assert MetadataSettings(auto_update_days=value).auto_update_days == value
+
+
+@pytest.mark.parametrize("value", [-1, 1, MIN_AUTO_UPDATE_DAYS - 1, MAX_AUTO_UPDATE_DAYS + 1])
+def test_the_setting_rejects_values_outside_the_range(value: int) -> None:
+ with pytest.raises(ValidationError):
+ MetadataSettings(auto_update_days=value)
+
+
+# ------------------------------------------------------------------ the clock
+
+
+class Clock:
+ """A hand-moved UTC epoch-millisecond clock."""
+
+ def __init__(self, now_ms: int) -> None:
+ self.now_ms = now_ms
+
+ def __call__(self) -> int:
+ return self.now_ms
+
+ def advance(self, ms: int) -> None:
+ self.now_ms += ms
+
+
+class Harness:
+ """A real service and updater on one hand-moved clock."""
+
+ def __init__(
+ self, service: MetadataService, clock: Clock, runs: list[ImportRun], data_dir: Path
+ ) -> None:
+ self.service = service
+ self.clock = clock
+ self.runs = runs
+ self.interval_days = 30
+ self.free_bytes: int | None = None
+ self.updater = MetadataAutoUpdater(
+ service=service,
+ interval_days=lambda: self.interval_days,
+ data_dir=data_dir,
+ clock=clock,
+ free_space=lambda _path: self.free_bytes,
+ grace_s=0,
+ tick_s=3600,
+ )
+
+ async def tick(self) -> TickOutcome:
+ outcome = await self.updater.tick()
+ task = self.service.update_task
+ if task is not None:
+ await task
+ return outcome
+
+
+@pytest.fixture
+async def harness(
+ database: Database, live: LiveStore, registry: SourceRegistry, isolated_data_dir: Path
+) -> AsyncIterator[Harness]:
+ clock = Clock(T0)
+ runs: list[ImportRun] = []
+
+ async def capture(run: ImportRun) -> None:
+ runs.append(run)
+
+ service = MetadataService(
+ database=database,
+ live=live,
+ data_dir=isolated_data_dir,
+ registry=registry,
+ clock=clock,
+ listeners=(capture,),
+ )
+ await service.start()
+ instance = Harness(service, clock, runs, isolated_data_dir)
+ try:
+ yield instance
+ finally:
+ await instance.updater.stop()
+ await service.cancel_update()
+ await service.stop()
+
+
+async def _manual_import(harness: Harness) -> None:
+ await harness.service.start_update().task
+
+
+async def test_nothing_runs_on_an_install_that_never_imported(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ harness.clock.advance(365 * DAY_MS)
+
+ assert await harness.tick() is TickOutcome.NOTHING_DUE
+ assert provider.downloads == 0
+
+
+async def test_a_stale_source_is_updated_through_the_same_run_path(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A], version="v1")
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+ assert harness.runs[-1].automatic is False
+
+ harness.clock.advance(30 * DAY_MS - HOUR_MS)
+ assert await harness.tick() is TickOutcome.NOTHING_DUE
+ assert provider.downloads == 1
+
+ harness.clock.advance(HOUR_MS)
+ provider.version = "v2"
+ assert await harness.tick() is TickOutcome.STARTED
+
+ assert provider.downloads == 2
+ run = harness.runs[-1]
+ assert run.automatic is True
+ assert run.succeeded == ("mictronics",)
+ statuses = {entry.source: entry for entry in await harness.service.statuses()}
+ assert statuses["mictronics"].dataset_version == "v2"
+ assert statuses["mictronics"].last_success_ms == harness.clock.now_ms
+
+
+async def test_only_the_sources_that_are_due_run(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ stale = InMemoryMetadataProvider([RECORD_A])
+ fresh = InMemoryMetadataProvider([RECORD_B])
+ registry.register("mictronics", stale)
+ registry.register("faa", fresh)
+ await _manual_import(harness)
+
+ harness.clock.advance(10 * DAY_MS)
+ await harness.service.start_update(["faa"]).task # a manual run of one source
+
+ harness.clock.advance(20 * DAY_MS)
+ assert await harness.tick() is TickOutcome.STARTED
+
+ assert [result.source for result in harness.runs[-1].results] == ["mictronics"]
+ assert (stale.downloads, fresh.downloads) == (2, 2)
+
+
+async def test_a_failed_source_waits_out_the_back_off(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+
+ provider.fail_at = ImportPhase.DOWNLOAD
+ harness.clock.advance(30 * DAY_MS)
+ assert await harness.tick() is TickOutcome.STARTED
+ assert harness.runs[-1].failed == ("mictronics",)
+
+ harness.clock.advance(HOUR_MS)
+ assert await harness.tick() is TickOutcome.NOTHING_DUE
+ harness.clock.advance(RETRY_BACKOFF_MS - HOUR_MS)
+ assert await harness.tick() is TickOutcome.STARTED
+ assert provider.downloads == 3
+
+
+async def test_a_run_in_flight_is_never_joined_by_a_second(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ """Single-flight across both callers: the scheduler and the button."""
+ hold = asyncio.Event()
+ provider = InMemoryMetadataProvider([RECORD_A], hold=hold)
+ registry.register("mictronics", provider)
+ hold.set()
+ await _manual_import(harness)
+
+ hold.clear()
+ provider.started.clear()
+ harness.clock.advance(30 * DAY_MS)
+ assert await harness.updater.tick() is TickOutcome.STARTED
+ async with asyncio.timeout(2):
+ await provider.started.wait()
+
+ manual = harness.service.start_update()
+ assert manual.started is False
+ assert manual.task is harness.service.update_task
+ assert await harness.updater.tick() is TickOutcome.BUSY
+
+ hold.set()
+ await manual.task
+ assert provider.downloads == 2
+
+
+async def test_a_manual_run_resets_the_clock(harness: Harness, registry: SourceRegistry) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+
+ harness.clock.advance(29 * DAY_MS)
+ await _manual_import(harness)
+ harness.clock.advance(2 * DAY_MS)
+
+ assert await harness.tick() is TickOutcome.NOTHING_DUE
+
+
+async def test_the_interval_is_read_on_every_tick(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+ harness.clock.advance(10 * DAY_MS)
+
+ assert await harness.tick() is TickOutcome.NOTHING_DUE
+ harness.interval_days = 7
+ assert await harness.tick() is TickOutcome.STARTED
+ harness.interval_days = 0
+ harness.clock.advance(365 * DAY_MS)
+ assert await harness.tick() is TickOutcome.OFF
+
+
+async def test_low_disk_skips_the_run_and_says_so_once_a_day(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+ before = {entry.source: entry for entry in await harness.service.statuses()}
+ runs_before = len(harness.runs)
+
+ harness.free_bytes = 100 * 1024**2
+ harness.clock.advance(30 * DAY_MS)
+ assert await harness.tick() is TickOutcome.SKIPPED_LOW_DISK
+
+ assert provider.downloads == 1
+ skipped = harness.runs[-1]
+ assert skipped.skipped is True
+ assert skipped.automatic is True
+ assert skipped.failed == ("mictronics",)
+ assert skipped.results[0].error is not None
+ assert "free on the data volume" in skipped.results[0].error
+ # A skip is not an attempt: the stored row (and so the back-off) is untouched.
+ after = {entry.source: entry for entry in await harness.service.statuses()}
+ assert after["mictronics"].last_attempt_ms == before["mictronics"].last_attempt_ms
+ assert after["mictronics"].status is SourceStatus.OK
+
+ harness.clock.advance(HOUR_MS)
+ assert await harness.tick() is TickOutcome.SKIPPED_LOW_DISK
+ assert len(harness.runs) == runs_before + 1 # no second notice the same day
+
+ harness.free_bytes = None # unknown: never blocks
+ harness.clock.advance(HOUR_MS)
+ assert await harness.tick() is TickOutcome.STARTED
+ assert provider.downloads == 2
+
+
+async def test_the_loop_waits_out_the_grace_then_ticks(
+ harness: Harness, registry: SourceRegistry
+) -> None:
+ provider = InMemoryMetadataProvider([RECORD_A])
+ registry.register("mictronics", provider)
+ await _manual_import(harness)
+ provider.started.clear()
+ harness.clock.advance(31 * DAY_MS)
+
+ await harness.updater.start()
+ assert harness.updater.running is True
+ async with asyncio.timeout(2):
+ await provider.started.wait()
+ await harness.updater.stop()
+
+ assert harness.updater.running is False
+ task = harness.service.update_task
+ assert task is not None
+ await task
+ assert harness.runs[-1].automatic is True
+
+
+async def test_the_schedule_never_promises_a_run_inside_the_grace(
+ database: Database, live: LiveStore, registry: SourceRegistry, isolated_data_dir: Path
+) -> None:
+ clock = Clock(T0)
+ service = MetadataService(
+ database=database, live=live, data_dir=isolated_data_dir, registry=registry, clock=clock
+ )
+ registry.register("mictronics", InMemoryMetadataProvider([RECORD_A]))
+ await service.start_update().task
+ clock.advance(60 * DAY_MS) # long overdue
+ updater = MetadataAutoUpdater(
+ service=service,
+ interval_days=lambda: 30,
+ data_dir=isolated_data_dir,
+ clock=clock,
+ grace_s=1800,
+ )
+ await updater.start()
+ try:
+ (entry,) = updater.schedule(await service.statuses())
+ finally:
+ await updater.stop()
+
+ assert entry.next_ms == clock.now_ms + 1800 * 1000
diff --git a/backend/tests/test_config_api.py b/backend/tests/test_config_api.py
index 199b7047..aa51eff4 100644
--- a/backend/tests/test_config_api.py
+++ b/backend/tests/test_config_api.py
@@ -330,6 +330,8 @@ def test_metadata_section_defaults_opensky_to_off(client: TestClient) -> None:
assert body["config"]["metadata"] == {
"opensky_enabled": False,
"source_url_overrides": {},
+ # Slice 131 (ADR-0021): on by default, every 30 days.
+ "auto_update_days": 30,
}
diff --git a/config.example.yaml b/config.example.yaml
index 0d908313..431bdb00 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -119,8 +119,15 @@ enrichment:
# means off — no provider is constructed and nothing is ever requested. When on,
# it only fills gaps the other sources left empty and never overwrites them.
# See docs/adr/0013-opensky-metadata-source.md.
+#
+# auto_update_days: each source that has been imported at least once is
+# re-imported automatically this many days after its last successful update
+# (the same run as the "Update Aircraft Metadata" button). 0 turns automatic
+# updates off — use it on an install with no internet access. Otherwise 7-365.
+# Applies on save, no restart. See docs/adr/0021-scheduled-metadata-updates.md.
metadata:
opensky_enabled: false
+ auto_update_days: 30
# Browser notifications, enabled per alert severity.
notifications:
From d0b07fd7ca27904e3f2ceb35191278ec50e5ace5 Mon Sep 17 00:00:00 2001
From: Steven Pickles
Date: Mon, 30 Nov 2026 08:55:48 -0500
Subject: [PATCH 12/33] feat(settings): show the next automatic metadata update
The Settings metadata card says when the next automatic update is due (or
that automatic updates are off, or wait for a first manual import), and each
source card shows its own next run. The Activity feed labels automatic and
skipped metadata runs.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
---
.../lib/describeActivityEvent.test.ts | 38 +++++++
.../activity/lib/describeActivityEvent.ts | 16 ++-
.../src/features/settings/lib/draft.test.ts | 4 +-
.../sections/MetadataSection.test.tsx | 107 +++++++++++++++++-
.../settings/sections/MetadataSection.tsx | 57 ++++++++++
frontend/src/lib/api/config.ts | 3 +
frontend/src/lib/api/metadata.ts | 21 ++++
frontend/src/test/configApiMock.ts | 2 +-
frontend/src/test/metadataApiMock.ts | 1 +
9 files changed, 245 insertions(+), 4 deletions(-)
diff --git a/frontend/src/features/activity/lib/describeActivityEvent.test.ts b/frontend/src/features/activity/lib/describeActivityEvent.test.ts
index b3ac14f5..b2d8dfa2 100644
--- a/frontend/src/features/activity/lib/describeActivityEvent.test.ts
+++ b/frontend/src/features/activity/lib/describeActivityEvent.test.ts
@@ -271,6 +271,44 @@ describe("describeActivityEvent", () => {
expect(detail).toBe("ConnectError: no network");
});
+ it("says a metadata update was automatic (slice 131)", () => {
+ expect(
+ describeActivityEvent(
+ event("metadata_updated", {
+ source: "mictronics",
+ ok: true,
+ automatic: true,
+ }),
+ ).label,
+ ).toBe("Metadata updated automatically: mictronics");
+ expect(
+ describeActivityEvent(
+ event("metadata_updated", {
+ source: "faa",
+ ok: false,
+ automatic: true,
+ error: "ConnectError: no network",
+ }),
+ ).label,
+ ).toBe("Automatic metadata update failed: faa");
+ });
+
+ it("says an automatic update was skipped, with the reason", () => {
+ const { label, detail } = describeActivityEvent(
+ event("metadata_updated", {
+ source: "routes",
+ ok: false,
+ automatic: true,
+ skipped: true,
+ error: "Automatic update skipped: 0.4 GiB free on the data volume",
+ }),
+ );
+ expect(label).toBe("Automatic metadata update skipped: routes");
+ expect(detail).toBe(
+ "Automatic update skipped: 0.4 GiB free on the data volume",
+ );
+ });
+
it("treats a metadata event with no `ok` flag as a plain update", () => {
// A missing flag must never invent a failure the backend did not report.
const { label } = describeActivityEvent(
diff --git a/frontend/src/features/activity/lib/describeActivityEvent.ts b/frontend/src/features/activity/lib/describeActivityEvent.ts
index a075f4dc..cfea1fad 100644
--- a/frontend/src/features/activity/lib/describeActivityEvent.ts
+++ b/frontend/src/features/activity/lib/describeActivityEvent.ts
@@ -353,7 +353,21 @@ export function describeActivityEvent(
const failed = bool(payload, "ok") === false;
const rows = num(payload, "rows_imported");
const rejected = num(payload, "rows_rejected");
- const label = failed ? "Metadata update failed" : "Metadata updated";
+ // Slice 131 (ADR-0021): a run the scheduler started says so, and one it
+ // skipped (low disk) is not reported as a failed download. Both flags
+ // are absent from events recorded before slice 131 — read as a manual
+ // run, which is what every one of them was.
+ const automatic = bool(payload, "automatic") === true;
+ const skipped = bool(payload, "skipped") === true;
+ const label = skipped
+ ? "Automatic metadata update skipped"
+ : failed
+ ? automatic
+ ? "Automatic metadata update failed"
+ : "Metadata update failed"
+ : automatic
+ ? "Metadata updated automatically"
+ : "Metadata updated";
return {
label: source === null ? label : `${label}: ${source}`,
detail: failed
diff --git a/frontend/src/features/settings/lib/draft.test.ts b/frontend/src/features/settings/lib/draft.test.ts
index 402b9966..4a8c2915 100644
--- a/frontend/src/features/settings/lib/draft.test.ts
+++ b/frontend/src/features/settings/lib/draft.test.ts
@@ -278,7 +278,9 @@ describe("buildMetadataPatch", () => {
describe("pickMetadata", () => {
it("round-trips the stored value out of a config document", () => {
const draft = draftFromConfig(
- defaultFlightSiteConfig({ metadata: { opensky_enabled: true } }),
+ defaultFlightSiteConfig({
+ metadata: { opensky_enabled: true, auto_update_days: 30 },
+ }),
);
expect(pickMetadata(draft)).toEqual({ openskyEnabled: true });
diff --git a/frontend/src/features/settings/sections/MetadataSection.test.tsx b/frontend/src/features/settings/sections/MetadataSection.test.tsx
index 016b3d12..3549881c 100644
--- a/frontend/src/features/settings/sections/MetadataSection.test.tsx
+++ b/frontend/src/features/settings/sections/MetadataSection.test.tsx
@@ -452,7 +452,9 @@ describe("MetadataSection — the opt-in OpenSky source (ADR-0013)", () => {
it("renders the toggle on when the stored config has it enabled", async () => {
installConfigApiMock();
renderSection(
- defaultFlightSiteConfig({ metadata: { opensky_enabled: true } }),
+ defaultFlightSiteConfig({
+ metadata: { opensky_enabled: true, auto_update_days: 30 },
+ }),
);
expect(await screen.findByTestId("metadata-opensky-toggle")).toBeChecked();
@@ -474,4 +476,107 @@ describe("MetadataSection — the opt-in OpenSky source (ADR-0013)", () => {
expect(await screen.findByText("OpenSky")).toBeInTheDocument();
expect(screen.getByText("Mictronics")).toBeInTheDocument();
});
+
+ describe("automatic updates (slice 131)", () => {
+ const NEXT_MS = Date.UTC(2099, 5, 1, 12, 0, 0);
+ const NEXT_LOCAL = formatReceiverLocalDateTime(
+ new Date(NEXT_MS).toISOString(),
+ TIMEZONE,
+ );
+
+ it("shows the next automatic update, overall and on the source", async () => {
+ installMetadataApiMock({
+ statusSequence: [
+ {
+ sources: [
+ metadataSource({
+ name: "mictronics",
+ status: "ok",
+ last_success_ms: OK_SUCCESS_MS,
+ next_auto_update_ms: NEXT_MS,
+ }),
+ metadataSource({ name: "faa" }),
+ ],
+ auto_update: { enabled: true, interval_days: 30, next_ms: NEXT_MS },
+ },
+ ],
+ });
+ renderSection();
+
+ expect(
+ await screen.findByTestId("metadata-auto-update-line"),
+ ).toHaveTextContent(
+ `Next automatic update: ${NEXT_LOCAL} (every 30 days)`,
+ );
+ const perSource = screen.getAllByTestId("metadata-source-next-auto");
+ expect(perSource).toHaveLength(1);
+ expect(perSource[0]).toHaveTextContent(NEXT_LOCAL);
+ });
+
+ it("says a due update starts within the hour", async () => {
+ installMetadataApiMock({
+ statusSequence: [
+ {
+ sources: [metadataSource({ status: "ok" })],
+ auto_update: {
+ enabled: true,
+ interval_days: 30,
+ next_ms: OK_SUCCESS_MS,
+ },
+ },
+ ],
+ });
+ renderSection();
+
+ expect(
+ await screen.findByTestId("metadata-auto-update-line"),
+ ).toHaveTextContent("Next automatic update: within the hour");
+ });
+
+ it("says when automatic updates are off", async () => {
+ installMetadataApiMock({
+ statusSequence: [
+ {
+ sources: [metadataSource({ status: "ok" })],
+ auto_update: { enabled: false, interval_days: 0, next_ms: null },
+ },
+ ],
+ });
+ renderSection();
+
+ expect(
+ await screen.findByTestId("metadata-auto-update-line"),
+ ).toHaveTextContent("Automatic updates off");
+ });
+
+ it("says the first import stays manual when nothing has been imported", async () => {
+ installMetadataApiMock({
+ statusSequence: [
+ {
+ sources: [metadataSource()],
+ auto_update: { enabled: true, interval_days: 30, next_ms: null },
+ },
+ ],
+ });
+ renderSection();
+
+ expect(
+ await screen.findByTestId("metadata-auto-update-line"),
+ ).toHaveTextContent(
+ "Automatic updates every 30 days, once a source has been updated here for the first time",
+ );
+ });
+
+ it("says nothing about a schedule an older backend does not report", async () => {
+ installMetadataApiMock({
+ statusSequence: [{ sources: [metadataSource()] }],
+ });
+ renderSection();
+
+ expect(await screen.findByText("Mictronics")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("metadata-auto-update-line"),
+ ).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/features/settings/sections/MetadataSection.tsx b/frontend/src/features/settings/sections/MetadataSection.tsx
index fa08af2e..28d20767 100644
--- a/frontend/src/features/settings/sections/MetadataSection.tsx
+++ b/frontend/src/features/settings/sections/MetadataSection.tsx
@@ -30,6 +30,7 @@ import type { FlightSiteConfig } from "@/lib/api/config";
import {
useMetadataStatusQuery,
useTriggerMetadataUpdateMutation,
+ type MetadataAutoUpdateStatus,
type MetadataSourceStatus,
type MetadataSourceStatusEntry,
} from "@/lib/api/metadata";
@@ -155,6 +156,16 @@ function SourceCard({ source, timezone }: SourceCardProps) {
)}
+ {source.next_auto_update_ms != null && (
+
+ Next automatic update{" "}
+ {formatNextAutoUpdate(source.next_auto_update_ms, timezone)}
+
+ )}
+
{credit !== undefined && (
", or "within the hour" once the due time has passed — the
+ * scheduler ticks hourly, so a past due time means the next tick starts it. */
+function formatNextAutoUpdate(nextMs: number, timezone: string): string {
+ if (nextMs <= Date.now()) {
+ return "within the hour";
+ }
+ return formatReceiverLocalDateTime(epochMsToIso(nextMs), timezone);
+}
+
+/** Slice 131 (SPEC §27 owner amendment, ADR-0021): when the scheduler will
+ * next update a source, or that it will not. Renders nothing until the
+ * status has loaded, and nothing for a backend older than slice 131, which
+ * sends no `auto_update` block — saying "off" there would be a guess. */
+function AutoUpdateLine({
+ autoUpdate,
+ timezone,
+}: {
+ autoUpdate: MetadataAutoUpdateStatus | undefined;
+ timezone: string;
+}) {
+ if (autoUpdate === undefined) {
+ return null;
+ }
+ const every = `every ${autoUpdate.interval_days.toLocaleString()} days`;
+ let text: string;
+ if (!autoUpdate.enabled) {
+ text = "Automatic updates off";
+ } else if (autoUpdate.next_ms === null) {
+ text = `Automatic updates ${every}, once a source has been updated here for the first time`;
+ } else {
+ text = `Next automatic update: ${formatNextAutoUpdate(autoUpdate.next_ms, timezone)} (${every})`;
+ }
+ return (
+
+ {text}
+
+ );
+}
+
/** A source card's shape with none of its content known yet — rendered
* while the status is still loading, so the first paint is not indistinguishable
* from "no sources are registered" (R4-11). Not a `SourceCard` with dummy
@@ -371,6 +424,10 @@ export function MetadataSection({ timezone, config }: MetadataSectionProps) {
isPending={statusQuery.isPending}
isError={statusQuery.isError}
/>
+