-
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 all 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,131 @@ | ||
| """ | ||
| 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) | ||
|
|
||
|
|
||
| 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 _require_prefetch(occurrence: Occurrence, *relations: str) -> None: | ||
| """Raise if any required top-level relation is missing from the prefetch cache. | ||
|
|
||
| Only checks top-level relations; nested prefetch (e.g. `detections__classifications`) | ||
| is required by callers but not enforced here. Use the list/detail factories above | ||
| to keep the pairing correct. Tighter depth-checking is deferred to django-zen-queries | ||
| (#1271 follow-up). | ||
| """ | ||
| 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` (per-algorithm max-score, then `-terminal, -score`). | ||
| Skips `score=None` to match SQL semantics of `score__in=Subquery(...)`. | ||
|
|
||
| Strict: requires `detections` (and each detection's `classifications`) prefetched. | ||
| """ | ||
| _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]] | ||
| 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` (BEST_IDENTIFICATION_ORDER = -created_at, -pk). | ||
|
|
||
| Strict: requires `identifications` 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` prefetched. Pass `limit` to bound output. | ||
| """ | ||
| _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.