Repository navigation
fix(alerts): rare-type counts stay current between imports (slice 128) - #378
Merged
Merged
Conversation
…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
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Slice 128. Closes #364.
Summary
The metadata cache's per-type airframe map (
type_aircraft_hereforrare_typeconditions) 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 arare_typerule 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.load_type_counts()now returns aTypeCount(airframes, through_aircraft_id)per type: the sameGROUP BYas before plusmax(aircraft.id). The newload_type_count(type_code)is the same query for a single type.aircraftrows 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.type_count()isNoneuntil 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.type_aircraft_herecomes fromtype_count_including(...). It isNoneuntil the persistence worker has given the airframe's row ids and the count includes it.max(1, …)floor is deleted, because a count that includes the airframe is at least 1.awaiting_type_countflag joinsawaiting_metadata/awaiting_sighting/pendingin the repair pass._state_forcallsrequest_type_countonce the airframe has anaircraft_id.AircraftMetadataView.type_countstays as a display snapshot, documented as such. The engine no longer reads it.Rulings implemented (Fable plan review 5–9)
aircraft_metadata_resolved, and imports already end ininvalidate(). The only change between imports is a newaircraftrow. That is the event the cache now handles.type_count_including), not theview.type_countsnapshot.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).type_aircraft_hereisNoneuntil the row exists and the count has been re-read after it. Themax(1, …)floor is deleted. The repair pass has a new condition,awaiting_type_count("type known, count unknown")./analytics/raritykeeps readingtype_stats. Both use the same definition and the same<=. DATA_MODEL §6.5 now documents thattype_statstrails a newly persisted airframe by one rollup pass (at most the 30 s flush). The agreement test asserts agreement after atype_statsrefresh, and that the endpoint does not list the type before it.Query plan: the per-type re-read
Without statistics (fresh install):
After
ANALYZE(synthetic DB: 200k resolved rows across 5 types, 20k airframes; the maintenance task'sPRAGMA optimizecan write these statistics):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_typerule. Checked 2026-11-30: its rules are military, government, police, first_ever, locally_rare and watchlist, plus the defaults. No falserare_typematches exist there to remove.Tests
New:
tests/metadata/test_cache.pyNonefor the new airframe until re-read, then includes it; a second airframe of a known type goes from 2 to 3tests/alerts/test_engine.pytype_aircraft_hereisNonebefore the row commits and while the map predates it, then 1rare_type max 1rule, 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.AnalyticsQueries.rarityat thresholds 1, 2 and 3 after atype_statsrefresh, with the sameunique_aircraft. The endpoint does not list the type before the pass.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.pyis untouched. Slice 131 owns its update/locking code.lookup()there still buildstype_countfromcache.type_count(), which now returnsint | None. The field type already allowedNone.aircraft_id. It was already in the repair set throughawaiting_sighting, so nothing changes there.🤖 Generated with Claude Code
https://claude.ai/code/session_01JFZvpNYnicPHv6pjHTVK2f