Skip to content

fix: batch list_people's per-person queries into one - #446

Merged
Abhash-Chakraborty merged 3 commits into
Abhash-Chakraborty:canaryfrom
payalrvs3:fix/people-list-n-plus-one
Aug 11, 2026
Merged

fix: batch list_people's per-person queries into one#446
Abhash-Chakraborty merged 3 commits into
Abhash-Chakraborty:canaryfrom
payalrvs3:fix/people-list-n-plus-one

Conversation

@payalrvs3

Copy link
Copy Markdown
Contributor

Summary

list_people() in backend/src/find_api/routers/people.py ran two separate database queries per person inside its main loop, a face-count query and a sample-media query so listing N people cost 1 + 2N queries. Measured empirically with 30 seeded people: 61 queries for one request.

Fixes #437

Type of change

  • Bug fix

Release impact

  • Patch (backward-compatible fix)

What changed

  • Replaced the per-person count/sample queries in list_people with a single query fetching every (person_id, media_id) face pair; face_count and sample_media_ids are both derived from it in Python instead of two extra round trips per person.
  • Dropped the now-unused func import.
  • Added 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/ -v

To see the query-count difference directly: seed 30+ distinct people and compare query counts before/after with SQL echo (echo=True on 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

  • I linked the related issue
  • I ran required checks from CONTRIBUTING.md
  • I updated docs/env notes if needed (none needed)
  • My PR is scoped to a single issue
  • I followed commit message conventions
  • I am not committing secrets or local artifacts
  • This PR targets canary unless it is the maintainer promotion PR

GSSoC'26 checklist

  • I requested issue assignment before starting
  • I have meaningful commits (no spam commits)
  • I am ready to explain my implementation in review comments

Signed-off-by: Payalrvs0310@gmail.com <Payalrvs0310@gmail.com>
@github-actions

Copy link
Copy Markdown

PR Context Summary

Suggested issue links

  • No strong issue match found yet.

Use Fixes #123 or Closes #123 in the PR body when one of the suggestions is the intended issue.
Manual rerun: Actions > PR Context Triage > Run workflow > set pr_number and force_review=true.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@Abhash-Chakraborty, you've reached your PR review limit, so we couldn't start this review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9a17db74-b1ea-420e-a74a-9274aecd50a4

📥 Commits

Reviewing files that changed from the base of the PR and between d03e717 and 981d0a9.

📒 Files selected for processing (2)
  • backend/src/find_api/routers/people.py
  • backend/tests/test_people.py

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@macroscopeapp

macroscopeapp Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Approvability

Verdict: 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 Abhash-Chakraborty added gssoc26 Related to GirlScript Summer of Code 2026. gssoc:approved Valid GSSoC contribution approved for scoring. type:performance Performance improvement PR. GSSoC type bonus: +15 points. quality:clean Clean and maintainable PR. GSSoC contributor multiplier: 1.2x. backend FastAPI, database, storage, and API work api API contract, endpoint behavior, and response shape performance Speed, startup, memory, image size, and runtime efficiency bug Something is broken and needs to be fixed. level:intermediate GSSoC difficulty level: intermediate. Base contributor points: 35. labels Aug 11, 2026

@Abhash-Chakraborty Abhash-Chakraborty left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_countGROUP BY over the scoped face set.
  • sample_media_idsROW_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 no ORDER BY, so a person's thumbnail could change between requests. Ordering by media_id pins 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.

@Abhash-Chakraborty
Abhash-Chakraborty merged commit b2cdd6e into Abhash-Chakraborty:canary Aug 11, 2026
29 of 30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api API contract, endpoint behavior, and response shape backend FastAPI, database, storage, and API work bug Something is broken and needs to be fixed. gssoc:approved Valid GSSoC contribution approved for scoring. gssoc26 Related to GirlScript Summer of Code 2026. level:intermediate GSSoC difficulty level: intermediate. Base contributor points: 35. performance Speed, startup, memory, image size, and runtime efficiency quality:clean Clean and maintainable PR. GSSoC contributor multiplier: 1.2x. type:performance Performance improvement PR. GSSoC type bonus: +15 points.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: list_people runs 2 extra database queries per person (N+1)

2 participants