Skip to content

fix(alerts): rare-type counts stay current between imports (slice 128) - #378

Merged
stevenpickles merged 5 commits into
devfrom
128-rare-type-live-counts
Nov 30, 2026
Merged

stevenpickles merged 5 commits into
devfrom
128-rare-type-live-counts

Conversation

@stevenpickles

Copy link
Copy Markdown
Owner

Slice 128. Closes #364.

Summary

The metadata cache's per-type airframe map (type_aircraft_here for rare_type conditions) was loaded only at start and after a metadata import, and the engine read a copy frozen into each cached view, floored at one. So a type first heard since the last load read 0, was floored to 1, and every airframe of that type matched a rare_type rule until the next import or restart.

The fix follows slice 125's design for sightings_here. While the count is unknown, the condition fails and the airframe stays in the engine's repair set. It is evaluated again once the real count is known.

  • Repository. load_type_counts() now returns a TypeCount(airframes, through_aircraft_id) per type: the same GROUP BY as before plus max(aircraft.id). The new load_type_count(type_code) is the same query for a single type. aircraft rows are never deleted, and the single writer assigns ids in commit order. So a count whose mark is at least an airframe's id was read after that airframe's row committed, and it includes that airframe.
  • Cache.
    • type_count() is None until the first load.
    • type_count_including(type, aircraft_id) answers only when the type's mark covers that airframe. It is pure memory.
    • request_type_count(type) re-reads one type on the cache's own task, under the population lock, so it cannot interleave with an import's reload. Requests are deduplicated per type. wait_idle() also waits for these re-reads.
  • Engine.
    • type_aircraft_here comes from type_count_including(...). It is None until the persistence worker has given the airframe's row ids and the count includes it.
    • The max(1, …) floor is deleted, because a count that includes the airframe is at least 1.
    • A new awaiting_type_count flag joins awaiting_metadata / awaiting_sighting / pending in the repair pass. _state_for calls request_type_count once the airframe has an aircraft_id.
  • AircraftMetadataView.type_count stays as a display snapshot, documented as such. The engine no longer reads it.

Rulings implemented (Fable plan review 5–9)

  1. The type is known only from aircraft_metadata_resolved, and imports already end in invalidate(). The only change between imports is a new aircraft row. That is the event the cache now handles.
  2. The engine reads the live map (type_count_including), not the view.type_count snapshot.
  3. The cache does a targeted, idempotent re-read of the one type instead of adding 1. It runs the same SQL as load_type_counts / derive_type_stats, restricted to that type (query plan below). Asking twice, or asking about a current type, cannot inflate the count (tested).
  4. The count includes this airframe. type_aircraft_here is None until the row exists and the count has been re-read after it. The max(1, …) floor is deleted. The repair pass has a new condition, awaiting_type_count ("type known, count unknown").
  5. One shared source is not possible here. /analytics/rarity keeps reading type_stats. Both use the same definition and the same <=. DATA_MODEL §6.5 now documents that type_stats trails a newly persisted airframe by one rollup pass (at most the 30 s flush). The agreement test asserts agreement after a type_stats refresh, and that the endpoint does not list the type before it.

Query plan: the per-type re-read

SELECT count(aircraft.id), max(aircraft.id)
FROM aircraft_metadata_resolved JOIN aircraft ON aircraft.icao24 = aircraft_metadata_resolved.icao24
WHERE aircraft_metadata_resolved.type_code = ?

Without statistics (fresh install):

SEARCH aircraft_metadata_resolved USING COVERING INDEX ix_amr_type (type_code=?)
SEARCH aircraft USING COVERING INDEX sqlite_autoindex_aircraft_1 (icao24=?)

After ANALYZE (synthetic DB: 200k resolved rows across 5 types, 20k airframes; the maintenance task's PRAGMA optimize can write these statistics):

SCAN aircraft USING COVERING INDEX sqlite_autoindex_aircraft_1
SEARCH aircraft_metadata_resolved USING COVERING INDEX ix_amr_type (type_code=? AND icao24=?)

Both plans read only covering indexes and never scan a table. The cost is bounded by the smaller of the type's resolved rows and the airframes heard here. The query runs at most once per newly heard airframe that has a resolved type, and never on the ingest or evaluation path.

No data migration

The production instance (fermi) has no rare_type rule. Checked 2026-11-30: its rules are military, government, police, first_ever, locally_rare and watchlist, plus the defaults. No false rare_type matches exist there to remove.

Tests

New:

  • tests/metadata/test_cache.py
    • counts are unknown before the first load
    • a type first heard after the load is None for the new airframe until re-read, then includes it; a second airframe of a known type goes from 2 to 3
    • a re-read is idempotent
    • restart consistency: after re-reads, a fresh cache over the same DB loads identical counts and marks
  • tests/alerts/test_engine.py
    • type_aircraft_here is None before the row commits and while the map predates it, then 1
    • Rarity: per-type airframe counts go stale between metadata imports (rare_type) #364 reproduced: with a rare_type max 1 rule, a type first heard after the load matches its first airframe once (from the repair pass, no event needed). The second airframe does not match (count 2), and nothing is left in the repair set afterwards.
    • the condition agrees with AnalyticsQueries.rarity at thresholds 1, 2 and 3 after a type_stats refresh, with the same unique_aircraft. The endpoint does not list the type before the pass.
  • One existing test (test_going_stale_evaluates_nothing) now lets the owed type-count re-evaluation run before the aircraft goes stale. Its A320 airframe is new to a map that was loaded empty, so one more evaluation is correct.

Run (targeted, per the machine-load rule):

  • uv run ruff check .: clean. uv run ruff format --check .: clean. uv run mypy: no issues (577 files).
  • uv run pytest tests/alerts tests/metadata --no-cov: 963 passed.
  • uv run pytest tests/api/test_alerts_api.py tests/api/test_serializer_metadata.py tests/watchlists/test_cache_integration.py tests/analytics/test_api.py tests/demo/test_airframes.py --no-cov: 217 passed.

Notes and discovered work

  • metadata/service.py is untouched. Slice 131 owns its update/locking code. lookup() there still builds type_count from cache.type_count(), which now returns int | None. The field type already allowed None.
  • A new airframe of a type the map does not cover costs one extra engine evaluation (the repair pass after the re-read lands). The cost is bounded by new airframes per cycle.
  • If the persistence worker is degraded, an airframe never gets an aircraft_id. It was already in the repair set through awaiting_sighting, so nothing changes there.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f

stevenpickles and others added 3 commits November 30, 2026 08:58
…import

The metadata cache's per-type airframe map was loaded only at start and
after an import, and the engine read a copy frozen into each view, floored
at one. A type first heard since the last load read zero, became one, and
every airframe of it matched a rare_type rule (#364).

- metadata repository: each type count carries the highest aircraft.id it
  covers (TypeCount); load_type_count re-reads one type with the same
  GROUP BY as the full load and type_stats.
- metadata cache: counts are unknown until the first load;
  type_count_including(type, aircraft_id) answers only when the count's
  mark covers the airframe; request_type_count re-reads one type on the
  cache's own task, under the population lock, deduped per type.
- alerts engine: type_aircraft_here is None until the airframe's row has
  ids and the cache's count includes it; the max(1, ...) floor is gone;
  awaiting_type_count joins the repair pass and asks for the re-read.

Closes #364

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
DATA_MODEL §6.5 documents that the alert condition and
GET /analytics/rarity count the same airframes with the same inequality,
that type_stats trails a newly persisted airframe by one rollup pass, and
how the cache keeps its count current between imports. ARCHITECTURE §3.3
and the API rule-condition table point there. Adds roadmap slice 128.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
Fable review of PR #378:

- cache: the population task owns the idle flag. A re-read finishing
  while the loop holds an event and waits on the lock no longer reports
  the cache idle (_populating, _settle_idle); wait_idle loops until both
  are done. stop() clears the task before cancelling re-reads. Re-read
  failures are warned at most once per 5 minutes, with a failure count.
  The docstring records the id-growth invariant and the self-healing
  window between an import's swap and its invalidate.
- engine: awaiting_type_count and the re-read only while an enabled rule
  has a rare_type condition; a rare_type rule coming into force gives
  every live aircraft one repair pass.
- docs: DATA_MODEL §2.2 and §6.5 state that aircraft rows are never
  deleted and ids only grow, that the type-count mark depends on it, and
  that a pruning slice must revisit it.
- tests: a population parked behind a re-read (fails without the fix),
  the rate-limited warning, an airframe committed during a re-read being
  asked for again, and no waiting without a rare_type rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f
@stevenpickles

Copy link
Copy Markdown
Owner Author

Review follow-ups pushed in 8540c5a: both required items (DATA_MODEL §2.2/§6.5 id-growth invariant; the population task now owns the idle flag, with a regression test that fails without the fix) and nits a–e. (f) is left for the issue. Targeted: ruff, format, mypy clean; pytest tests/alerts tests/metadata: 967 passed.

@stevenpickles
stevenpickles merged commit ba99e6a into dev Nov 30, 2026
14 checks passed
@stevenpickles
stevenpickles deleted the 128-rare-type-live-counts branch November 30, 2026 15:31
@stevenpickles stevenpickles mentioned this pull request Nov 30, 2026
20 of 28 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rarity: per-type airframe counts go stale between metadata imports (rare_type)

1 participant