diff --git a/.github/dependabot.yml b/.github/dependabot.yml index bc70c6d2..8b1f670f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -110,6 +110,16 @@ updates: # @types/node tracks the Node 24 runtime; lift with the next LTS move. - dependency-name: "@types/node" update-types: ["version-update:semver-major"] + # Playwright 1.65.x ships Firefox build 1572 (Firefox 159), whose content + # process segfaults when `ariaLabelledByElements` is read from both the + # page (axe-core) and Playwright's isolated world (a named getByRole): + # Mozilla bug 2090055, microsoft/playwright#43967 and #44135, fixed by + # microsoft/playwright#43982 for 1.66 (issue #383, roadmap slice 132). + # 1.64.1 (Firefox 157) is pinned until then. Remove this rule when + # Dependabot offers 1.66.0, and take that bump only once the Firefox + # axe scans in e2e pass on it. + - dependency-name: "@playwright/test" + versions: [">= 1.65.0, < 1.66.0"] groups: # @playwright/test is pinned exactly and must stay in lockstep with the # container image in .github/workflows/visual.yml diff --git a/.github/workflows/visual.yml b/.github/workflows/visual.yml index 838cbdd6..b515b09f 100644 --- a/.github/workflows/visual.yml +++ b/.github/workflows/visual.yml @@ -49,7 +49,7 @@ jobs: # different browser builds. scripts/visual.mjs fails the run if the # installed Playwright and this image disagree. container: - image: mcr.microsoft.com/playwright:v1.65.1-noble + image: mcr.microsoft.com/playwright:v1.64.1-noble # Chromium's default 64 MB /dev/shm is too small for the full-page # screenshots of the Analytics and Receiver pages. options: --ipc=host diff --git a/CHANGELOG.md b/CHANGELOG.md index fcca4d58..187b64f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,122 @@ follows [Keep a Changelog](https://keepachangelog.com/); versions follow [Semantic Versioning](https://semver.org/) (`0.x.y` during pre-1.0 development). This file is updated only on release branches (see `docs/RELEASE.md`). +## [0.18.0] — 2026-11-30 + +Metadata that keeps itself current, and feeder status you can believe after a restart. +FlightSite now runs "Update Aircraft Metadata" on its own every 30 days (an owner +amendment to SPEC §27). ADS-B Exchange and AeroDataBox no longer show as offline after a +backend restart because of a routine readsb warning. "Locally rare type" rules stop +matching every airframe of a newly heard type. Every way of selecting an aircraft on the +Live Map now brings it into view, and a full read pool answers with a clear, retryable 503 +instead of a 500. The end-to-end suite no longer crashes in Firefox. No database migration. + +### Added +- **Scheduled metadata updates** (SPEC §27 owner amendment, 2026-11-30; ADR-0021): each + metadata source is updated automatically once its last successful update is older than + `metadata.auto_update_days` (new optional setting; default 30, `0` turns it off, otherwise + 7–365). There is no Settings control yet (#381), so edit `config.yaml` and restart the + backend to change it. + - Sources that fall due within a day of each other are updated together in one run, so a + source may be updated up to 24 h before the date shown for it. A failing source that is + waiting out its back-off does not join. + - The first import of each source stays manual, so a fresh or offline install never + starts a download nobody asked for. + - A failed source is retried after 24 h, then weekly once it has been overdue a week. + - Nothing starts in the first 30 minutes after the backend starts. + - A run is skipped, with one Activity entry a day, when the volume holding the data + directory (`/opt/flightsite/data`) has less than 2 GiB free. + - Never in demo mode. + - Settings shows the next automatic update, overall and for each source. Activity marks + automatic and skipped runs. A manual update and an automatic one never run at once. +- **`read_pool_exhausted`** (roadmap 123; ADR-0020 amended): when every read connection is + busy, an `/api/v1` request now waits at most 5 s for each read and then answers `503` with + error code `read_pool_exhausted` and `Retry-After: 5`, instead of failing after 30 s with + an unmapped 500. The pages retry it as before. Background work keeps the long wait. + Events are counted as `read_pool_exhaustions` in `/api/v1/health` and diagnostics. + `/api/v1/receiver` and the "Since T0" views answer the same way rather than treating a + busy pool as an unknown T0. + +### Fixed +- **ADS-B Exchange and AeroDataBox shown as offline after a restart** (#369): readsb's + periodic "Bad connection, dropping data (connection lost N% of data)" warning was read as + a disconnect, so after a restart those feeds showed down, Health went Degraded and two + "Feed offline" self-alerts were raised, until readsb next reconnected. + - Only readsb's real connect and disconnect lines now decide whether a Beast output is + connected; the wording is taken from readsb's own source. + - The warning can only mark a feed degraded: when it is at most 15 minutes old and reports + at least 1.0% lost. It never marks a feed down. readsb counts that figure over the + connection's whole life, so the message says "N% lost since it connected". + - An unrecognised readsb line keeps the previous status and is logged once as a warning. +- **"Locally rare type" rules matched every airframe of a newly heard type** (#364): the + per-type airframe count was refreshed only at start-up and after a metadata import. + - The count for a type is now re-read whenever a new airframe of that type is saved, and + the rule waits until the count includes it. + - This runs only while an enabled rule has a rare-type condition, so installs without one + pay nothing. + - No rule on the reference install uses a rare-type condition, so no data clean-up is + needed. +- **Selecting an aircraft did not always bring it into view** (#362): picking one from the + Interesting list, cycling with the keyboard, or opening a `?selected=` link now moves the + map to it. Interesting-list rows and keyboard cycling move the map only when the aircraft + is off screen; on a phone, the area under the bottom sheet counts as off screen. + Clicking a marker still only selects it. + - A `?selected=` link opened on a fresh page load is no longer pulled back to the + receiver when the configuration arrives. + +### Documentation +- **Upgrade check** (#366): `docs/INSTALL.md` §8.1's backend-first upgrade waits on + `/api/v1/health`, then checks `/api/v1/ready` once. It starts the frontend only when that + answers 200, and says what to do after a failed migration or a failed integrity check. +- `docs/DEVELOPMENT.md` explains when a data-only Alembic revision is atomic and asks each + one to carry a rollback test. +- ADR-0017 and the Feeders page design note how Beast-output lines are now read. + `docs/DATA_MODEL.md` records that `aircraft` rows are never deleted. + +### Development +- New end-to-end spec `04-selected-deep-link-focus` checks that a `?selected=` link brings + the aircraft into view. +- The end-to-end suite's Playwright is pinned to 1.64.1 (#383, slice 132). Under + Playwright 1.65, Firefox crashes when an accessibility scan and Playwright both read an + element's ARIA references (Mozilla bug 2090055), which failed the Receiver and Health + scans intermittently. Playwright 1.64 does not read them that way, so it does not + trigger the crash. Dependabot skips 1.65.x; the fix arrives with Playwright 1.66. + +### Upgrade notes +- No migration; a plain `docker compose pull && docker compose up -d` is enough. Taking a + backup first is still recommended. +- **Automatic metadata updates are on by default** (every 30 days) for sources you have + imported at least once. + - An install whose metadata is older than that starts its first automatic update about + 30 minutes after the backend starts. It runs the same import as the Settings button, + so expect the same download size and run time. + - FlightSite now contacts the metadata sources (and OpenSky, if you enabled and imported + it) on its own; `docs/SECURITY.md` lists them. + - To keep updates manual, set `metadata.auto_update_days: 0` in `config.yaml` and restart + the backend. Do this on an install with no internet access: otherwise every due source + fails once a day for a week and weekly after that, each failure adding an Activity + entry and turning Health's metadata section Degraded. +- `read_pool_exhaustions` is a new counter in `/api/v1/health` and diagnostics. +- The host SDR watchdog's version moves to 0.18.0 with FlightSite but its code is + unchanged; re-running its installer is optional. + +### Known issues +- #309: TypeScript 7 waits for typescript-eslint support. +- #374: on desktop, an aircraft hidden under the detail or Interesting panel counts as in + view, so keyboard cycling does not move the map to it. +- #375: the Beast-output loss figure covers the connection's whole life, not a current + rate. +- #376: readsb's DNS-failure lines are not matched, and "Ignoring this DNS reply" warns at + every retry. +- #377: diagnostics reports a busy read pool as "database unreachable". +- #380: Aircraft detail: the type count on a newly heard type reads 0 until the next + metadata load (the alert rule itself is fixed). +- #381: there is no Settings control for the automatic-update interval; edit `config.yaml` + and restart. +- #382: the Mictronics and routes downloads are held in memory while they are imported. +- #386: the Settings metadata-sources loading placeholder carries an `aria-label` without a + role; the Settings accessibility scan can flag it if it runs before the status loads. + ## [0.17.0] — 2026-11-29 Alerts you can trust again, and list queries that cannot run away. The "First-ever diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 568345ff..d5566646 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "flightsite" -version = "0.17.0" +version = "0.18.0" description = "FlightSite backend: self-hosted ADS-B observatory API and ingestion service." readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/backend/src/flightsite/activity/facts.py b/backend/src/flightsite/activity/facts.py index c87a5a37..28a3dbfe 100644 --- a/backend/src/flightsite/activity/facts.py +++ b/backend/src/flightsite/activity/facts.py @@ -135,6 +135,13 @@ 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 + #: Every source a skipped run would have updated. A skip is one outcome + #: for the whole run (``source`` is these names joined), not one per source. + sources: tuple[str, ...] = () @dataclass(frozen=True, slots=True) diff --git a/backend/src/flightsite/activity/producers.py b/backend/src/flightsite/activity/producers.py index 0e94af50..db4829b4 100644 --- a/backend/src/flightsite/activity/producers.py +++ b/backend/src/flightsite/activity/producers.py @@ -539,9 +539,27 @@ 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. A skip is one event for the + whole run: its ``source`` is the due sources joined with ``", "`` and its + payload adds the list as ``sources``. Additive per ``docs/API.md`` §6. """ events: list[NewActivityEvent] = [] for outcome in outcomes: + payload: dict[str, Any] = { + "source": outcome.source, + "ok": outcome.ok, + "rows_imported": outcome.rows_imported, + "rows_rejected": outcome.rows_rejected, + "dataset_version": outcome.dataset_version, + "error": outcome.error, + "automatic": outcome.automatic, + "skipped": outcome.skipped, + } + if outcome.skipped: + payload["sources"] = list(outcome.sources) events.append( NewActivityEvent( type=ActivityEventType.METADATA_UPDATED, @@ -550,14 +568,7 @@ def import_events(outcomes: Iterable[ImportOutcome]) -> ActivityBatch: ActivityEventType.METADATA_UPDATED.value, outcome.source, outcome.finished_ms ), severity=Severity.INFO if outcome.ok else Severity.INTERESTING, - payload={ - "source": outcome.source, - "ok": outcome.ok, - "rows_imported": outcome.rows_imported, - "rows_rejected": outcome.rows_rejected, - "dataset_version": outcome.dataset_version, - "error": outcome.error, - }, + payload=payload, ) ) return ActivityBatch(events=tuple(events)) diff --git a/backend/src/flightsite/activity/service.py b/backend/src/flightsite/activity/service.py index 1aeb3d69..c4741ec2 100644 --- a/backend/src/flightsite/activity/service.py +++ b/backend/src/flightsite/activity/service.py @@ -345,6 +345,22 @@ async def record_import(self, run: ImportRun) -> None: service's own transaction, so a feed failure can never turn a successful import into a failed request. """ + if run.skipped: + # Slice 131: a skipped automatic run is one piece of news — "the + # update did not happen, and why" — not one failure per source. + names = tuple(result.source for result in run.results) + self._pending_imports.append( + ImportOutcome( + source=", ".join(names), + ok=False, + finished_ms=run.finished_ms, + error=run.results[0].error if run.results else None, + automatic=True, + skipped=True, + sources=names, + ) + ) + return for result in run.results: self._pending_imports.append( ImportOutcome( @@ -355,6 +371,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/alerts/engine.py b/backend/src/flightsite/alerts/engine.py index 28098696..29205bdd 100644 --- a/backend/src/flightsite/alerts/engine.py +++ b/backend/src/flightsite/alerts/engine.py @@ -43,8 +43,9 @@ ≤50 ms/500-aircraft budget above, which is measured on a full live set. The re-evaluation set is the aircraft whose metadata the cache had not resolved, -or whose sighting the persistence worker had not given ids yet, when they were -last looked at. Every condition is a requirement and an unknown input fails +whose sighting the persistence worker had not given ids yet, or whose resolved +type the cache had not yet counted them in (issue #364), when they were last +looked at. Every condition is a requirement and an unknown input fails it (:mod:`flightsite.alerts.evaluator`), so a military aircraft must not be decided against on the half-second before its classification arrives. Keeping the set explicit rather than re-scanning the live set is what keeps "no full @@ -210,6 +211,13 @@ class AircraftAlertState: #: comes out one high — and an aircraft that then never updates again must #: still get its rarity answered with the right figure (issue #360). awaiting_sighting: bool = True + #: True while this airframe has a resolved type but the cache's count of + #: that type did not yet include it at the last evaluation — its + #: ``aircraft`` row is newer than the type's last read (issue #364). A + #: re-evaluation reason like the two above: the cache re-reads the type on + #: request, and an aircraft that never updates again must still have its + #: ``rare_type`` question answered once the count includes it. + awaiting_type_count: bool = False @dataclass(frozen=True, slots=True) @@ -272,10 +280,15 @@ def subject_for( it, and adding one would count it twice. ``type_aircraft_here`` is distinct airframes of this type ever recorded, - floored at one because *this* aircraft is one of them: the resident type - map is rebuilt when a metadata import completes rather than continuously, - so a type first heard since the last import legitimately reads zero, and a - floor of one is the truthful minimum rather than a guess. + **including this one** (:func:`_type_aircraft_here`): ``None`` until the + worker has committed this airframe's ``aircraft`` row *and* the cache's + count of the type has been read since. Before slice 128 the type map was + re-read only at start and on import, so a type first heard since then read + zero, was floored to one, and every airframe of it matched a ``rare_type`` + rule (issue #364). Now an unknown count fails the condition, the engine + asks the cache to re-read the type, and the airframe stays in the + re-evaluation set until the answer includes it. No floor is needed: a + count that includes this airframe is at least one by construction. """ record = live.get(icao) if record is None: @@ -283,7 +296,7 @@ def subject_for( view = metadata.get(icao) resolved = None if view is None else view.metadata active = persistence.sighting_for(icao) - type_count = None if view is None else view.type_count + type_code = None if resolved is None else resolved.type_code position = record.position return AlertSubject( icao=icao, @@ -302,12 +315,12 @@ def subject_for( longitude=None if position is None else position.longitude, callsign=record.callsign, classification=view.classification if view is not None else _UNKNOWN_CLASSIFICATION, - type_code=None if resolved is None else resolved.type_code, + type_code=type_code, model=None if resolved is None else resolved.model, registration=None if resolved is None else resolved.registration, watchlists=watchlists.matches(icao), sightings_here=_sightings_here(view, active), - type_aircraft_here=None if type_count is None else max(1, type_count), + type_aircraft_here=_type_aircraft_here(metadata, type_code, active), metadata_resolved=view is not None, ) @@ -328,6 +341,20 @@ def _sightings_here(view: AircraftMetadataView | None, active: ActiveSighting | return max(count, 1) if counted else count + 1 +def _type_aircraft_here( + metadata: MetadataCache, type_code: str | None, active: ActiveSighting | None +) -> int | None: + """Airframes of ``type_code`` recorded here including this one, or ``None``. + + ``None`` without a resolved type, before the worker has committed this + airframe's row (no ``aircraft_id`` yet), and while the cache's count of the + type predates that row. See :func:`subject_for`. + """ + if type_code is None or active is None or active.aircraft_id is None: + return None + return metadata.type_count_including(type_code, active.aircraft_id) + + class AlertEngine: """Evaluates rules against live updates and records what matched. @@ -361,6 +388,7 @@ class AlertEngine: "_queue_size", "_repository", "_rules", + "_rules_use_rare_type", "_states", "_subscription", "_task", @@ -391,6 +419,9 @@ def __init__( self._counters = counters self._rules: tuple[CompiledRule, ...] = () + # Whether any enabled rule has a `rare_type` condition: only then is a + # type count worth waiting for, or re-reading (issue #364). + self._rules_use_rare_type = False self._states: dict[str, AircraftAlertState] = {} self._adopted: dict[int, dict[str, AlertSeverity]] = {} self._listeners: list[AlertListener] = [] @@ -491,6 +522,18 @@ def set_rules(self, rules: Iterable[CompiledRule]) -> None: a re-created rule gets a new id and a clean scope. """ self._rules = tuple(rules) + uses_rare_type = any( + compiled.rule.enabled and compiled.rule.conditions.rare_type is not None + for compiled in self._rules + ) + if uses_rare_type and not self._rules_use_rare_type: + # A rare_type rule just came into force: an aircraft already + # evaluated without one may never update again, so give every live + # aircraft one repair pass; it then waits only if its count is + # still unknown. + for state in self._states.values(): + state.awaiting_type_count = True + self._rules_use_rare_type = uses_rare_type def set_alert_radius(self, alert_radius_nm: float | None) -> None: """Update the configured alert radius (SPEC §66).""" @@ -659,11 +702,16 @@ def _collect(self, events: Sequence[LiveEvent]) -> list[str]: continue else: wanted[event.icao] = None - # The repair pass: aircraft whose metadata was still unresolved, or - # whose sighting had no ids yet, when they were last looked at. See - # the module docstring. + # The repair pass: aircraft whose metadata was still unresolved, whose + # sighting had no ids yet, or whose type count did not include them + # yet, when they were last looked at. See the module docstring. for icao, state in self._states.items(): - if state.awaiting_metadata or state.awaiting_sighting or state.pending: + if ( + state.awaiting_metadata + or state.awaiting_sighting + or state.awaiting_type_count + or state.pending + ): wanted.setdefault(icao, None) return list(wanted) @@ -742,6 +790,22 @@ def _state_for(self, icao: str, subject: AlertSubject) -> AircraftAlertState: state.sighting_id = sighting_id state.awaiting_metadata = not subject.metadata_resolved state.awaiting_sighting = sighting_id is None + # A resolved type whose count does not include this airframe yet + # (issue #364). Once the row has ids, ask the cache to re-read the + # type; before that, `awaiting_sighting` already brings it back. Only + # while an enabled rule asks about rare types: otherwise nothing reads + # the count and neither the wait nor the read is worth its cost. + state.awaiting_type_count = ( + self._rules_use_rare_type + and subject.type_code is not None + and subject.type_aircraft_here is None + ) + if ( + state.awaiting_type_count + and subject.type_code is not None + and subject.aircraft_id is not None + ): + self._metadata.request_type_count(subject.type_code) return state # --------------------------------------------------------- the write leg diff --git a/backend/src/flightsite/alerts/evaluator.py b/backend/src/flightsite/alerts/evaluator.py index 7b1a083e..c69e6308 100644 --- a/backend/src/flightsite/alerts/evaluator.py +++ b/backend/src/flightsite/alerts/evaluator.py @@ -131,8 +131,10 @@ def _rarity_holds(conditions: RuleConditions, subject: AlertSubject) -> bool: rare_type = conditions.rare_type if rare_type is None: return True - # No resolved type means the question has no answer, and an unanswered - # requirement fails — the same rule every other condition follows. + # No resolved type, or a count not yet known to include this airframe + # (issue #364), means the question has no answer, and an unanswered + # requirement fails — the same rule every other condition follows. The + # engine re-evaluates once the cache's count includes the airframe. here = subject.type_aircraft_here return here is not None and here <= rare_type.max_sightings diff --git a/backend/src/flightsite/alerts/model.py b/backend/src/flightsite/alerts/model.py index ffe803e3..55d4f436 100644 --- a/backend/src/flightsite/alerts/model.py +++ b/backend/src/flightsite/alerts/model.py @@ -787,7 +787,10 @@ class AlertSubject: sightings_here: int | None = None #: Distinct airframes of this aircraft's type ever recorded here, #: including this one. ``None`` when no metadata source has resolved a - #: type, in which case a ``rare_type`` condition cannot be satisfied. + #: type, and also while the count is not yet known to include this + #: airframe (its ``aircraft`` row is not committed, or the type was last + #: counted before it was, issue #364). Either way a ``rare_type`` + #: condition cannot be satisfied until it is known. type_aircraft_here: int | None = None #: False while the metadata cache has not resolved this airframe yet. The diff --git a/backend/src/flightsite/api/context.py b/backend/src/flightsite/api/context.py index 21679c42..43dd3835 100644 --- a/backend/src/flightsite/api/context.py +++ b/backend/src/flightsite/api/context.py @@ -86,7 +86,14 @@ ) from flightsite.api.sightings import SightingsRepository from flightsite.config import Settings -from flightsite.db import Database, MetaRepository, from_epoch_ms, to_epoch_ms, utc_now_ms +from flightsite.db import ( + Database, + MetaRepository, + ReadPoolExhausted, + from_epoch_ms, + to_epoch_ms, + utc_now_ms, +) from flightsite.live import LiveAircraft, LiveStore from flightsite.metadata import MetadataCache, MetadataService from flightsite.receiver_metrics import MetricsRepository, ReceiverMetricsService @@ -569,10 +576,17 @@ async def _t0(self) -> datetime | None: payload is pure configuration, and the live picture behind it is fine. An unreadable T0 is therefore reported as "unknown" (§2.7) rather than as a 500, with the reason logged once per read. + + A busy read pool is not an unreadable T0: :exc:`ReadPoolExhausted` + propagates, so the request answers ``503 read_pool_exhausted`` and is + counted, instead of waiting a second bound for its next read or + answering 200 with T0 silently unknown (slice 123). """ database: Database = self._app.state.database try: t0_ms = await MetaRepository(database).get_t0() + except ReadPoolExhausted: + raise except Exception as exc: logger.warning("t0_unavailable", error=str(exc), error_type=type(exc).__name__) return None 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/api/read_pool.py b/backend/src/flightsite/api/read_pool.py new file mode 100644 index 00000000..30418b5e --- /dev/null +++ b/backend/src/flightsite/api/read_pool.py @@ -0,0 +1,134 @@ +"""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 + +import math +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 whole seconds: one checkout bound. +RETRY_AFTER_S: Final = math.ceil(API_READ_CHECKOUT_TIMEOUT_S) + +#: 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..1fcfc59a 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": { @@ -225,6 +227,9 @@ def _bound_ms(moment: datetime | None) -> int | None: @router.get("/health", tags=["service"]) async def health(request: Request) -> dict[str, Any]: """Liveness endpoint: always 200 once the app is answering requests.""" + # Must not read the database. This is the Docker healthcheck's target and + # sits inside the /api/v1 read-checkout bound (slice 123): a read here + # would turn a busy read pool into a failed liveness probe. start_time: float = request.app.state.start_time uptime_s = time.monotonic() - start_time return { diff --git a/backend/src/flightsite/app.py b/backend/src/flightsite/app.py index 1317cb2d..96fa515c 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 @@ -38,11 +37,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 @@ -67,6 +71,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 +323,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 +789,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 +833,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 +849,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 +943,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 +1244,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 @@ -1228,7 +1265,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/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/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/src/flightsite/feeders/ultrafeeder.py b/backend/src/flightsite/feeders/ultrafeeder.py index 0605126e..460bbb61 100644 --- a/backend/src/flightsite/feeders/ultrafeeder.py +++ b/backend/src/flightsite/feeders/ultrafeeder.py @@ -30,16 +30,53 @@ 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 +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 discards half the output for a while, because it could not + write everything (two seconds) or because the remote asked it to reduce + with a ``W S`` command. ``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 since +it connected)"); 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. +``N`` is a lifetime share of the connection, not a current rate, so the +threshold is coarse. On a long-lived connection a fresh, severe episode may +never reach it and reads ``up`` (ten minutes of half-drop on a two-day +connection is about 0.2%); a connection that lost data early reads +``degraded`` for 15 minutes on any later two-second hiccup; and a young +connection overstates its loss. + A silent log is not evidence (slice 101, issue #276) ----------------------------------------------------- @@ -61,7 +98,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 +143,23 @@ #: 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. N is a lifetime share of the +#: connection, not a current rate: a severe episode late in a long connection +#: may never reach this (ten minutes of half-drop on a two-day connection is +#: about 0.2%), a connection that lost data early stays over it on every later +#: hiccup, and a young connection overstates. +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 +204,61 @@ 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)". Called on a +#: write shortfall (flushClient, flushWrites) and on a remote "W S" reduce +#: command. +_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 +273,10 @@ class UltrafeederProbe: "_host", "_log_cursor_s", "_log_newest_ms", + "_loss", "_mlat_port", "_name", + "_unrecognised_seen", "_url", "_zero_peer_polls", ) @@ -200,6 +308,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 +367,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 and key not in 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 since it connected)" + 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 +488,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 +515,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 +547,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/src/flightsite/metadata/autoupdate.py b/backend/src/flightsite/metadata/autoupdate.py new file mode 100644 index 00000000..a5cbbb2b --- /dev/null +++ b/backend/src/flightsite/metadata/autoupdate.py @@ -0,0 +1,406 @@ +"""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, + confirmed by the owner on 2026-11-30). 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. +5. Once any source is due, every other source that would fall due within + :data:`COALESCE_HORIZON_MS` (24 h) — and whose newest attempt succeeded, + so it is in no back-off — runs with it. Without this, "one run" would not + survive its first cycle: the importer stamps each source's + ``last_success_ms`` with that source's own start time, so sources imported + together fall due minutes apart and would split across successive ticks. +""" + +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 + +#: Once a source is due, sources falling due within this horizon join its run +#: (rule 5 above), so sources imported together stay together. +COALESCE_HORIZON_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. ``next_ms`` is each source's own due time; a + source can run earlier than that when it is coalesced into another's run + (rule 5 in the module docstring). + """ + names = frozenset(registered) + rows: list[tuple[SourceStatusRecord, int | None]] = [ + (record, next_due_ms(record, interval_days=interval_days)) + for record in statuses + if record.source in names + ] + any_due = any( + next_ms is not None and now_ms >= next_ms and not record.run.running + for record, next_ms in rows + ) + plan: list[SourceSchedule] = [] + for record, next_ms in rows: + due = ( + any_due + and next_ms is not None + and not record.run.running + and ( + now_ms >= next_ms or (_settled(record) and next_ms - now_ms <= COALESCE_HORIZON_MS) + ) + ) + plan.append(SourceSchedule(source=record.source, next_ms=next_ms, due=due)) + return tuple(plan) + + +def _settled(record: SourceStatusRecord) -> bool: + """True when the source's newest attempt succeeded — it is in no back-off.""" + return record.last_attempt_ms is None or ( + record.last_success_ms is not None and record.last_attempt_ms <= record.last_success_ms + ) + + +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" + ) + # Warn (and tell the feed) once a day, not every tick: an hourly + # warning would crowd the diagnostics error ring for as long as + # the disk stays full. Ticks in between log at debug. + notify = now_ms >= self._skip_notice_until_ms + log = logger.warning if notify else logger.debug + log( + "metadata_auto_update_skipped", + reason="low_disk", + free_bytes=free, + required_bytes=self._min_free_bytes, + sources=list(due), + ) + if notify: + 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__ = [ + "COALESCE_HORIZON_MS", + "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/cache.py b/backend/src/flightsite/metadata/cache.py index a10684ea..b3653230 100644 --- a/backend/src/flightsite/metadata/cache.py +++ b/backend/src/flightsite/metadata/cache.py @@ -33,9 +33,13 @@ same function, so the two cannot disagree. * **A rarity counter per live aircraft** — ``aircraft.sighting_count``, the lifetime figure of ``docs/DATA_MODEL.md`` §2.2 — loaded in the same batch. -* **The full type-count map**, a few thousand entries, refreshed with the rest - on import completion. Small enough to hold whole, and holding it whole is - what makes "how rare is this type?" a dict lookup. +* **The full type-count map**, a few thousand entries, reloaded whole at start + and on import completion. Small enough to hold whole, and holding it whole is + what makes "how rare is this type?" a dict lookup. Each entry also records + the newest airframe it covers, and between imports one type is re-read when + an airframe newer than that is persisted + (:meth:`MetadataCache.request_type_count`, issue #364) — see "Type counts + between imports" below. Population is *batched*, and the batching is free. ``LiveStore.apply`` runs a whole decoder poll synchronously without awaiting, so by the time this task is @@ -82,12 +86,46 @@ (:meth:`MetadataCache.invalidate`). Repopulating the *live set* rather than lazily per aircraft matters: the live set is what the WebSocket is about to send, and a lazy refill would show every live aircraft as unknown for one poll. + +Type counts between imports +--------------------------- + +An airframe's type comes only from ``aircraft_metadata_resolved``, which only +an import writes, and an import ends in :meth:`MetadataCache.invalidate`. So +the one thing that moves a type's count between imports is a new ``aircraft`` +row, written by the persistence worker when it opens a never-seen airframe's +first sighting. Until slice 128 the map ignored that: a type first heard since +the last reload read zero, the engine floored it to one, and every airframe of +the type looked like the only one (issue #364). + +The fix is a targeted, idempotent re-read rather than a blind ``+1``. Each +entry is a :class:`~flightsite.metadata.repository.TypeCount` whose +``through_aircraft_id`` is the newest ``aircraft.id`` of the type at the read. +:meth:`MetadataCache.type_count_including` answers only when that mark reaches +the asking airframe's id (the count was read after its row committed) and +``None`` otherwise; the alert engine then calls +:meth:`MetadataCache.request_type_count`, which re-reads that one type on a +task of its own, under the population lock so it cannot interleave with an +import's reload. A re-read can never double count: it is the full load's +query restricted to one type. + +The mark relies on ``aircraft`` ids only growing: rows are never deleted, and +``id`` is a plain ``INTEGER PRIMARY KEY``, so SQLite would hand a deleted +highest id out again (``docs/DATA_MODEL.md`` §2.2). A slice that prunes +airframes must revisit this. + +One window self-heals rather than being locked out: a re-read that runs after +an import's swap has committed but before its :meth:`MetadataCache.invalidate` +reads the new dataset beside views that still describe the old one. Invalidate +follows at once and reloads every count and view under the same lock, and an +airframe whose type count is still not covering it simply asks again. """ from __future__ import annotations import asyncio import contextlib +import time from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field, replace from typing import Final @@ -106,7 +144,7 @@ ) from flightsite.live.store import LiveStore from flightsite.metadata.precedence import ResolvedMetadata -from flightsite.metadata.repository import AircraftLookup, MetadataRepository +from flightsite.metadata.repository import AircraftLookup, MetadataRepository, TypeCount logger = structlog.get_logger(__name__) @@ -121,6 +159,11 @@ #: limit once the repository chunks its ``IN`` clauses. MAX_BATCH: Final = 512 +#: Least time between two "type count re-read failed" warnings. A re-read is +#: asked again on every engine cycle while its airframe waits, so a database +#: that keeps failing would otherwise log once a second per waiting type. +TYPE_COUNT_WARNING_INTERVAL_S: Final = 300.0 + #: A cache observer: called with an aircraft's address and its freshly #: resolved view, or ``None`` when the aircraft left the live set. See the #: module docstring's "Observing resolved views" section. @@ -154,7 +197,11 @@ class AircraftMetadataView: #: set inside its closure gap), and then the trailing-by-one note above #: does not hold (issue #360). latest_sighting_id: int | None = None - #: Unique airframes ever recorded of this aircraft's resolved type. + #: Unique airframes ever recorded of this aircraft's resolved type, **as of + #: the moment this view was built**: a snapshot for display, frozen until + #: the aircraft is next resolved. The alert engine does not read it; it + #: asks :meth:`MetadataCache.type_count_including`, which follows the live + #: map (issue #364). type_count: int | None = None #: Display name of the curated operator group (SPEC §38), or ``None`` when #: the exact operator matched no group. The exact operator is on @@ -213,12 +260,17 @@ class MetadataCache: "_live", "_lock", "_on_resolved", + "_populating", "_populations", "_queue_size", "_repository", "_subscription", "_task", + "_type_count_failures", + "_type_count_warned_at", "_type_counts", + "_type_counts_loaded", + "_type_refreshes", ) def __init__( @@ -235,7 +287,21 @@ def __init__( self._on_resolved = on_resolved self._entries: dict[str, AircraftMetadataView] = {} - self._type_counts: dict[str, int] = {} + self._type_counts: dict[str, TypeCount] = {} + # False until the first full load: before it, every type count is + # unknown rather than zero (issue #364). + self._type_counts_loaded = False + # One-type re-reads in flight, keyed by type so a type is never read + # twice at once however many airframes ask. + self._type_refreshes: dict[str, asyncio.Task[None]] = {} + # Re-read failures since the last warning, and when that warning was + # logged (monotonic seconds); see TYPE_COUNT_WARNING_INTERVAL_S. + self._type_count_failures = 0 + self._type_count_warned_at: float | None = None + # True from the moment the population task takes an event until it + # has installed what the event asked for. The idle flag is set only + # by whichever of it and a re-read finishes last (`_settle_idle`). + self._populating = False self._subscription: EventSubscription | None = None self._task: asyncio.Task[None] | None = None self._populations = 0 @@ -295,18 +361,57 @@ def sighting_count(self, icao: str) -> int | None: entry = self._entries.get(icao) return None if entry is None else entry.sighting_count - def type_count(self, type_code: str) -> int: - """Unique airframes ever recorded of ``type_code``. + def type_count(self, type_code: str) -> int | None: + """Unique airframes ever recorded of ``type_code``, as the map holds it. - Zero for an unseen type, which is the truthful answer: the map holds - every type the receiver has ever recorded, so absence is a count of - none rather than a missing entry. + Zero for a type absent from the map: the map holds every type the + receiver had recorded when it was read, so absence is a count of none + rather than a missing entry. ``None`` before the map's first load, + when nothing is known yet. A display figure; the alert engine asks + :meth:`type_count_including` instead. """ - return self._type_counts.get(type_code, 0) + if not self._type_counts_loaded: + return None + entry = self._type_counts.get(type_code) + return 0 if entry is None else entry.airframes def type_counts(self) -> Mapping[str, int]: """A snapshot of the resident type-count map.""" - return dict(self._type_counts) + return {code: entry.airframes for code, entry in self._type_counts.items()} + + def type_count_including(self, type_code: str, aircraft_id: int) -> int | None: + """``type_code``'s airframe count, if it already includes ``aircraft_id``. + + ``None`` (unknown) before the map's first load, and whenever the + type's entry was read before that airframe's ``aircraft`` row + committed, i.e. its mark is below the id. The caller then calls + :meth:`request_type_count`, and the answer after the re-read includes + the airframe. Pure memory, like every other lookup here. See the + module docstring's "Type counts between imports". + """ + if not self._type_counts_loaded: + return None + entry = self._type_counts.get(type_code) + if entry is None or entry.through_aircraft_id < aircraft_id: + return None + return entry.airframes + + def request_type_count(self, type_code: str) -> None: + """Re-read ``type_code``'s count soon, on a task of the cache's own. + + Never awaits and never touches SQLite on the caller's task, so the + alert engine can ask from its evaluation pass. A request while the + type is already being re-read, or before the cache has started and + made its first full load (which covers it anyway), is a no-op. + """ + if not self.running or not self._type_counts_loaded: + return + if type_code in self._type_refreshes: + return + self._idle.clear() + self._type_refreshes[type_code] = asyncio.create_task( + self._refresh_type_count(type_code), name="flightsite-metadata-type-count" + ) # -------------------------------------------------------------- lifecycle @@ -335,7 +440,16 @@ async def start(self) -> None: async def stop(self) -> None: """Stop the population task and release the subscription. Idempotent.""" + # Not running from here on, so no new re-read can be requested while + # the ones in flight are cancelled. task, self._task = self._task, None + refreshes = list(self._type_refreshes.values()) + self._type_refreshes.clear() + for refresh in refreshes: + refresh.cancel() + for refresh in refreshes: + with contextlib.suppress(asyncio.CancelledError): + await refresh if task is not None and not task.done(): task.cancel() with contextlib.suppress(asyncio.CancelledError): @@ -355,9 +469,14 @@ async def wait_idle(self) -> None: (:func:`tests.metadata.conftest.settle` is what does that). Tests wait on this rather than sleeping, which is what makes the latency measurement measure the cache rather than a polling interval - (``docs/TEST_STRATEGY.md`` §3). + (``docs/TEST_STRATEGY.md`` §3). A type-count re-read + (:meth:`request_type_count`) counts as work too. """ - await self._idle.wait() + while True: + await self._idle.wait() + if not self._type_refreshes: + return + await asyncio.gather(*self._type_refreshes.values(), return_exceptions=True) # ------------------------------------------------------------ invalidation @@ -392,6 +511,7 @@ async def _loop(self) -> None: return while True: event = await subscription.get() + self._populating = True self._idle.clear() try: # Held across collect and populate together: see the lock's @@ -407,8 +527,22 @@ async def _loop(self) -> None: error_type=type(exc).__name__, ) finally: - if subscription.pending == 0: - self._idle.set() + self._populating = False + self._settle_idle() + + def _settle_idle(self) -> None: + """Set the idle flag if nothing is left to do. + + Called by the population task and by a re-read as each finishes. A + re-read can finish while the population task holds an event and waits + on the lock that re-read held, so neither may set the flag on its own + account alone. + """ + if self._populating or self._type_refreshes: + return + subscription = self._subscription + if subscription is None or subscription.pending == 0: + self._idle.set() def _collect(self, first: LiveEvent, subscription: EventSubscription) -> list[str]: """Apply queued lifecycle events; return addresses needing resolution. @@ -535,11 +669,48 @@ def _notify(self, icao: str, view: AircraftMetadataView | None) -> None: async def _reload_type_counts(self) -> None: self._type_counts = await self._repository.load_type_counts() + self._type_counts_loaded = True + + async def _refresh_type_count(self, type_code: str) -> None: + """Re-read one type's count and mark (issue #364). + + Under the population lock, so a re-read cannot land between an + import's clear and its reload carrying a pre-import figure, nor after + the reload carrying a stale one. + """ + try: + async with self._lock: + entry = await self._repository.load_type_count(type_code) + if entry is None: + self._type_counts.pop(type_code, None) + else: + self._type_counts[type_code] = entry + except Exception as exc: + # A failed re-read leaves the count unknown for the airframe that + # asked; its next evaluation asks again, so the warning is + # rate-limited rather than logged per attempt. + self._type_count_failures += 1 + now = time.monotonic() + last = self._type_count_warned_at + if last is None or now - last >= TYPE_COUNT_WARNING_INTERVAL_S: + logger.warning( + "metadata_cache_type_count_error", + type_code=type_code, + failures=self._type_count_failures, + error=str(exc), + error_type=type(exc).__name__, + ) + self._type_count_warned_at = now + self._type_count_failures = 0 + finally: + self._type_refreshes.pop(type_code, None) + self._settle_idle() __all__ = [ "DEFAULT_QUEUE_SIZE", "MAX_BATCH", + "TYPE_COUNT_WARNING_INTERVAL_S", "AircraftMetadataView", "MetadataCache", "OnResolvedFn", 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/repository.py b/backend/src/flightsite/metadata/repository.py index 3a4f084c..f13dbf5c 100644 --- a/backend/src/flightsite/metadata/repository.py +++ b/backend/src/flightsite/metadata/repository.py @@ -207,6 +207,23 @@ def evidence(self, icao24: str, *, callsign: str | None = None) -> Evidence: ) +@dataclass(frozen=True, slots=True) +class TypeCount: + """One type's unique-airframe count, and the newest airframe it covers. + + ``through_aircraft_id`` is the highest ``aircraft.id`` of the type at the + time of the read. ``aircraft`` rows are never deleted and the single + writer assigns ids in commit order, so a read whose mark is at least an + airframe's id was taken after that airframe's row committed: the count + includes it. That is what lets the alert engine tell a count that already + includes the airframe in front of it from one that predates its row + (issue #364), without counting anything twice. + """ + + airframes: int + through_aircraft_id: int + + @dataclass(frozen=True, slots=True) class MetadataClearCounts: """Rows removed by :meth:`MetadataRepository.clear_all` (SPEC §73).""" @@ -712,25 +729,62 @@ async def load_live_view(self, icaos: Sequence[str]) -> dict[str, AircraftLookup ) return found - async def load_type_counts(self) -> dict[str, int]: + async def load_type_counts(self) -> dict[str, TypeCount]: """Unique airframes ever recorded, per resolved ICAO type designator. - ``docs/DATA_MODEL.md`` §6.5 gives this figure a table of its own - (``type_stats``) — but that table lands with the analytics rollups in - slice 031, so until then the same number is computed from ``aircraft`` - joined to the resolved types. One row per airframe in ``aircraft`` - makes the count a unique-airframe count by construction. + The same definition as ``type_stats.unique_aircraft`` + (:meth:`flightsite.analytics.repository.AnalyticsRepository.derive_type_stats`, + ``docs/DATA_MODEL.md`` §6.5): ``aircraft`` joined to the resolved + types, one row per airframe, so the count is a unique-airframe count by + construction. Computed here rather than read from ``type_stats`` + because that table is refreshed per analytics rollup pass and trails + a newly persisted airframe; the alert engine needs the figure as of + now (issue #364). """ async with self._database.read_session() as session: rows = ( await session.execute( - select(AircraftMetadataResolved.type_code, func.count()) + select( + AircraftMetadataResolved.type_code, + func.count(Aircraft.id), + func.max(Aircraft.id), + ) .join(Aircraft, Aircraft.icao24 == AircraftMetadataResolved.icao24) .where(AircraftMetadataResolved.type_code.is_not(None)) .group_by(AircraftMetadataResolved.type_code) ) ).all() - return {str(type_code): int(count) for type_code, count in rows} + return { + str(type_code): TypeCount(airframes=int(count), through_aircraft_id=int(mark)) + for type_code, count, mark in rows + } + + async def load_type_count(self, type_code: str) -> TypeCount | None: + """One type's :class:`TypeCount`, or ``None`` when no airframe has it. + + The single-type form of :meth:`load_type_counts`, re-read when a new + airframe of the type is persisted between metadata imports (issue + #364), at most once per new airframe. Both joined sides are read from + covering indexes: without statistics SQLite seeks ``ix_amr_type`` and + probes ``aircraft``'s ``icao24`` index per row; after ``ANALYZE`` (the + maintenance task's ``PRAGMA optimize``) it may instead walk ``aircraft``'s + ``icao24`` index and probe ``ix_amr_type`` on ``(type_code, icao24)``. + Either way the cost is bounded by the smaller of the type's resolved + rows and the airframes heard here, never a table scan. + """ + async with self._database.read_session() as session: + row = ( + await session.execute( + select(func.count(Aircraft.id), func.max(Aircraft.id)) + .select_from(AircraftMetadataResolved) + .join(Aircraft, Aircraft.icao24 == AircraftMetadataResolved.icao24) + .where(AircraftMetadataResolved.type_code == type_code) + ) + ).one() + count, mark = row + if not count or mark is None: + return None + return TypeCount(airframes=int(count), through_aircraft_id=int(mark)) # ------------------------------------------------------------- reset @@ -1082,4 +1136,5 @@ def _to_status(row: MetadataSource) -> SourceStatusRecord: "MetadataClearCounts", "MetadataRepository", "ResolutionBuild", + "TypeCount", ] 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..cab484a7 100644 --- a/backend/tests/activity/test_producers.py +++ b/backend/tests/activity/test_producers.py @@ -461,6 +461,31 @@ 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, + sources=("routes",), + ), + ] + ) + + 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 + assert batch.events[2].payload["sources"] == ["routes"] + assert "sources" not in batch.events[1].payload + + 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/activity/test_service.py b/backend/tests/activity/test_service.py index 8fb70734..5854ea1f 100644 --- a/backend/tests/activity/test_service.py +++ b/backend/tests/activity/test_service.py @@ -605,6 +605,30 @@ async def test_a_completed_import_run_becomes_one_event_per_source( ] +async def test_a_skipped_automatic_run_is_one_event_naming_every_source( + database: Database, clock: ManualClock +) -> None: + """Slice 131: "the update did not happen, and why" is one piece of news.""" + service = await started(database, clock) + reason = "Automatic update skipped: 0.1 GiB free on the data volume" + + await service.record_import( + ImportRun( + results=tuple( + SourceImportResult(source=name, ok=False, phase=ImportPhase.DOWNLOAD, error=reason) + for name in ("faa", "mictronics") + ), + started_ms=BASE_MS, + finished_ms=BASE_MS + 1_000, + automatic=True, + skipped=True, + ) + ) + await service.flush() + + assert await feed_keys(database) == [f"metadata_updated:faa, mictronics:{BASE_MS + 1_000}"] + + async def test_the_same_run_recorded_twice_is_one_set_of_events( database: Database, clock: ManualClock ) -> None: diff --git a/backend/tests/alerts/test_engine.py b/backend/tests/alerts/test_engine.py index d4d6add4..c174283f 100644 --- a/backend/tests/alerts/test_engine.py +++ b/backend/tests/alerts/test_engine.py @@ -26,6 +26,7 @@ from flightsite.activity.facts import AlertMatchFact from flightsite.alerts.engine import AlertEngine, subject_for +from flightsite.alerts.evaluator import evaluate from flightsite.alerts.model import ( ClassificationCondition, CompiledRule, @@ -34,12 +35,14 @@ ) from flightsite.alerts.repository import AlertRepository from flightsite.alerts.vocabulary import AlertSeverity +from flightsite.analytics import AnalyticsQueries, AnalyticsRepository, Window from flightsite.counters import counters from flightsite.db import Database from flightsite.db.startup import DB_ERRORS_COUNTER from flightsite.ingest import AircraftStateUpdate, Position from flightsite.live import LiveStore from flightsite.metadata import MetadataService, SourceRegistry +from flightsite.metadata.repository import MetadataRepository, TypeCount from flightsite.sightings import PersistenceWorker from flightsite.sightings.vocabulary import SightingEventType from flightsite.watchlists import WatchlistEntryKind, WatchlistService @@ -756,6 +759,262 @@ async def test_a_count_read_between_commit_and_id_assignment_is_repaired( assert len(await stored_matches(database)) == 1 +# ------------------------------------------- rare_type between imports (#364) + +RARE_TYPE_ONCE = RuleConditions(rare_type=RarityCondition(max_sightings=1)) + + +def type_rarity( + icao: str, + *, + live: LiveStore, + metadata: MetadataService, + watchlists: WatchlistService, + persistence: PersistenceWorker, +) -> int | None: + """``type_aircraft_here`` as the engine would compute it right now.""" + built = subject_for( + icao, + live=live, + metadata=metadata.cache, + watchlists=watchlists.matcher, + persistence=persistence, + now_ms=NOW_MS, + ) + assert built is not None + return built.type_aircraft_here + + +async def test_a_type_count_is_unknown_until_this_airframes_row_is_counted( + live: LiveStore, + metadata: MetadataService, + watchlists: WatchlistService, + persistence: PersistenceWorker, + database: Database, +) -> None: + """Issue #364: the type map was loaded before this airframe was heard, so + until its row is committed *and* the type re-read, how many airframes of + the type are here is unknown, not zero and not floored to one.""" + await seed_resolved_metadata(database, "ae1463", type_code="C172") + observe(live) + await settle(metadata) + + def probe(icao: str) -> int | None: + return type_rarity( + icao, live=live, metadata=metadata, watchlists=watchlists, persistence=persistence + ) + + assert probe("ae1463") is None # no aircraft row yet + + await commit_sighting(persistence) + assert probe("ae1463") is None # row newer than the map + + active = persistence.sighting_for("ae1463") + assert active is not None and active.aircraft_id is not None + metadata.cache.request_type_count("C172") + await settle(metadata) + assert probe("ae1463") == 1 + + +async def test_a_type_first_heard_after_the_load_matches_its_first_airframe_only( + engine: AlertEngine, + live: LiveStore, + metadata: MetadataService, + watchlists: WatchlistService, + persistence: PersistenceWorker, + database: Database, +) -> None: + """Issue #364, reproduced: a type first heard since the map was loaded + read zero, was floored to one, and *every* airframe of it matched a + ``rare_type`` rule. Now the first airframe matches once the count + includes it, and the second, with the count at two, does not.""" + await seed_resolved_metadata(database, "ae1463", type_code="C172") + await seed_resolved_metadata(database, "ae1464", type_code="C172") + await use(engine, database, rule(RARE_TYPE_ONCE)) + + def probe(icao: str) -> int | None: + return type_rarity( + icao, live=live, metadata=metadata, watchlists=watchlists, persistence=persistence + ) + + observe(live, "ae1463") + await settle(metadata) + await commit_sighting(persistence) + assert (await engine.process_pending()).recorded == 0 # count unknown, re-read asked + await settle(metadata) + repaired = await engine.process_pending() # no event: the repair pass + assert repaired.events == 0 + assert repaired.recorded == 1 + assert probe("ae1463") == 1 + + observe(live, "ae1464", second=1) + await settle(metadata) + await commit_sighting(persistence) + assert (await engine.process_pending()).recorded == 0 + await settle(metadata) + assert (await engine.process_pending()).recorded == 0 + assert probe("ae1464") == 2 + assert engine.interesting("ae1464") is None + + # Nothing is owed any more: both airframes have left the repair set. + await commit_sighting(persistence) + assert (await engine.process_pending()).evaluated == 0 + matches = await stored_matches(database) + assert len(matches) == 1 + + +async def test_rare_type_agrees_with_analytics_rarity_after_a_rollup_pass( + engine: AlertEngine, + live: LiveStore, + metadata: MetadataService, + watchlists: WatchlistService, + persistence: PersistenceWorker, + database: Database, +) -> None: + """The condition and ``GET /api/v1/analytics/rarity`` count the same + airframes with the same inequality. The endpoint reads ``type_stats``, + re-derived once per analytics rollup pass, so it trails a newly persisted + airframe by one pass; after ``refresh_type_stats`` the two agree.""" + for icao in ("ae1463", "ae1464"): + await seed_resolved_metadata(database, icao, type_code="C172") + await use(engine, database, rule(RARE_TYPE_ONCE)) + for second, icao in enumerate(("ae1463", "ae1464")): + observe(live, icao, second=second) + await settle(metadata) + await commit_sighting(persistence) + await engine.process_pending() + await settle(metadata) + + def probe(icao: str) -> int | None: + return type_rarity( + icao, live=live, metadata=metadata, watchlists=watchlists, persistence=persistence + ) + + here = probe("ae1463") + assert here == probe("ae1464") == 2 + + queries = AnalyticsQueries(database) + window = Window( + start_ms=0, end_ms=NOW_MS + 86_400_000, first_day="1970-01-01", last_day="2100-01-01" + ) + trailing = await queries.rarity(window, max_type_aircraft=1000) + assert [row.type_code for row in trailing.rare_types] == [] # before the pass + + repository = AnalyticsRepository(database) + await repository.replace_type_stats(await repository.derive_type_stats()) + + for threshold in (1, 2, 3): + rarity = await queries.rarity(window, max_type_aircraft=threshold) + listed = {row.type_code: row.unique_aircraft for row in rarity.rare_types} + subject = subject_for( + "ae1463", + live=live, + metadata=metadata.cache, + watchlists=watchlists.matcher, + persistence=persistence, + now_ms=NOW_MS, + ) + assert subject is not None + matched = bool( + evaluate( + subject, + [rule(RuleConditions(rare_type=RarityCondition(max_sightings=threshold)))], + alert_radius_nm=None, + ) + ) + assert matched == ("C172" in listed) + if matched: + assert listed["C172"] == here + + +async def test_an_airframe_committed_during_a_re_read_is_asked_for_again( + engine: AlertEngine, + live: LiveStore, + metadata: MetadataService, + watchlists: WatchlistService, + persistence: PersistenceWorker, + database: Database, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A second airframe of the type commits while the first one's re-read + is in flight: its own request is dropped as a duplicate, the re-read + that lands predates its row, and the next engine cycle asks again.""" + entered = asyncio.Event() + release = asyncio.Event() + original = MetadataRepository.load_type_count + + async def gated(repository: MetadataRepository, type_code: str) -> TypeCount | None: + found = await original(repository, type_code) + if not release.is_set(): + entered.set() + await release.wait() + return found + + monkeypatch.setattr(MetadataRepository, "load_type_count", gated) + for icao in ("ae1463", "ae1464"): + await seed_resolved_metadata(database, icao, type_code="C172") + await use(engine, database, rule(RARE_TYPE_ONCE)) + + def probe(icao: str) -> int | None: + return type_rarity( + icao, live=live, metadata=metadata, watchlists=watchlists, persistence=persistence + ) + + observe(live, "ae1463") + for _ in range(10): + await asyncio.sleep(0) + await metadata.cache.wait_idle() + await commit_sighting(persistence) + await engine.process_pending() # asks for C172 + await entered.wait() # read taken: one airframe + + observe(live, "ae1464", second=1) + await commit_sighting(persistence) # resolution waits on the lock; the row commits + await engine.process_pending() # ae1464's request is a duplicate + release.set() + await settle(metadata) + + assert probe("ae1463") == 1 + assert probe("ae1464") is None # the read that landed predates its row + await engine.process_pending() # ae1463 matches; ae1464 asks again + await settle(metadata) + await engine.process_pending() + + assert probe("ae1463") == probe("ae1464") == 2 + assert engine.interesting("ae1464") is None + assert len(await stored_matches(database)) == 1 + + +async def test_without_a_rare_type_rule_no_type_count_is_awaited( + engine: AlertEngine, + live: LiveStore, + metadata: MetadataService, + persistence: PersistenceWorker, + database: Database, +) -> None: + """Nothing reads the count unless an enabled rule has ``rare_type``, so + nothing waits for it or re-reads it; once such a rule arrives, every + live aircraft gets one repair pass, which asks for the count it needs.""" + await seed_resolved_metadata(database, "ae1463", type_code="C172") + await use(engine, database, rule(NEAR, rule_id=2)) + observe(live) + await settle(metadata) + await commit_sighting(persistence) + await engine.process_pending() + await settle(metadata) + + assert metadata.cache.type_count("C172") == 0 # never re-read + assert (await engine.process_pending()).evaluated == 0 + + await use(engine, database, rule(NEAR, rule_id=2), rule(RARE_TYPE_ONCE)) + repaired = await engine.process_pending() + assert repaired.events == 0 + assert repaired.evaluated == 1 + await settle(metadata) + assert (await engine.process_pending()).recorded == 1 + assert metadata.cache.type_count("C172") == 1 + + async def test_ground_traffic_is_excluded_from_a_rule_but_not_from_an_emergency( engine: AlertEngine, live: LiveStore, 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/api/test_read_pool_api.py b/backend/tests/api/test_read_pool_api.py new file mode 100644 index 00000000..a512306e --- /dev/null +++ b/backend/tests/api/test_read_pool_api.py @@ -0,0 +1,191 @@ +"""``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 context as context_module +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, and +#: the receiver block, whose only read is T0 behind a broad ``except`` that +#: must let a busy pool through (it would otherwise answer 200, T0 unknown). +READS = [ + "/api/v1/aircraft/a00001", + "/api/v1/sightings?preset=t0", + "/api/v1/analytics/summary?preset=t0", + "/api/v1/receiver", +] + + +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_a_busy_pool_is_not_reported_as_an_unreadable_t0( + harness: Harness, rest: AsyncClient, monkeypatch: pytest.MonkeyPatch +) -> None: + log = RecordingLogger() + monkeypatch.setattr(context_module, "logger", log) + counters.reset() + + async with AsyncExitStack() as stack: + await _hold_every_read_connection(harness, stack) + response = await rest.get("/api/v1/receiver") + + assert response.status_code == 503 + assert response.json()["error"]["code"] == "read_pool_exhausted" + assert counters.snapshot()[READ_POOL_EXHAUSTIONS] == 1 + assert [event for _, event, _ in log.events if event == "t0_unavailable"] == [] + + +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..ecce68e5 --- /dev/null +++ b/backend/tests/db/test_read_pool_checkout.py @@ -0,0 +1,140 @@ +"""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 + +#: Bounded checkouts that give up on a saturated pool in the no-leak test. +TIMEOUTS_WHILE_SATURATED = 25 + + +@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_repeated_timeouts_on_a_full_size_pool_leak_no_connection(db_path: Path) -> None: + database = Database(db_path, read_pool_size=engine_module.READ_POOL_SIZE) + pool = database._read_engine.pool + try: + async with AsyncExitStack() as stack: + for _ in range(engine_module.READ_POOL_SIZE): + await _hold_every_connection(database, stack) + for _ in range(TIMEOUTS_WHILE_SATURATED): + with pytest.raises(ReadPoolExhausted), bounded_read_checkout(0.005): + async with database.read_session(): + pytest.fail("the session must not open") # pragma: no cover + + # Every connection is still the pool's to hand out: all of them at + # once, each within the bound. + async with AsyncExitStack() as stack: + with bounded_read_checkout(SHORT_BOUND_S * 20): + sessions = [ + await stack.enter_async_context(database.read_session()) + for _ in range(engine_module.READ_POOL_SIZE) + ] + for session in sessions: + assert await session.scalar(text("SELECT 1")) == 1 + assert pool.checkedout() == 0 # type: ignore[attr-defined] + finally: + await database.dispose() + + +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/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..8e5f34f6 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 since it connected)" + 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 since it connected)") + + +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( + [ + # The same line twice in one read, then once more through the overlap. + [stamped(-60, ESTABLISHED.format(host=ADSBX)), stamped(-2, odd), stamped(-2, odd)], + [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/backend/tests/metadata/test_autoupdate.py b/backend/tests/metadata/test_autoupdate.py new file mode 100644 index 00000000..e64e506f --- /dev/null +++ b/backend/tests/metadata/test_autoupdate.py @@ -0,0 +1,514 @@ +"""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 + + +def test_sources_falling_due_within_a_day_join_the_run() -> None: + """Ruling 19 after review: one run must survive its own staggered stamps. + + The importer stamps each source's ``last_success_ms`` with that source's own + start, so sources imported in one run fall due minutes apart. Once one is + due, the others due within the 24 h horizon go with it — but not one in + back-off, one never imported, or one due later than the horizon. + """ + plan = plan_auto_update( + [ + status("airports", last_success_ms=T0), + status("faa", last_success_ms=T0 + 4 * 60_000), + status("mictronics", last_success_ms=T0 + 20 * HOUR_MS), + status("routes", last_success_ms=T0 + 2 * DAY_MS), + status( + "opensky", last_success_ms=T0, last_attempt_ms=T0 + 30 * DAY_MS - HOUR_MS + ), # failed an hour ago: in back-off, due again within the horizon + status("never", last_success_ms=None), + ], + registered=["airports", "faa", "mictronics", "routes", "opensky", "never"], + interval_days=30, + now_ms=T0 + 30 * DAY_MS, + ) + + assert {entry.source for entry in plan if entry.due} == {"airports", "faa", "mictronics"} + # Each source still reports its own due time. + assert plan[1].next_ms == T0 + 4 * 60_000 + 30 * DAY_MS + + +def test_nothing_is_coalesced_while_nothing_is_due() -> None: + plan = plan_auto_update( + [status("faa", last_success_ms=T0)], + registered=["faa"], + interval_days=30, + now_ms=T0 + 30 * DAY_MS - HOUR_MS, + ) + + assert plan[0].due is False + + +# --------------------------------------------------------------- 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_sources_imported_minutes_apart_stay_in_one_run( + harness: Harness, registry: SourceRegistry +) -> None: + """The review's probe: staggered stamps must not split the next cycle.""" + first = InMemoryMetadataProvider([RECORD_A]) + second = InMemoryMetadataProvider([RECORD_B]) + registry.register("faa", first) + registry.register("mictronics", second) + await harness.service.start_update(["faa"]).task + harness.clock.advance(7 * 60_000) # the second source's import starts later + await harness.service.start_update(["mictronics"]).task + + harness.clock.advance(30 * DAY_MS - 7 * 60_000) + assert await harness.tick() is TickOutcome.STARTED + + assert [result.source for result in harness.runs[-1].results] == ["faa", "mictronics"] + harness.clock.advance(HOUR_MS) + assert await harness.tick() is TickOutcome.NOTHING_DUE + assert (first.downloads, second.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/metadata/test_cache.py b/backend/tests/metadata/test_cache.py index ca8dbcf8..98db845f 100644 --- a/backend/tests/metadata/test_cache.py +++ b/backend/tests/metadata/test_cache.py @@ -2,13 +2,17 @@ from __future__ import annotations +import asyncio + import pytest +from sqlalchemy import text from flightsite.db import Database from flightsite.live import LiveStore from flightsite.metadata import MetadataImporter, MetadataService, SourceRegistry from flightsite.metadata.cache import MetadataCache from flightsite.metadata.registry import ImportPhase +from flightsite.metadata.repository import MetadataRepository, TypeCount from tests.metadata.conftest import appear, record, seed_aircraft, settle from tests.metadata.provider import InMemoryMetadataProvider @@ -288,6 +292,210 @@ async def test_an_unseen_type_counts_zero(populated: None, cache: MetadataCache) await cache.stop() +# ------------------------------------------- type counts between imports (#364) + +#: FLEET plus two airframes the metadata knows but the receiver has not heard +#: yet: one of a type nobody here has heard (C172), one of a known type (B738). +LATER_FLEET = [ + *FLEET, + record("a00004", registration="N4DD", type_code="C172"), + record("a00005", registration="N5EE", type_code="B738"), +] + + +@pytest.fixture +async def later(importer: MetadataImporter, registry: SourceRegistry, database: Database) -> None: + """:data:`LATER_FLEET` imported; only FLEET's three airframes heard.""" + registry.register("mictronics", InMemoryMetadataProvider(LATER_FLEET)) + await importer.run() + await seed_aircraft(database, {"a00001": 42, "a00002": 1, "a00003": 7}) + + +async def hear_airframe(database: Database, icao24: str, aircraft_id: int) -> None: + """Insert the ``aircraft`` row the persistence worker writes for a new airframe.""" + async with database.writer_session() as session: + await session.execute( + text( + "INSERT INTO aircraft (id, icao24, first_seen_ms, last_seen_ms, " + "sighting_count, total_observed_ms) VALUES (:id, :icao24, 0, 0, 1, 0)" + ), + {"id": aircraft_id, "icao24": icao24}, + ) + + +async def test_type_counts_are_unknown_until_the_map_has_loaded( + later: None, cache: MetadataCache +) -> None: + """Before the first load, a type count is unknown, never zero.""" + assert cache.type_count("B738") is None + assert cache.type_count_including("B738", 1) is None + cache.request_type_count("B738") # not started: a no-op, not a crash + await cache.start() + try: + assert cache.type_count("B738") == 2 + assert cache.type_count_including("B738", 1) == 2 + assert cache.type_count_including("B738", 2) == 2 + finally: + await cache.stop() + + +async def test_a_type_first_heard_after_the_load_is_counted_once_re_read( + later: None, cache: MetadataCache, database: Database +) -> None: + """Issue #364: a type heard since the last load is unknown for the new + airframe until re-read, then includes it, and a second airframe of it is + the second, not another first.""" + await cache.start() + try: + await hear_airframe(database, "a00004", 4) + assert cache.type_count("C172") == 0 + assert cache.type_count_including("C172", 4) is None + + cache.request_type_count("C172") + await settle(cache) + + assert cache.type_count_including("C172", 4) == 1 + assert cache.type_counts()["C172"] == 1 + + await hear_airframe(database, "a00005", 5) + assert cache.type_count_including("B738", 5) is None + # Airframes the map already covered still answer from it. + assert cache.type_count_including("B738", 2) == 2 + cache.request_type_count("B738") + await settle(cache) + assert cache.type_count_including("B738", 5) == 3 + finally: + await cache.stop() + + +async def test_a_re_read_is_idempotent( + later: None, cache: MetadataCache, database: Database +) -> None: + """Re-reading is a count, never a ``+1``: asking twice, or asking for a + type that is already current, cannot inflate it.""" + await cache.start() + try: + await hear_airframe(database, "a00004", 4) + cache.request_type_count("C172") + cache.request_type_count("C172") + await settle(cache) + cache.request_type_count("C172") + cache.request_type_count("B738") + await settle(cache) + + assert cache.type_counts() == {"B738": 2, "A320": 1, "C172": 1} + finally: + await cache.stop() + + +async def test_a_re_read_agrees_with_a_reload( + later: None, cache: MetadataCache, database: Database, live: LiveStore +) -> None: + """Restart consistency: the counts a re-read reaches are exactly what a + fresh cache over the same database loads.""" + await cache.start() + try: + await hear_airframe(database, "a00004", 4) + await hear_airframe(database, "a00005", 5) + cache.request_type_count("C172") + cache.request_type_count("B738") + await settle(cache) + refreshed = dict(cache.type_counts()) + finally: + await cache.stop() + + restarted = MetadataCache(database=database, live=live) + await restarted.start() + try: + assert restarted.type_counts() == refreshed == {"B738": 3, "A320": 1, "C172": 1} + assert restarted.type_count_including("C172", 4) == 1 + assert restarted.type_count_including("B738", 5) == 3 + finally: + await restarted.stop() + + +class GatedTypeCount: + """Holds :meth:`MetadataRepository.load_type_count` open until released. + + The re-read runs under the population lock, so while it is held open a + population that took an event is parked on that lock: exactly the + interleaving the idle flag has to survive. + """ + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.entered = asyncio.Event() + self.release = asyncio.Event() + original = MetadataRepository.load_type_count + + async def gated(repository: MetadataRepository, type_code: str) -> TypeCount | None: + found = await original(repository, type_code) + self.entered.set() + await self.release.wait() + return found + + monkeypatch.setattr(MetadataRepository, "load_type_count", gated) + + +async def test_idle_waits_for_a_population_parked_behind_a_re_read( + later: None, + cache: MetadataCache, + database: Database, + live: LiveStore, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A re-read finishing must not report the cache idle while the + population task holds an event it has not resolved yet.""" + gate = GatedTypeCount(monkeypatch) + await cache.start() + try: + await hear_airframe(database, "a00004", 4) + cache.request_type_count("C172") + await gate.entered.wait() + + appear(live, "a00001") + for _ in range(10): # let the population task take the event + await asyncio.sleep(0) + gate.release.set() + await cache.wait_idle() + + assert cache.get("a00001") is not None + assert cache.type_count_including("C172", 4) == 1 + finally: + await cache.stop() + + +async def test_a_repeated_re_read_failure_warns_once_per_interval( + later: None, cache: MetadataCache, monkeypatch: pytest.MonkeyPatch +) -> None: + """The engine asks again every cycle while an airframe waits; a database + that keeps failing must not turn that into a warning per second.""" + warnings: list[dict[str, object]] = [] + + class Recorder: + def warning(self, event: str, **fields: object) -> None: + warnings.append({"event": event, **fields}) + + def info(self, event: str, **fields: object) -> None: + pass + + async def failing(repository: MetadataRepository, type_code: str) -> TypeCount | None: + raise OSError("disk I/O error") + + monkeypatch.setattr("flightsite.metadata.cache.logger", Recorder()) + monkeypatch.setattr(MetadataRepository, "load_type_count", failing) + await cache.start() + try: + for _ in range(3): + cache.request_type_count("C172") + await settle(cache) + finally: + await cache.stop() + + assert [entry["event"] for entry in warnings] == ["metadata_cache_type_count_error"] + assert warnings[0]["failures"] == 1 + assert cache.type_count("C172") == 0 + + # ------------------------------------------------------------ invalidation diff --git a/backend/tests/metadata/test_resolution.py b/backend/tests/metadata/test_resolution.py index 986be23e..ed6e009f 100644 --- a/backend/tests/metadata/test_resolution.py +++ b/backend/tests/metadata/test_resolution.py @@ -229,7 +229,8 @@ async def test_type_counts_count_unique_airframes( database, {"a00001": 3, "a00002": 1, "a00003": 7, "a00005": 2, "a00006": 9} ) - counts = await repository.load_type_counts() + loaded = await repository.load_type_counts() + counts = {code: entry.airframes for code, entry in loaded.items()} assert counts == ({} if empty else {"B738": 2, "A320": 1}) 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/backend/uv.lock b/backend/uv.lock index e2cf4cdf..0a5c584d 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -180,7 +180,7 @@ wheels = [ [[package]] name = "flightsite" -version = "0.17.0" +version = "0.18.0" source = { editable = "." } dependencies = [ { name = "aiosqlite" }, 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: diff --git a/deploy/sdr-watchdog/pyproject.toml b/deploy/sdr-watchdog/pyproject.toml index 520562a8..d0915367 100644 --- a/deploy/sdr-watchdog/pyproject.toml +++ b/deploy/sdr-watchdog/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "flightsite-sdr-watchdog" -version = "0.17.0" +version = "0.18.0" description = "Host watchdog that restarts the ADS-B decoder container after an RTL-SDR dongle re-enumerates." requires-python = ">=3.11" license = { text = "MIT" } diff --git a/deploy/sdr-watchdog/src/sdr_watchdog/__init__.py b/deploy/sdr-watchdog/src/sdr_watchdog/__init__.py index 7dddb35f..80212134 100644 --- a/deploy/sdr-watchdog/src/sdr_watchdog/__init__.py +++ b/deploy/sdr-watchdog/src/sdr_watchdog/__init__.py @@ -3,4 +3,4 @@ Standard library only (Python 3.11+). See docs/design/103-sdr-watchdog.md. """ -__version__ = "0.17.0" +__version__ = "0.18.0" diff --git a/deploy/sdr-watchdog/uv.lock b/deploy/sdr-watchdog/uv.lock index 3e30e8d9..318c76fb 100644 --- a/deploy/sdr-watchdog/uv.lock +++ b/deploy/sdr-watchdog/uv.lock @@ -81,7 +81,7 @@ wheels = [ [[package]] name = "flightsite-sdr-watchdog" -version = "0.17.0" +version = "0.18.0" source = { virtual = "." } [package.dev-dependencies] diff --git a/docs/API.md b/docs/API.md index da8f25f0..f445cbe3 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,34 @@ 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. Each read a request makes waits at +most 5 s for a free connection; if every connection stays busy that long, the request 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`. + +One exception for now: `GET /api/v1/diagnostics` (§3.11) catches every failure of its +database probe, so a busy pool shows there as `database_reachable: false` with a `200` +rather than as this `503`, until issue +[#377](https://github.com/stevenpickles/flightsite/issues/377) is resolved. + ### 2.6 Provenance representation Objects that carry enriched/derived fields include a `provenance` map naming the @@ -266,7 +294,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 +1208,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 one + of the request's reads for its whole 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: @@ -1443,6 +1476,19 @@ 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 since it connected)") + while such a line is at most 15 minutes old and `N` is at least 1.0. `N` is a + lifetime share of the connection, not a current rate: on a long-lived connection a + fresh, severe episode may never reach 1.0% and reads `up` (ten minutes of half-drop + on a two-day connection is about 0.2%); a connection that lost data early reads + `degraded` for 15 minutes on any later two-second hiccup; a young connection + overstates its loss. 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. @@ -1617,7 +1663,7 @@ config/domain models the backend uses. | Watchlists | `GET/POST /watchlists`, `PUT/DELETE /watchlists/{id}`, entries CRUD | 037 | | Alert rules | `GET/POST /alert-rules`, `PUT/DELETE /alert-rules/{id}`, `GET /alert-templates`, `POST /alert-templates/{key}/rules` (instantiates a shipped template as a rule carrying its `template_key`; empty body — the conditions come from the catalogue, never from the caller; `404` unknown key, `409` built-in or already instantiated) | 038/041 | | Alert matches | `POST /alerts/matches/{id}/notified` (records that a browser notification was actually shown for one match; empty body — the assertion *is* the request; `204` whether this call marked the row or found it already marked, `404` for an unknown id) | #104 | -| Metadata update | `POST /metadata/update` (starts run), `GET /metadata/status` (per-source status, last success, versions) | 025 | +| Metadata update | `POST /metadata/update` (starts run), `GET /metadata/status` (per-source status, last success, versions, automatic-update schedule) | 025, 131 | | Reset | `POST /reset/data` (requires `confirm` token), `POST /reset/metadata-cache` | 045 | | Alert webhook | `POST /webhook/test` → posts the test document (§7, `type: "test"`) once to the **saved** `webhook` configuration, enabled or not, with no retries, and answers `200` with `{ok, status_code, error, elapsed_ms}` whatever the receiver said — `error` is FlightSite's own wording (`no webhook URL is configured`, `timeout`, `connection failed`, `HTTP 404`, …), never the URL. The URL and header value are configured through `PUT /config` like any other secret | 111 | | Feeder stats links | `GET /feeders/{name}/stats-link` → `302` to that feeder's per-network stats page (`feeders.stats_urls.` in `secrets.yaml`; for a `piaware` feeder with none configured, the site page piaware itself reports). `404` when there is no link or no such feeder. `Cache-Control: no-store`, `Referrer-Policy: no-referrer`. The only place a stats URL ever leaves the backend, and only as the `Location` of this response — never in `/api/v1`, a log line or the rendered page; `/api/v1/feeders` carries just `stats_link: true\|false` | 077 | @@ -1634,7 +1680,7 @@ match (an inverted window). Every error's `loc` names the field. | `classification` | `{military, government, law_enforcement: bool, mission?}` | every required claim is asserted | v1 | | `type_code` / `model` | string | exact type designator / model substring, ignoring case | v1 | | `watchlist_id` / `watchlist_any` | int / bool | on that watchlist / on any | v1 | -| `rare_aircraft` / `rare_type` | `{max_sightings: 1..1000}` | seen at most N times / type on at most N airframes here | v1 | +| `rare_aircraft` / `rare_type` | `{max_sightings: 1..1000}` | seen at most N times / type on at most N airframes here, this one included (unknown, so unmatched, until counted: [DATA_MODEL.md](DATA_MODEL.md) §6.5) | v1 | | `min_distance_nm`, `max_distance_nm` | number, nm (0..10000) | inclusive window | v1 | | `min_alt_ft`, `max_alt_ft` | number, ft (-2000..100000) | inclusive window, barometric | v1 | | `squawk_in` | array of 1–16 `"[0-7]{4}"` strings | live squawk is one of them | v2 | @@ -1675,6 +1721,40 @@ number of callsigns it knows a route for and whose `dataset_version` is the SHA- the archive it was imported from. Clients must tolerate sources they do not recognise: the list is what this build ships, not a fixed vocabulary. +Since slice 131 ([ADR-0021](adr/0021-scheduled-metadata-updates.md)) the same import +also runs on a schedule, and the status document says when: + +```json +{ + "sources": [ + {"name": "mictronics", "status": "ok", "last_success_ms": 1790000000000, + "dataset_version": "…", "row_count": 620000, "last_error": null, + "next_auto_update_ms": 1792592000000} + ], + "auto_update": {"enabled": true, "interval_days": 30, "next_ms": 1792592000000} +} +``` + +- `next_auto_update_ms` (per source) — when the scheduler will next update that source, + epoch ms UTC; `null` when it never will (automatic updates off, or the source has never + succeeded: the first import stays manual). It can be in the past: the source is due + and the hourly tick starts it within the hour. A due time inside the 30-minute startup + grace is reported as the end of the grace. It is the source's own due time: a source + may be updated up to 24 h earlier, when it joins the run of another source that fell + due first (ADR-0021 rule 5). +- `auto_update.enabled` — whether this process runs automatic updates at all: false when + `metadata.auto_update_days` is `0`, in demo mode, and when the database failed to + migrate. `interval_days` is the setting; `next_ms` is the earliest per-source value, or + `null`. + +`POST /metadata/update` and the scheduler share one in-flight run: a trigger during an +automatic run answers `{"started": false, "already_running": true, "started_ms": …}` with +that run's start, exactly as a second click always has. Automatic runs appear in the +activity feed as `metadata_updated` events whose payload carries `"automatic": true`; a +run skipped by the free-space guard is **one** `metadata_updated` event (at most one a +day) with `"ok": false`, `"skipped": true`, the reason in `error`, the due sources as a +list in `sources`, and `source` set to those names joined with `", "`. + Backup and restore have **no HTTP surface at all**, internal or external: they are CLI operations (`flightsite-backup`, see `docs/BACKUP.md`), deliberately, so that a restore cannot be triggered by anything reachable from a browser. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index aa711658..9bb43bf1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -36,8 +36,8 @@ flowchart LR BE --- DATA BE -. "feeder status polls (LAN)" .-> FEED BE -. "container logs/health (opt-in)" .-> SOCK - BE -. "manual metadata update" .-> MIC - BE -. "manual metadata update" .-> FAA + BE -. "metadata update (manual / every 30 d)" .-> MIC + BE -. "metadata update (manual / every 30 d)" .-> FAA BE -. "route enrichment (API key)" .-> ADB BROWSER -. "map tiles" .-> TILES ``` @@ -180,7 +180,9 @@ Asyncio tasks in one process: for the live aircraft set, plus resident rarity counters (per-live-aircraft sighting counts and the full type-count table). Populated asynchronously on aircraft-appear events (off the hot path), incremented in memory as sightings open, and invalidated - + repopulated when a metadata import completes. Memory bound: live set + + repopulated when a metadata import completes. Between imports one type's count is + re-read on the cache's own task when a newly persisted airframe of it is not yet + counted (slice 128; [DATA_MODEL.md](DATA_MODEL.md) §6.5). Memory bound: live set (≤ ~1,000 aircraft × ~1 KB) plus a few thousand type-stat rows — well inside the <1 GB budget. This cache is what preserves the "no live request or decoder poll ever waits on SQLite" invariant for metadata joins and rule/rarity evaluation; diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index b210da74..f7f18a37 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -113,6 +113,11 @@ saving, with nothing to restart. So does `webhook.*` (slice 111). The delivery service reads the section on every message, so a new URL, scope or header is used by the next alert after you save. +So does `metadata.auto_update_days` (slice 131). The automatic-update scheduler reads it +on every hourly tick, and the Settings page's metadata card on every status read, so a +new interval — or `0`, which switches automatic updates off — applies with nothing to +restart. + So does `history.query_budget_s` (slice 122). The list endpoints read it on every request, so the next request after you save runs under the new budget, with nothing to restart. @@ -274,6 +279,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, each read an `/api/v1` request makes waits at most 5 s for a free read +connection, and the request 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 | @@ -338,6 +348,7 @@ already-known routes last. |---|---|---|---| | `opensky_enabled` | bool | `false` | Opt in to the OpenSky aircraft database as a supplementary source | | `source_url_overrides` | map of source name → URL | `{}` | Fetch one source's dataset from somewhere other than its default — a mirror, or a fixture server. See below | +| `auto_update_days` | int | `30` | Re-import each source this many days after its last successful update. `0` = off; otherwise 7–365. Applies on save. See [Automatic updates](#automatic-updates) | **What "Update Aircraft Metadata" fetches.** One click runs every registered source, each independently — a failure in one leaves the others' data and status untouched @@ -352,11 +363,44 @@ Settings page: | `routes` | The **offline route directory** — origin and destination per airline callsign, from the Virtual Radar Server standing data (CC0). Consulted before AeroDataBox, so a callsign it knows costs no API credit at all ([ADR-0016](adr/0016-offline-route-directory.md)) | Always active | | `opensky` | Supplementary operator, owner, model and build year | Off by default — see below | -All of them are **fetched on demand**: nothing is downloaded until you run the update, -and nothing is bundled in the container image +All of them are **fetched on demand**: nothing is downloaded until you run the update +for the first time, and nothing is bundled in the container image ([licensing register](LICENSES.md)). The route directory is a ~7 MB archive of which -only the route files are read; it is not refreshed automatically, so re-run the update -when you want newer schedules. +only the route files are read. After that first import, each source is kept current by +[automatic updates](#automatic-updates). + +#### Automatic updates + +Since slice 131 ([ADR-0021](adr/0021-scheduled-metadata-updates.md), the SPEC §27 owner +amendment), FlightSite runs the same import on its own: a source is re-imported +`auto_update_days` (default **30**) after its last successful update. The Settings page's +metadata card shows when the next one is due. What to expect: + +- **The first import is always yours.** A source that has never been imported + successfully is never fetched automatically — run "Update Aircraft Metadata" once. +- **Per source, one run.** Each source keeps its own clock (a manual update resets it). + When one falls due, every other source that would fall due within the next 24 hours + joins it, so sources you imported together stay together and are updated in one run, + exactly as if you had pressed the button. A source that is failing and waiting out its + back-off does not join early. +- **Not right after a restart.** The scheduler waits 30 minutes after the backend + starts, then checks once an hour, so an update starts within the hour after it falls + due. +- **Failures back off.** A failed source keeps its previous data (SPEC §27), and is + retried a day later, then weekly once it has been failing for a week. Each failure is + an Activity event and makes the Health page's metadata section **Degraded**; there is + no separate notification. +- **Low disk skips the run.** If the data volume has less than 2 GiB free when an update + is due, it is skipped, and once a day the Activity feed says why in one event naming + the sources that were due (a warning is logged at the same moment). It runs at the + next hourly check after space is freed. +- **Never in demo mode.** A demo never downloads anything on its own. +- **One run at a time.** Pressing the button during an automatic update joins it + instead of starting a second. + +**No internet access?** Set `auto_update_days: 0`. Otherwise every due source fails +once a day for a week and weekly after that, each time adding an Activity event and +keeping Health degraded. With `0` the button works exactly as before. The four default sources are always active and need no configuration. OpenSky is separate because its licensing is genuinely unclear: diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md index f1b40a9d..887f2a13 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -102,7 +102,11 @@ CREATE INDEX ix_aircraft_sightings ON aircraft(sighting_count); Surrogate `id` (not `icao24` as PK): compact FKs across high-volume tables, and a clean escape hatch for the (rare) ICAO reassignment problem and future multi-receiver -work. Record columns carry their `_ms` moments so the UI can say *when* the record was +work. **`aircraft` rows are never deleted, and `id` only grows.** It is a plain +`INTEGER PRIMARY KEY` without `AUTOINCREMENT`, so after a delete SQLite would hand the +highest id out again. The alert engine's rare-type count relies on ids growing in +commit order (its per-type mark, §6.5, slice 128); a future slice that prunes +airframes must revisit that mark. Record columns carry their `_ms` moments so the UI can say *when* the record was set. Rarity ("never seen", "seen fewer than N times", SPEC §44) reads `sighting_count` / `first_seen_ms` directly. @@ -313,6 +317,17 @@ CREATE TABLE metadata_sources ( Per-source status reporting (SPEC §27) reads straight from this table; it also feeds "metadata database age" in health (SPEC §67) and backup manifests (SPEC §72). +Since slice 131 it is also the **schedule** for automatic updates +([ADR-0021](adr/0021-scheduled-metadata-updates.md)); no column was added. A source is +due `metadata.auto_update_days` after `last_success_ms` (never, while that is `NULL`), +and when `last_attempt_ms > last_success_ms` — the newest attempt failed or never +finished — not before `last_attempt_ms` plus a back-off of 24 h (7 days once the source +has been overdue a week). `last_attempt_ms` is written when an attempt *starts*, which is +what makes an attempt that crashed the process count. A run the free-space guard skips +writes nothing here. The `metadata_updated` activity event's payload gains `automatic` +and `skipped` booleans (absent on events recorded before slice 131); a skipped run is +one event whose payload also lists the due sources in `sources`. + ### 3.2 `aircraft_metadata` — slice 021 (rows from 022/023) **One row per (icao24, source)** — sources never overwrite each other; imports replace @@ -878,6 +893,31 @@ CREATE TABLE type_stats ( -- since-T0 per type; rarity + first- ) WITHOUT ROWID; ``` +**Rare-type counts: one definition, two readers** (slice 128, issue #364). +`type_stats.unique_aircraft` is `count(aircraft)` joined to +`aircraft_metadata_resolved` by `icao24`, grouped by the resolved `type_code`. A +`rare_type {max_sightings}` alert condition counts the same airframes with the same +inequality (`unique_aircraft <= max_sightings`), so the condition and +`GET /analytics/rarity`'s `rare_types` answer alike, but they read it at different +times: + +- `type_stats` is re-derived on each analytics rollup pass that rebuilt a day, and a + sighting opening dirties its day, so the endpoint **trails a newly persisted + airframe by one pass** (at most the 30 s flush interval). +- The alert engine reads the metadata cache's in-memory per-type map: the same + `GROUP BY`, loaded whole at start and after each metadata import, with each entry + also holding the highest `aircraft.id` it covers. A type changes only on import, so + between imports the one thing that moves a count is a new `aircraft` row. When the + engine evaluates an airframe whose id is above its type's mark, the count is + *unknown*: the condition fails, the cache re-reads that one type, and the engine + re-evaluates the airframe until the count includes it. A count is also unknown + before the airframe's row has committed and before the map's first load. There is + no `max(1, …)` floor any more: a count that includes the airframe is at least one. + The mark is sound only because `aircraft` rows are never deleted and their ids only + grow (§2.2): a count whose highest id is at least an airframe's id was read after + that airframe's row committed. A slice that prunes airframes must revisit it. The + wait and the re-read happen only while an enabled rule has a `rare_type` condition. + "Most frequently seen aircraft" over a window is deliberately **not** rolled up per (day, aircraft): it is a `GROUP BY aircraft_id` over `ix_sightings_started` (≤ ~45k rows for a 30-day window on a busy receiver — measured budget in slice 031); the diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 145bb81c..4796c3ab 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -440,6 +440,26 @@ 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: 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 +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..534d6a53 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -517,13 +517,34 @@ 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 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 + echo "READY: upgrade complete." +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 +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 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. 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. 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/docs/LICENSES.md b/docs/LICENSES.md index c9b8aa38..dbb6f865 100644 --- a/docs/LICENSES.md +++ b/docs/LICENSES.md @@ -37,13 +37,16 @@ the exact upstream license text/version has been verified and recorded. - Genuinely ambiguous licensing questions are escalated to the project owner rather than decided autonomously (SPEC §123). - Three postures exist, and a row must state which it takes. **Fetched** (compatible; - downloaded on demand when the user runs an update — Mictronics, FAA, OurAirports, + downloaded on demand when the user runs an update, and re-downloaded on the + `metadata.auto_update_days` schedule once imported — Mictronics, FAA, OurAirports, VRS standing data). **Rejected** (a clear license clearly forbids the use; no code path exists at all — openAIP, [ADR-0012](adr/0012-airspace-data-source.md)). **Opt-in** (the license is genuinely unclear rather than prohibitive: fetched only when the user turns it on, off by default, with the ambiguity disclosed in-product beside the control — - OpenSky, [ADR-0013](adr/0013-opensky-metadata-source.md)). The middle posture is for + OpenSky, [ADR-0013](adr/0013-opensky-metadata-source.md); once the user has turned it + on and imported it, it is re-fetched on the `metadata.auto_update_days` schedule like + the Fetched sources). The middle posture is for clear incompatibility; the third is for uncertainty, and must not be used to ship something a license actually forbids. - The release qualification checklist includes a documentation review; a release must diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md index 528ebcf5..6dbb3043 100644 --- a/docs/PRODUCT.md +++ b/docs/PRODUCT.md @@ -330,7 +330,10 @@ configuration (AeroDataBox key), browser notification settings, receiver self-al toggles and thresholds (slice 088). Additional actions: - **Update Aircraft Metadata** — manual, per-source download/validate/import with - independent status reporting and transactional safety (§27). + independent status reporting and transactional safety (§27). The same import also + runs automatically every `metadata.auto_update_days` (default 30) for each source + imported at least once; the card shows when the next one is due (§27 owner + amendment, ADR-0021). - **Reset FlightSite Data** and **Clear Metadata Cache** — explicit confirmation required; backup strongly suggested first (§73). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 03c0ce1a..37258c69 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -52,6 +52,7 @@ Releases are prepared on `release/vX.Y.Z` branches from qualified `dev`; the mer | v0.15.0 | 9 | Outage follow-through: an optional alert webhook, feeders marked not sending while the decoder is down, a Health card and hardening for the host SDR watchdog, sightings query cost, faster parallel backend CI, frontend polish and a dependency refresh (slices 105–113; no migration; recorded 2026-11-29) | | v0.16.0 | 9 | Clean-up: aircraft search with a second filter, per-feeder local-decoder override, Health webhook card, transport-error wording, React 19 and two dependency waves (slices 114–119; no migration; recorded 2026-11-29) | | v0.17.0 | 9 | Trustworthy alerts and bounded list queries: rarity alerts wait for the real sighting count and migration 0021 removes the false matches already recorded, a notification click brings the aircraft into view with a last-known marker, a read-statement budget for the four slow list queries, Alerts label-in-name fixes and Starlette's test client on httpx2 (slices 120–122, 124–126; migration 0021; recorded 2026-11-29) | +| v0.18.0 | 9 | Self-updating metadata and trustworthy feeder status: scheduled metadata updates every 30 days (SPEC §27 owner amendment, ADR-0021), readsb's lossy-connection warning no longer marks a Beast output down, live rare-type counts, every selection path brings the aircraft into view, a mapped 503 for an exhausted read pool, and the upgrade check checks /ready, plus a Playwright pin for a Firefox crash in CI (slices 123, 127–132; no migration; recorded 2026-11-30) | | v1.0.0 | 8 | Qualified stable release per SPEC §114 definition of done | ## Slices @@ -247,6 +248,6 @@ metadata overrides · full offline map-region download manager · weather integr airport-level historical analytics · period-over-period analytics · aircraft-follow mode · circling/loitering/repeated-pass detection · complex nested boolean alert expressions · user-installable plugins · Prometheus/Grafana integration · automatic -self-updater · additional decoder adapters (Beast, SBS, remote receiver) · scheduled -metadata updates · packed-track on-disk layout revisit (rowid / page_size 16384 with a -migration path; deferred by ADR-0014) +self-updater · additional decoder adapters (Beast, SBS, remote receiver) · packed-track +on-disk layout revisit (rowid / page_size 16384 with a migration path; deferred by +ADR-0014) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 78b58f0b..ce64bc92 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -174,9 +174,9 @@ FlightSite is local-first. The complete list of optional outbound traffic: |---|---|---| | AeroDataBox route enrichment | Only when `enrichment.aerodatabox_enabled` is on **and** an API key is set; then at most once per airline callsign per `enrichment.route_ttl_days` (default 7 days), capped by `enrichment.daily_lookup_budget` lookups per UTC day when you set one, and by 10 requests/minute always | One `GET https://api.aerodatabox.com/flights/callsign/{callsign}` per lookup: the transmitted callsign in the URL path and your API key in the `X-Api-Key` header. No request body, no query parameters. | | Basemap tiles | When using internet basemaps (default) | Standard tile HTTP requests, which reveal the viewed map area (and therefore approximately your receiver's region) to the tile provider | -| Metadata updates | Only on the manual "Update Aircraft Metadata" action | Plain HTTP(S) downloads from Mictronics/tar1090, FAA, airport-data and route-directory sources; nothing about your receiver is uploaded | +| Metadata updates | On the "Update Aircraft Metadata" action, and — since slice 131 — automatically for each source that has been imported once, every `metadata.auto_update_days` (default 30; `0` = never) ([ADR-0021](adr/0021-scheduled-metadata-updates.md)) | Plain HTTP(S) downloads from Mictronics/tar1090, FAA, airport-data and route-directory sources — and from OpenSky when you have enabled it (`metadata.opensky_enabled`): once imported, it is re-fetched on the same schedule; nothing about your receiver is uploaded | | Feeder status polls | Only while `feeders.entries` is non-empty; one poll per entry per `feeders.poll_interval_s` | **Nothing leaves your network.** Every poll is a plain HTTP `GET` to a LAN address you configured (your own piaware, fr24feed and ultrafeeder status pages), and the optional Docker socket is local to the host. The per-network stats pages are opened by your browser when you click a link, never fetched by FlightSite. | -| Route directory download | Only on the manual "Update Aircraft Metadata" action | One `GET https://github.com/vradarserver/standing-data/archive/refs/heads/main.zip` — a ~7 MB public archive of Virtual Radar Server standing data (CC0). No headers of yours, no key, no query string, no body: the request says nothing except which file is wanted. Nothing is uploaded, and the file is read into the local `route_directory` table and discarded ([ADR-0016](adr/0016-offline-route-directory.md)). | +| Route directory download | With the other metadata updates: on the "Update Aircraft Metadata" action, and automatically every `metadata.auto_update_days` once it has been imported | One `GET https://github.com/vradarserver/standing-data/archive/refs/heads/main.zip` — a ~7 MB public archive of Virtual Radar Server standing data (CC0). No headers of yours, no key, no query string, no body: the request says nothing except which file is wanted. Nothing is uploaded, and the file is read into the local `route_directory` table and discarded ([ADR-0016](adr/0016-offline-route-directory.md)). | | Alert webhook | Only when `webhook.enabled` is on **and** a `webhook.url` is set; one `POST` per alert (self-alerts by default, aircraft alerts too under `scope: all`), at most one per condition per 5 min and 30 aircraft alerts per hour; plus one per **Send test** click | A small JSON document to the URL you configured ([API.md §7](API.md#7-alert-webhook-payload--slice-111)): alert type, severity, FlightSite's title/message, timestamps, the activity event id, the aircraft's ICAO address and identity fields for aircraft alerts, and a link built from `webhook.link_base_url` if you set one. Never configuration, keys or other URLs. The URL may be on your LAN or the internet — your choice; `http`/`https` only, no redirects followed, the response body never read, proxy environment variables ignored | | SDR watchdog stats poll (optional host service, not FlightSite) | Only if you install `flightsite-sdr-watchdog`; once per tick (default 5 s) | **Nothing leaves your network.** One HTTP `GET` to the readsb `stats.json` URL you configured (default `127.0.0.1:8080`, on the host itself); see §11. | @@ -232,8 +232,10 @@ key adds is the ability to ask about the flights your local directory has never The directory's own download is the one new outbound request, and it is the least revealing one here: a single unauthenticated GET for a public file, made only when you -press "Update Aircraft Metadata", carrying nothing about your receiver, your aircraft or -you. It is not scheduled and never happens on its own. +press "Update Aircraft Metadata" — and, since slice 131, again every +`metadata.auto_update_days` once you have imported it +([ADR-0021](adr/0021-scheduled-metadata-updates.md); `0` restores manual-only) — +carrying nothing about your receiver, your aircraft or you. ### What route enrichment does *not* send diff --git a/docs/adr/0016-offline-route-directory.md b/docs/adr/0016-offline-route-directory.md index 60a6ff71..c876e74b 100644 --- a/docs/adr/0016-offline-route-directory.md +++ b/docs/adr/0016-offline-route-directory.md @@ -174,8 +174,14 @@ to edit the schema in place through `PRAGMA writable_schema`, which is not a thi to a user's primary history table unattended. **No scheduled refresh in v1.** The directory updates only when the user runs "Update -Aircraft Metadata", which is SPEC §79's existing backlog item for scheduled metadata -updates and not this slice's business. +Aircraft Metadata". Scheduled metadata updates were a roadmap backlog item +(`planning/roadmap.yaml`), not this slice's business. *(Corrected 2026-11-30: this +paragraph originally called it a SPEC §79 item; §79 does not list it.)* + +> *Superseded 2026-11-30* by the SPEC §27 owner amendment and +> [ADR-0021](0021-scheduled-metadata-updates.md): the directory, like every source that +> has been imported once, is now re-imported automatically every +> `metadata.auto_update_days` (default 30). The manual action is unchanged. **"Enrichment is off" now means something narrower.** Before this decision, no API key meant no enrichment subsystem at all: no subscription, no task, no routes. That was the diff --git a/docs/adr/0017-feeder-status-sources.md b/docs/adr/0017-feeder-status-sources.md index 89e7416f..96a1ee17 100644 --- a/docs/adr/0017-feeder-status-sources.md +++ b/docs/adr/0017-feeder-status-sources.md @@ -36,6 +36,17 @@ feeders publish it the same way and some do not publish it at all. | FlightRadar24 | `:8754/monitor.json` (every value a string) | `feed_status`, `feed_status_message`, `feed_current_server`, `feed_last_ac_sent_time`/`_num`, `feed_last_connected_time`, `rx_connected`, `num_messages`, `timing_source`, `time_update_utc`, `build_version` | `fr24key`, `feed_alias`, `feed_legacy_id`, `local_ips`; never link `/settings.html` | | OpenSky | **logs only**, a Statistics block every 10 min | `currently online\|offline`, `N [P%] seconds online (overall)`, `disconnections`, `bytes sent (rate)` | timestamps are local time | +**Amendment of 2026-11-30** (slice 127, issue +[#369](https://github.com/stevenpickles/flightsite/issues/369)): the ADS-B out row's +"connected iff the last line for the host is established" is narrowed. Only +`Connection established` and readsb's real close/failure lines (remote disconnect, +send error or timeout, heartbeat reconnect, failed or timed-out connect; wording from +readsb `net_io.c` at commit `bc57f2dd`) are state: the newest of them decides. readsb's +"Bad connection, dropping data (connection lost N% of data)" warning is logged on an +open connection; it never changes the state and only overlays it as `degraded` (N, the +share lost since that connection opened, at least 1.0%, line at most 15 min old). Any +other matched line keeps the verdict. + The local pages all answer on the LAN (and through the owner's reverse proxy). piaware's `status.json` is served at `:8081/status.json`, **outside** the `/skyaware/` path a reverse proxy usually exposes. FR24 runs with `MLAT=no` deliberately. There is no diff --git a/docs/adr/0020-read-statement-budget.md b/docs/adr/0020-read-statement-budget.md index acb103ef..06c937c2 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,49 @@ 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. The bound is per + read session, not per request: each read a request makes waits at most 5 s. + A broad `except` on an `/api/v1` read path must let `ReadPoolExhausted` through + (as `LiveApiContext._t0` does), or the request waits a second bound or answers + `200` uncounted. `/api/v1/diagnostics` still reports a busy pool as unreachable + ([#377](https://github.com/stevenpickles/flightsite/issues/377)). + - **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 read from outliving a running one by much (worst case for a + budgeted list 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) each read of an + `/api/v1` request that arrives then waits at most 5 s, and the request 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/0021-scheduled-metadata-updates.md b/docs/adr/0021-scheduled-metadata-updates.md new file mode 100644 index 00000000..03127050 --- /dev/null +++ b/docs/adr/0021-scheduled-metadata-updates.md @@ -0,0 +1,152 @@ +# ADR-0021: Scheduled metadata updates + +**Status:** Accepted (2026-11-30; owner request that day, recorded as the SPEC §27 owner +amendment; design ruled by Fable in the v0.18.0 plan review, rulings 17–24; implemented in +slice 131). Rule 2 below — a source that has never succeeded is never run automatically — +was Fable's recommendation, **confirmed by the owner on 2026-11-30**: "The first import +being manual is OK." + +## Context + +SPEC §27 made metadata updating manual: one **Update Aircraft Metadata** action, and +*"No scheduled metadata updating in v1."* [ADR-0016](0016-offline-route-directory.md) +repeated that for the route directory, and the roadmap kept scheduled updates in the +backlog. On 2026-11-30 the owner asked, verbatim: + +> "I want metadata sources to be automatically updated every 30 days." + +The reference install (fermi) shows why: its metadata was 85 days old, because nobody +remembers to press a button once a quarter. The manual action keeps working; this ADR is +about running the same action unattended, on a Raspberry Pi, without anyone watching. + +What already existed and is reused as is: + +- `MetadataService.update()` — the import of SPEC §27: each source downloaded, validated, + staged and swapped independently, a failed source keeping its previous dataset, one + `metadata_sources` row per source with `last_attempt_ms` (written when an attempt + starts) and `last_success_ms`. +- The post-import listeners: the Activity feed records one `metadata_updated` event per + source, and the metadata cache and the airport index refresh on a run that changed data + — so an automatic run refreshes everything a manual one does, because it is the same + call. + +What did not exist: any run lock in the service. The only single-flight guard was +`app.state.metadata_update_task` in the update endpoint, which a second caller could not +see. + +## Decision + +### Single-flight belongs to the service + +`MetadataService.start_update(sources, automatic=...)` is the one way to start a +background run. It checks for a run in flight and records the new one with no `await` in +between, so two callers on one event loop cannot both start one; a caller that finds a +run in flight gets that run's ticket (`started: false`, its `started_ms`). The endpoint +and the scheduler both call it, and shutdown cancels the in-flight run through +`MetadataService.cancel_update()`. A manual trigger during an automatic run joins it and +does not widen it — the same answer a second click has always had. + +### The decision is per source, the run is one + +`metadata.auto_update_days` (default **30**, for new and upgraded installs alike; `0` = +off; otherwise 7–365) is the interval. For each **registered** source: + +1. Off when the interval is `0`. +2. **Never automatically if the source has never succeeded.** The first import of every + source stays a manual act: nobody gets a several-hundred-megabyte download they did not + ask for on an install that has never imported anything, and an opt-in source switched + on only for a look is not fetched again unless it worked once. *(Confirmed by the + owner, 2026-11-30: "The first import being manual is OK.")* +3. Due `interval` after its `last_success_ms`. +4. If its newest attempt did not succeed (`last_attempt_ms > last_success_ms` — a failure, + or an attempt that never finished), not before `last_attempt_ms + back-off`: **24 h**, + escalating to **7 days** once the source has been overdue for a week. Keyed on + `last_attempt_ms` because it is written when an attempt *starts* and survives a + restart: an attempt that took the process down with it (an OOM mid-download) still + counts, so a crash loop cannot become a download loop. + +Every source due at a tick goes into **one** `update(sources=due)` run. A manual run of +some sources resets only their clocks. This replaces the plan's "oldest source decides a +whole run" proposal (ruling 19): that rule would re-download fresh sources to refresh one +stale one. + +5. **Coalescing.** Once any source is due, every other source that would fall due within + **24 h** joins the run, unless its newest attempt failed (it is in back-off) or it has + never succeeded. Without this, "one run" would not survive its first cycle: the + importer stamps each source's `last_success_ms` with that source's own start time, so + sources imported in one run fall due minutes apart and would otherwise split across + successive hourly ticks (found in Fable's PR review). A source can therefore be updated + up to a day before its own due time; the status endpoint still reports each source's + own due time. + +The decision is a pure function (`metadata/autoupdate.py`: `next_due_ms`, +`plan_auto_update`), tested as a table. + +### The clock + +`MetadataAutoUpdater` waits **30 minutes** after startup, then ticks **hourly**. An upgrade +or restart is when the owner is watching the Pi come back; a download starting under them +would slow exactly that. An hour is nothing against a 30-day interval. The interval is +read on every tick, so a saved change (including `0`) applies with no restart. + +It is **not started** in demo mode (a demo must never start a download nobody asked for) +or when the database failed to migrate (it reads `metadata_sources`). In both cases the +status endpoint reports automatic updates as off. + +### No quiet hours + +There is no time-of-day window. Downloading, validating, staging and building the +resolution all happen off the writer lock, in short transactions between which the +persistence worker keeps draining (`metadata/importer.py`, "Where the work happens"); only +the final swap holds the writer. A scheduled run therefore costs ingestion what a manual +run costs it, and a setting to move it to 3 a.m. would be a control for a problem the +pipeline does not have. If fermi's measurement (below) says otherwise, the hourly tick +makes a window a small change. + +### Visibility + +There is no metadata self-alert, and this ADR adds none. A run, automatic or not, appears +in the Activity feed per source (`metadata_updated`, now with `automatic` and `skipped` +flags); a failed source is `interesting` there and makes the Health page's metadata +section **Degraded**. The Settings metadata card shows when the next automatic update is +due, or that automatic updates are off. `GET /api/internal/metadata/status` gains an +`auto_update` block and a per-source `next_auto_update_ms` for that. + +An install with no internet access should set `auto_update_days: 0`; otherwise every due +source fails once a day for a week and weekly after that, each failure an Activity event +and a Degraded Health section. + +## Unattended risks + +A manual run has a person watching it. A scheduled one does not, so these are stated +rather than assumed away: + +- **Memory.** Mictronics (`sources/mictronics.py`, `_fetch`) and the route directory + (`sources/routes.py`) buffer the whole download in memory before parsing, up to their + caps of 200 MB and 128 MB. The manual action has always done the same; nothing new is + buffered here, but it now happens with nobody watching. Streaming them to disk is a + possible follow-up, not this slice's. +- **Disk.** Staging writes a second copy of a source's rows beside the live ones and the + swap grows the WAL by about as much again, on top of the download in `metadata-work/`. + There was no free-space check. Scheduled runs now have one: if the data volume has less + than **2 GiB** free when a run is due, the run is skipped. Once a day a warning is + logged and the Activity feed records **one** skipped `metadata_updated` event naming + every due source, with the reason; the hourly re-checks in between log at debug only, + so a full disk does not crowd the diagnostics error ring. A skip is not an attempt — no `metadata_sources` row + changes, so it starts no back-off and does not mark Health degraded. The manual action + is not guarded: the owner is there to see it fail. +- **The swap holds the writer.** It is one transaction per source. Its duration on the + reference Pi has not been measured; the orchestrator records it on fermi after the + v0.18.0 upgrade, where the first scheduled run will happen (its metadata is overdue). +- **Network.** The requests are the same unauthenticated GETs the button makes, now made + without a click. `docs/SECURITY.md` §10 lists them as scheduled. + +## Consequences + +- SPEC §27 carries the owner amendment; its original sentence stays, superseded. + ADR-0016's "No scheduled refresh in v1" paragraph points here. +- `metadata.auto_update_days` is a new setting that applies on save. +- A stock install that has imported metadata once now contacts the dataset hosts roughly + monthly without a click. That is the request. +- The import pipeline, its transactionality and its per-source independence are + unchanged: a scheduled run is the manual run, started by a clock. diff --git a/docs/adr/README.md b/docs/adr/README.md index a058cb63..488bea80 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -37,4 +37,5 @@ 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) | +| [0021](0021-scheduled-metadata-updates.md) | Scheduled metadata updates | Accepted | diff --git a/docs/design/077-feeders-page.md b/docs/design/077-feeders-page.md index f9520386..77bc5958 100644 --- a/docs/design/077-feeders-page.md +++ b/docs/design/077-feeders-page.md @@ -26,6 +26,12 @@ identities and never shown. | FlightRadar24 | `:8754/monitor.json` (all strings) | `feed_status`, `feed_status_message`, `feed_current_server`, `feed_last_ac_sent_time/_num`, `feed_last_connected_time`, `rx_connected`, `num_messages`, `timing_source`, `time_update_utc`, `build_version` | `fr24key`, `feed_alias`, `feed_legacy_id`, `local_ips`; never link `/settings.html` | | OpenSky | logs only, Statistics block every 10 min | `currently online|offline`, `N [P%] seconds online (overall)`, `disconnections`, `bytes sent (rate)` | timestamps local TZ | +Amended 2026-11-30 (slice 127, issue #369): for ADS-B out, only `Connection established` +and readsb's real close/failure lines are state (the newest decides). readsb's "Bad +connection, dropping data (connection lost N% of data)" warning is on an open +connection and only overlays the state as `degraded`; see ADR-0017's amendment of the +same date and `feeders/ultrafeeder.py`. + Local pages (200 on fermi and via `adsb.lonpix.com`): tar1090 `:8080/`, `:8080/graphs1090/`, SkyAware `:8081/`, FR24 `:8754/`. piaware status is at `:8081/status.json`, outside the `/skyaware/` proxy path. FR24 runs `MLAT=no` deliberately. No `aerodatabox-feed` container diff --git a/e2e/package-lock.json b/e2e/package-lock.json index 799bbfb2..edb5354a 100644 --- a/e2e/package-lock.json +++ b/e2e/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.0", "devDependencies": { "@axe-core/playwright": "^4.14.1", - "@playwright/test": "1.65.1", + "@playwright/test": "1.64.1", "@types/node": "^24.19.4", "typescript": "~6.0.3" }, @@ -34,13 +34,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.65.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", - "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.65.1" + "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -70,13 +70,13 @@ } }, "node_modules/playwright": { - "version": "1.65.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", - "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.65.1" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -86,9 +86,9 @@ } }, "node_modules/playwright-core": { - "version": "1.65.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", - "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/e2e/package.json b/e2e/package.json index 99b7e5f8..ad0118f3 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -26,7 +26,7 @@ }, "devDependencies": { "@axe-core/playwright": "^4.14.1", - "@playwright/test": "1.65.1", + "@playwright/test": "1.64.1", "@types/node": "^24.19.4", "typescript": "~6.0.3" } 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..f366bcbe --- /dev/null +++ b/e2e/tests/04-selected-deep-link-focus.spec.ts @@ -0,0 +1,113 @@ +/** + * 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, + type CurrentAircraft, + fetchPositionedAircraft, + waitForAircraftLayer, + waitForLiveAircraft, +} from "./support/liveMap"; +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 = pickOutlier(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) { + 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 }) => { + 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/package-lock.json b/frontend/package-lock.json index 2cdcef93..64c312bd 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "flightsite-frontend", - "version": "0.17.0", + "version": "0.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "flightsite-frontend", - "version": "0.17.0", + "version": "0.18.0", "dependencies": { "@radix-ui/react-separator": "^1.2.0", "@radix-ui/react-slot": "^1.5.0", diff --git a/frontend/package.json b/frontend/package.json index c1e5f5e0..e9410929 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "flightsite-frontend", "private": true, - "version": "0.17.0", + "version": "0.18.0", "type": "module", "engines": { "node": ">=22" 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/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..81748f93 100644 --- a/frontend/src/features/filters/hooks/useSelectionUrlSync.ts +++ b/frontend/src/features/filters/hooks/useSelectionUrlSync.ts @@ -12,9 +12,11 @@ * 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 - * 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 @@ -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/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 e74f5ec0..24344914 100644 --- a/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx +++ b/frontend/src/features/map/aircraft/useFocusSelectedAircraft.test.tsx @@ -150,6 +150,81 @@ 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("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; + 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..45ba0356 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,19 @@ export function useFocusSelectedAircraft(): void { if (target === null) { return; } + const onlyIfOffscreen = + useMapFocusRequestStore.getState().onlyIfOffscreen; endRequest(); const center: [number, number] = [target.lon, target.lat]; + // 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) { 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/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} /> +