fix: batch list_people's per-person queries into one - #446
Conversation
Signed-off-by: Payalrvs0310@gmail.com <Payalrvs0310@gmail.com>
PR Context Summary
Suggested issue links
Use |
|
Warning Review limit reached
Next review available in: 31 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
ApprovabilityVerdict: Needs human review This performance optimization batches N+1 database queries into fixed aggregate queries with new SQL constructs (subqueries, window functions). The author does not own the modified files, so the designated code owner should review these query logic changes. You can customize Macroscope's approvability policy. Learn more. |
The batching removed the 1 + 2N round trips, but replaced them with a single unbounded read: every visible (person_id, media_id) face pair in the library was fetched and folded in Python. That is constant in *queries* while being linear in *rows transferred*, so a large library trades one scaling cliff for another on the same endpoint the issue set out to make fast. Both aggregates now run in the database: - face_count is a GROUP BY over the scoped face set. - sample_media_ids uses ROW_NUMBER() OVER (PARTITION BY person_id), so the database returns at most SAMPLE_MEDIA_LIMIT rows per person instead of all of them. Ordering by media_id also makes the chosen thumbnail stable — the original `.distinct().limit(4)` had no ORDER BY and could return a different sample on each request. The shared-mode scope now lives in one helper used by both, so the count can never include rows the samples exclude. Adds a test asserting the query count is *constant*, not merely smaller: it seeds 3 people, then 23, and requires the same number of SELECTs. Against the original code it reports 7 -> 47. Response-shape assertions alone would not have caught the N+1, since the data was already correct — only slow.
Abhash-Chakraborty
left a comment
There was a problem hiding this comment.
Approved, with one change pushed.
The fix was right about queries but moved the cost rather than removing it. faces_query.all() fetched every visible (person_id, media_id) pair in the library and folded them in Python — constant in queries, linear in rows transferred. On a large library that is the same scaling cliff in a different place, on the endpoint the issue set out to make fast.
Pushed a commit moving both aggregates into SQL:
face_count→GROUP BYover the scoped face set.sample_media_ids→ROW_NUMBER() OVER (PARTITION BY person_id), so the database returns at most 4 rows per person instead of all of them.
Two things that fell out of it:
- The shared-mode scope now lives in one helper used by both aggregates. Previously the filters were written out twice; a count that included rows the samples excluded would surface a person group the page cannot render — and in shared mode that is the privacy boundary, not a cosmetic bug.
- Thumbnails are now stable. The original
.distinct().limit(4)had noORDER BY, so a person's thumbnail could change between requests. Ordering bymedia_idpins it.
Added the test that actually keeps this fixed: it seeds 3 people, then 23, and asserts the SELECT count is identical. Against the pre-fix code it reports 7 -> 47. Your test_..._not_mixed_between_people is a good correctness check, but response-shape assertions alone could never have caught the original N+1 — the data was already correct, just slow.
Verified locally: ruff check/format --check clean, full backend suite 788 passed, 7 skipped. Confirmed ROW_NUMBER works on the SQLite test engine as well as Postgres.
b2cdd6e
into
Abhash-Chakraborty:canary
Summary
list_people()inbackend/src/find_api/routers/people.pyran two separate database queries per person inside its main loop, a face-count query and a sample-media query so listing N people cost1 + 2Nqueries. Measured empirically with 30 seeded people: 61 queries for one request.Fixes #437
Type of change
Release impact
What changed
list_peoplewith a single query fetching every(person_id, media_id)face pair;face_countandsample_media_idsare both derived from it in Python instead of two extra round trips per person.funcimport.test_people_list_counts_and_samples_are_not_mixed_between_people(backend/tests/test_people.py) multiple people, multiple faces each (including two faces in the same media), verifying counts and samples aren't mixed up between people in the batched rewrite.Screenshots / recordings (for UI changes)
N/A - backend-only change.
How to test
cd backend uv run pytest tests/test_people.py -v uv run pytest tests/ -vTo see the query-count difference directly: seed 30+ distinct people and compare query counts before/after with SQL echo (
echo=Trueon the engine) or Postgres's query log. I measured 61 queries before the fix and 2 after - constant regardless of N (checked at both 30 and 100 people).Checklist
canaryunless it is the maintainer promotion PRGSSoC'26 checklist