Skip to content

fix(Segments): Fix N+1 on get_segment retrieve#7563

Open
matthewelwell wants to merge 1 commit into
mainfrom
fix(segments)/get_segment-n+1-fix
Open

fix(Segments): Fix N+1 on get_segment retrieve#7563
matthewelwell wants to merge 1 commit into
mainfrom
fix(segments)/get_segment-n+1-fix

Conversation

@matthewelwell
Copy link
Copy Markdown
Contributor

Thanks for submitting a PR! Please check the boxes below:

  • I have read the Contributing Guide.
  • I have added information to docs/ if required so people know about the feature.
  • I have filled in the "Changes" section below.
  • I have filled in the "How did you test this code" section below.

Changes

Closes #7557

The retrieve action on SegmentViewSet was missing the prefetch_related applied to list, causing a separate SELECT query for conditions for every rule on the segment (N+1). Additionally, has_object_permission was lazily loading segment.project and project.organisation on every retrieve request.

  • Extends prefetch_related to cover retrieve as well as list
  • Adds select_related("project__organisation") for retrieve to avoid the redundant lazy-loads triggered by has_object_permission
  • Adds a query-count regression test (test_retrieve_segment__without_rbac__expected_num_queries)

How did you test this code?

Added a django_assert_num_queries test that creates a segment with 3 nested rules and conditions and asserts the total query count is fixed regardless of the number of rules, covering both admin_client and admin_master_api_key_client auth types.

@matthewelwell matthewelwell requested a review from a team as a code owner May 21, 2026 11:22
@matthewelwell matthewelwell requested review from khvn26 and removed request for a team May 21, 2026 11:22
Copy link
Copy Markdown

@claude claude Bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@vercel
Copy link
Copy Markdown

vercel Bot commented May 21, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

3 Skipped Deployments
Project Deployment Actions Updated (UTC)
docs Ignored Ignored May 21, 2026 11:22am
flagsmith-frontend-preview Ignored Ignored May 21, 2026 11:22am
flagsmith-frontend-staging Ignored Ignored May 21, 2026 11:22am

Request Review

@github-actions github-actions Bot added api Issue related to the REST API fix labels May 21, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 21, 2026

Docker builds report

Image Build Status Security report
ghcr.io/flagsmith/flagsmith-e2e:pr-7563 Finished ✅ Skipped
ghcr.io/flagsmith/flagsmith-api-test:pr-7563 Finished ✅ Skipped
ghcr.io/flagsmith/flagsmith-frontend:pr-7563 Finished ✅ Results
ghcr.io/flagsmith/flagsmith-api:pr-7563 Finished ✅ Results
ghcr.io/flagsmith/flagsmith:pr-7563 Finished ✅ Results
ghcr.io/flagsmith/flagsmith-private-cloud:pr-7563 Finished ✅ Results

@codecov
Copy link
Copy Markdown

codecov Bot commented May 21, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.48%. Comparing base (1c49c44) to head (833ab67).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7563   +/-   ##
=======================================
  Coverage   98.48%   98.48%           
=======================================
  Files        1402     1402           
  Lines       53300    53315   +15     
=======================================
+ Hits        52490    52505   +15     
  Misses        810      810           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 21, 2026

Playwright Test Results (private-cloud - depot-ubuntu-latest-arm-16)

passed  19 passed

Details

stats  19 tests across 15 suites
duration  1 minute, 9 seconds
commit  833ab67
info  🔄 Run: #16886 (attempt 1)

Playwright Test Results (oss - depot-ubuntu-latest-16)

passed  1 passed

Details

stats  1 test across 1 suite
duration  39 seconds
commit  833ab67
info  🔄 Run: #16886 (attempt 1)

Playwright Test Results (oss - depot-ubuntu-latest-arm-16)

passed  1 passed

Details

stats  1 test across 1 suite
duration  42.9 seconds
commit  833ab67
info  🔄 Run: #16886 (attempt 1)

Playwright Test Results (private-cloud - depot-ubuntu-latest-16)

passed  3 passed

Details

stats  3 tests across 3 suites
duration  38.5 seconds
commit  833ab67
info  🔄 Run: #16886 (attempt 1)

@github-actions
Copy link
Copy Markdown
Contributor

Visual Regression

19 screenshots compared. See report for details.
View full report

Copy link
Copy Markdown
Contributor

@Zaimwa9 Zaimwa9 left a comment

Choose a reason for hiding this comment

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

👍

@Zaimwa9
Copy link
Copy Markdown
Contributor

Zaimwa9 commented May 22, 2026

@gemini-code-assist review

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes the segment retrieve action by implementing prefetch_related for rules and conditions and select_related for project and organization relationships to prevent N+1 query issues. A new unit test has been added to verify the expected number of database queries for this endpoint. The reviewer suggests extending these optimizations to other actions like update, partial_update, destroy, and clone to ensure consistent performance and efficient permission checks across all detail-oriented endpoints.

Comment thread api/segments/views.py
queryset = Segment.live_objects.filter(project=project, is_system_segment=False)

if self.action == "list":
if self.action in ("list", "retrieve"):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The N+1 optimization (prefetching rules and conditions) should also be applied to other actions that return the full segment representation, such as update, partial_update, and clone. This ensures that the response serialization and the cloning logic (which iterates over rules/conditions) do not trigger redundant database queries.

Suggested change
if self.action in ("list", "retrieve"):
if self.action in ("list", "retrieve", "update", "partial_update", "clone"):

Comment thread api/segments/views.py
Comment on lines +119 to +120
if self.action == "retrieve":
queryset = queryset.select_related("project__organisation")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The select_related("project__organisation") optimization should be extended to all detail actions that trigger object permission checks via get_object(). This includes update, partial_update, destroy, associated_features, and clone. This prevents redundant lazy-loading of the project and organisation during the has_object_permission check in SegmentPermissions.

Suggested change
if self.action == "retrieve":
queryset = queryset.select_related("project__organisation")
if self.action in ("retrieve", "update", "partial_update", "destroy", "associated_features", "clone"):
queryset = queryset.select_related("project__organisation")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Issue related to the REST API fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

N+1 query issue on get_segment endpoint

2 participants