-
Notifications
You must be signed in to change notification settings - Fork 15
fix(occurrences): remove all n+1 queries from occurrence API #1274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3e7d9dd
fix(occurrences): prefetch detections/classifications in list view to…
mihow b62fb39
fix(occurrences): address PR #1274 review feedback
mihow 80d4404
refactor(occurrences): centralize BEST_IDENTIFICATION_ORDER constant
mihow 22995b3
refactor(occurrences): require prefetch in serializer; drop fallback …
mihow 454ec77
refactor(occurrences): strict prefetch helpers + bounded list detecti…
mihow 38b04cb
test(occurrences): trim test surface
mihow 8f7db77
fix(occurrences): apply detail prefetches to JSON exporter; cap list …
mihow 1f5918a
test(occurrence): cover multi-detection scaling + drop None scores
mihow cbae3fc
chore(scripts): add reproducible benchmark for occurrences list endpoint
mihow 80f36cb
refactor(occurrence): drop empty wrappers, trim prefetch helper docst…
mihow 9b1c532
test: add N+1 regression guards for SourceImage and Taxon list endpoints
mihow d41deb7
fix(api): make TaxonListSerializer.parents actually return parent chain
mihow 054d331
chore: address CodeRabbit nits on test fixture and benchmark script
mihow File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| """ | ||
| Reusable Prefetch factories for Occurrence list/detail rendering. | ||
|
|
||
| The serializer trusts the prefetch contract — the viewset is the single place | ||
| that wires it up. Don't gate serializer methods on `_prefetched_objects_cache` | ||
| membership; require the prefetch. | ||
|
|
||
| Tracking issue: https://github.com/RolnickLab/antenna/issues/1271 | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| from django.db.models import Prefetch | ||
|
|
||
| if TYPE_CHECKING: | ||
| from ami.main.models import Classification, Identification, Occurrence | ||
|
|
||
|
|
||
| def _detections_prefetch(*, ordering: tuple[str, ...], with_source_image: bool) -> Prefetch: | ||
| from ami.main.models import Classification, Detection | ||
|
|
||
| qs = Detection.objects.prefetch_related( | ||
| Prefetch( | ||
| "classifications", | ||
| queryset=Classification.objects.select_related("taxon", "algorithm"), | ||
| ) | ||
| ).order_by(*ordering) | ||
| if with_source_image: | ||
| qs = qs.select_related("source_image") | ||
| return Prefetch("detections", queryset=qs) | ||
|
|
||
|
|
||
| def prefetch_detections_for_list() -> Prefetch: | ||
| """Detections + nested classifications, ordered for stable list image galleries.""" | ||
| return _detections_prefetch(ordering=("frame_num", "timestamp"), with_source_image=False) | ||
|
mihow marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def prefetch_detections_for_detail() -> Prefetch: | ||
| """Detections + nested classifications + source_image, ordered most-recent-first. | ||
|
|
||
| Detail responses serialize each detection via `DetectionNestedSerializer`, | ||
| which dereferences `source_image` (as `capture`). | ||
| """ | ||
| return _detections_prefetch(ordering=("-timestamp",), with_source_image=True) | ||
|
|
||
|
|
||
| def prefetches_for_list_serializer() -> list[Prefetch]: | ||
| return [prefetch_detections_for_list()] | ||
|
|
||
|
|
||
| def prefetches_for_detail_serializer() -> list[Prefetch]: | ||
| return [prefetch_detections_for_detail()] | ||
|
|
||
|
|
||
| def _require_prefetch(occurrence: Occurrence, *relations: str) -> None: | ||
| """Raise if any required relation is missing from the prefetch cache. | ||
|
|
||
| Strict contract: callers in serializer code must go through a viewset that | ||
| applied the corresponding prefetch. Silent slow-pathing (the serializer | ||
| triggering its own DB queries) is the N+1 we are fixing. | ||
|
|
||
| Caveat: only top-level relations are checked. Nested prefetch (e.g. | ||
| `detections__classifications`) is still required but not enforced here — | ||
| if a caller prefetches `detections` without nested `classifications`, | ||
| `best_prediction_from_prefetch` will silently re-introduce per-detection | ||
| queries. The list/detail prefetch factories pair them correctly; new | ||
| callers should use those factories rather than building Prefetch objects | ||
| by hand. Tighter enforcement is deferred to the django-zen-queries pass | ||
| (issue #1271 follow-up), which catches all per-row queries at the view | ||
| boundary regardless of depth. | ||
| """ | ||
| cache = getattr(occurrence, "_prefetched_objects_cache", {}) | ||
| missing = [r for r in relations if r not in cache] | ||
| if missing: | ||
| raise RuntimeError( | ||
| f"Occurrence {occurrence.pk} is missing prefetched relations {missing!r}. " | ||
| "Apply OccurrenceQuerySet.with_list_prefetches() / with_detail_prefetches() / " | ||
| "with_identifications() in the viewset's get_queryset()." | ||
| ) | ||
|
|
||
|
|
||
| def best_prediction_from_prefetch(occurrence: Occurrence) -> Classification | None: | ||
| """Pick the best machine prediction from a prefetched occurrence in Python. | ||
|
|
||
| Mirrors `Occurrence.best_prediction`, which calls `Occurrence.predictions()` | ||
| (per-algorithm max-score filtering) and then orders by `-terminal, -score`. | ||
|
|
||
| Null-score handling: classifications with `score=None` are skipped, which | ||
| matches the SQL behavior of `score__in=Subquery(...)` — `Max(score)` over | ||
| only-NULL rows returns NULL, and `score IN (NULL)` never matches in SQL. | ||
|
|
||
| Subtle SQL/Python difference (intentional): `Occurrence.predictions()` uses | ||
| `score__in=Subquery(per-algo maxes)`. If algo_A's max is 0.9 and algo_B has | ||
| a non-max classification at 0.9, the SQL form includes both; this Python | ||
| form keeps only per-algorithm maxima (algo_A's 0.9, not algo_B's). The | ||
| Python form is the stricter interpretation of the docstring intent | ||
| ("max score for each algorithm"). | ||
|
|
||
| Strict: requires `detections` (and each detection's `classifications`) to be | ||
| prefetched. Raises if not. | ||
| """ | ||
| _require_prefetch(occurrence, "detections") | ||
| classifications = [ | ||
| c for det in occurrence.detections.all() for c in det.classifications.all() if c.score is not None | ||
| ] | ||
| if not classifications: | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| return None | ||
|
|
||
| max_score_per_algo: dict[object, float] = {} | ||
| for c in classifications: | ||
| existing = max_score_per_algo.get(c.algorithm_id) | ||
| if existing is None or c.score > existing: | ||
| max_score_per_algo[c.algorithm_id] = c.score | ||
|
|
||
| candidates = [c for c in classifications if c.score == max_score_per_algo[c.algorithm_id]] | ||
| if not candidates: | ||
| return None | ||
| candidates.sort( | ||
| key=lambda c: ( | ||
| 0 if getattr(c, "terminal", False) else 1, | ||
| -c.score, | ||
| -c.pk, | ||
| ) | ||
| ) | ||
| return candidates[0] | ||
|
|
||
|
|
||
| def best_identification_from_prefetch(occurrence: Occurrence) -> Identification | None: | ||
| """Pick the most recent non-withdrawn identification from prefetched data. | ||
|
|
||
| Mirrors `Occurrence.best_identification`, which uses | ||
| `BEST_IDENTIFICATION_ORDER = ("-created_at", "-pk")`. `created_at=None` is | ||
| treated as lower than any real timestamp. | ||
|
|
||
| Strict: requires `identifications` to be prefetched (via | ||
| `OccurrenceQuerySet.with_identifications()`). | ||
| """ | ||
| _require_prefetch(occurrence, "identifications") | ||
| best: Identification | None = None | ||
| best_key: tuple[bool, object, int] | None = None | ||
| for ident in occurrence.identifications.all(): | ||
| if ident.withdrawn: | ||
| continue | ||
| ident_key: tuple[bool, object, int] = (ident.created_at is not None, ident.created_at, ident.pk) | ||
| if best_key is None or ident_key > best_key: | ||
| best = ident | ||
|
mihow marked this conversation as resolved.
|
||
| best_key = ident_key | ||
| return best | ||
|
|
||
|
|
||
| def detection_image_urls_from_prefetch(occurrence: Occurrence, limit: int | None = None) -> list[str]: | ||
| """Return media URLs for the prefetched detections (filtering out `path=None`). | ||
|
|
||
| Strict: requires `detections` to be prefetched. Pass `limit` to bound output — | ||
| list responses cap at a few cover images; detail responses currently return | ||
| all (TODO: bound when occurrence tracking lands; per-occurrence detection | ||
| counts can reach thousands). | ||
| """ | ||
| _require_prefetch(occurrence, "detections") | ||
|
|
||
| from ami.main.models import get_media_url | ||
|
|
||
| detections = [det for det in occurrence.detections.all() if det.path] | ||
| if limit is not None: | ||
| detections = detections[:limit] | ||
| return [get_media_url(det.path) for det in detections] | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.