Skip to content

feat(lint): Flag .first() on querysets with no explicit ordering - #130924

Merged
leeandher merged 4 commits into
leanderrodrigues/iswf-3679-noqa-productfrom
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
Nov 18, 2026
Merged

leeandher merged 4 commits into
leanderrodrigues/iswf-3679-noqa-productfrom
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to

Conversation

@leeandher

@leeandher leeandher commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Final PR for the new lint rule, this will be merged last in this stack ofc, but also after https://github.com/getsentry/getsentry/pull/23186.

The downstack PRs:

  • already converted the guaranteed unique .filter().first() usages
  • added #noqa comments referencing the rule being added here

If any violations are added after the merging of all those other PRs, they will be one-off'd here because I don't know a better way to handle that.

As for why we're adding this rule, it was one of the contributors to INC-2492

  • this pattern is largely used in the codebase to avoid DoesNotExist exceptions and get None instead, but get_or_none is more explicit about this
  • Django adds a ORDER BY pk to the query, and on the wrong table without an index this can break things, like the whole db for example
  • to get around this, devs should either explictly order, or not use this pattern.
AI Commentary

Adds flake8 rule S035, which flags .first() on a queryset with no explicit .order_by(...). The message tells the author to use .get_or_none() for a unique row, or to order by a column that matches the filter's index.

Why this pattern is risky. .first() on an unordered queryset makes Django add ORDER BY <pk> ASC LIMIT 1. For a selective filter, Postgres can then pick a plan that walks the primary-key index in order and checks the filter row by row, instead of using the filter's own index. On a large table where few or no rows match, that becomes a long scan. Most of these calls only wanted "the row or None", which .get_or_none() says directly without adding the ordering.

What the rule flags.

  • It follows the chain back from .first() through known QuerySet methods (filter, exclude, select_related, values_list, select_for_update, …) to a manager: Model.objects or a reverse *_set manager.
  • The last order_by() in the chain decides. With fields it counts as ordered. With no fields it clears the ordering, so .order_by().first() is flagged.
  • The error points at the .first line, so in a multi-line chain # noqa: S035 goes on that line.

What it deliberately doesn't flag, and why.

  • Chains that start from a helper call or a custom manager method, such as get_queryset().first() or Release.objects.filter_by_semver(v).first(). These often order the queryset themselves, and a single-file lint can't see inside them.
  • A bare variable, qs.first(). Nothing in the expression shows it's a queryset, or that it isn't already ordered.
  • Tests. They often rely on the pk ordering, and their queries run on tiny tables. testutils/ is exempt for the same reason.
  • Migrations. Applied migrations shouldn't be edited. Linting them also triggers the migration-drift check on any PR that touches one.
  • .agents/. Agent skill scripts only query a local dev database. It's exempted in setup.cfg.

So the rule is a heuristic that misses some cases: related managers like project.teams.first(), querysets passed around in variables, .last() (which has the same implicit ordering) and afirst().

Why a lint rule and not a runtime check in the manager. A check inside BaseQuerySet.first() could see the real query, but it would only fire on code paths tests run, and only in tests. The lint covers every changed line before review, in both repos.

Why order_by("id") passes, and why it isn't a fix. The rule can't tell an order_by("id") added only to quiet it from one that means "oldest first". Ordering by id does not help; it sends the same query as the implicit ordering, so the slow plan stays. The lint message says exactly that, so it doesn't read as permission. Flagging id/pk orderings could be a later tightening, but order_by("-id").first() is sometimes a real "latest row" lookup, so that has its own cost.

Rollout.

  • The PRs below this one convert the call sites that are provably unique to .get_or_none(). A script checked each model's primary key, unique fields and unique constraints. The rest are marked with # noqa: S035, which replaces the fingerprint allowlist from chore(ci): Add a flake8 rule for usage of .first() #123790: it needs no tooling, works the same in getsentry, and disappears when a site is fixed.
  • getsentry loads this plugin from its sentry checkout (paths = ../sentry), so its existing call sites must be marked before its sentry pin picks up the rule.
  • Calls added to master after the noqa PRs and before this one won't have a comment, and CI lints only changed files. So they'd fail S035 the next time someone edits their file. Run flake8 --select S035 . over the whole repo just before merging; flake8 also lints paths outside src/sentry, such as .agents/. This has already happened: four Supabase primary-key lookups and a new get_seer_run() in seer/autofix/pr_iteration/run_markers.py landed after the noqa PRs. This PR converts the Supabase calls to get_or_none() (all four filter on the primary key) and marks get_seer_run() with # noqa: S035, since its unique field is nullable.

Refs ISWF-3679

@linear-code

linear-code Bot commented Nov 12, 2026

Copy link
Copy Markdown

ISWF-3679

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 12, 2026
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch from 4a7a022 to 9ebbcdf Compare November 12, 2026 19:49
@leeandher
leeandher changed the base branch from master to leanderrodrigues/iswf-3679-noqa-product November 12, 2026 19:50
@leeandher
leeandher added this pull request to stack #130976 November 12, 2026 19:50
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch from 9ebbcdf to 5cbabf1 Compare November 16, 2026 20:29
@leeandher
leeandher removed this pull request from stack #130976 November 16, 2026 20:32
@leeandher
leeandher added this pull request to stack #131354 November 16, 2026 20:32
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch from 5cbabf1 to 05358bd Compare November 16, 2026 20:50
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch 2 times, most recently from 41b6388 to 632b5fb Compare November 17, 2026 17:46
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch 2 times, most recently from 1e2fde9 to 53da4be Compare November 17, 2026 18:40
@sentry

sentry Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Sentry Snapshot Testing

Name Added Removed Changed Renamed Unchanged Skipped Status
sentry-frontend
sentry-frontend
0 0 0 0 1006 0 ✅ Unchanged

⚙️ sentry-frontend Snapshot Settings

leeandher added a commit that referenced this pull request Nov 17, 2026
Master's #131321 replaced the per-file SeerRun lookup helpers in
seer/autofix/pr_iteration (emit.py, missing_permissions.py, out_of_credits.py,
pause.py) with a shared get_seer_run() in run_markers.py. Take master's side
in all five conflicts, which drops the # noqa: S035 comments on the deleted
lines. The PR stays comment-only.

New S035 violations from master are not marked here:
- run_markers.py get_seer_run() and four Supabase Integration lookups are
  handled in #131503.
- .agents/skills/verify-sentry/scripts/sentry_dev.py is exempted in #130924.

Refs ISWF-3679
@leeandher
leeandher marked this pull request as ready for review November 17, 2026 20:34
@leeandher
leeandher requested review from a team as code owners November 17, 2026 20:34
Comment thread src/AGENTS.md Resolved
Add flake8 rule S035. .first() on a queryset with no .order_by(...) makes
Django add ORDER BY pk, which can pick a slow query plan. The rule walks
the visible chain back to a manager: the last order_by() decides, and an
empty order_by() counts as unordered. Helper calls and bare variables are
not flagged since they may already be ordered. Tests and migrations are
exempt.

Refs ISWF-3679
Reword the S035 message so order_by("id") isn't read as a fix: it sends the
same query as the implicit ordering. Exempt .agents/ from S035, since its
scripts only query a local dev database, and drop the src/AGENTS.md guidance.

Refs ISWF-3679
@leeandher
leeandher force-pushed the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch from 327d8f2 to fb71c99 Compare November 18, 2026 17:41
Replace four Integration.objects.filter(id=...).first() calls with
get_or_none(). Each filters on the primary key, so at most one row matches,
and this drops the implicit ORDER BY pk that .first() adds.

Refs ISWF-3679
Address a new S035 violation that landed on master after the noqa PRs:
#131321 added get_seer_run() in seer/autofix/pr_iteration/run_markers.py with
an unordered SeerRun .first(). SeerRun.seer_run_state_id is unique but
nullable, the case the noqa PRs leave for a person to check, so mark it
instead of switching to get_or_none().

Refs ISWF-3679
@leeandher
leeandher requested review from a team as code owners November 18, 2026 17:47
@leeandher
leeandher merged commit 9e8d86e into master Nov 18, 2026
79 checks passed
@leeandher
leeandher deleted the leanderrodrigues/iswf-3679-add-some-repo-level-detector-to branch November 18, 2026 18:06
TkDodo added a commit that referenced this pull request Nov 19, 2026
#130924 added the S035 rule for `.first()` on an
unordered queryset. The existing call site in
`bin/preprod/trigger_size_status_check` was missed because the script
has no `.py` extension, so master has an S035 violation that only shows
up on PRs large enough to check every file.

This adds `# noqa: S035`, the same suppression the other existing call
sites use. No behavior change; this is a dev-only debugging script.

<!-- junior-request-attribution:start -->
via @TkDodo.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3ACUHS29QJ0%3A1795081321.318179 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/slack%3ACUHS29QJ0%3A1795081321.318179)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3ACUHS29QJ0%3A1795081321.318179/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Dominik Dorfmeister <[email protected]>
leeandher added a commit that referenced this pull request Nov 20, 2026
lint config changes should now run `prek --all-files` instead of `prek
--files` which may miss some violations that would cause failures on
future, unrelated PRs.

this happened when I added a new s035 flake8 rule in
#130924, which passed CI on
branch + master, but caused a violation in a PR with >1000 files
updated, thus requiring a separate PR
(#131763) to be merged and
unblock it

the responsibility of addressing violations should fall on the PRs that
add the rule, and only require other contributors to address the
violations they introduce
BYK added a commit that referenced this pull request Nov 20, 2026
Refs #131073

Our OpenAPI docs drift from what endpoints actually return, and nothing
catches it. This compares the responses tests get from **public**
operations with the schema drf-spectacular generates from the code:

- **S036**: the status isn't in the operation's `responses`
- **S037**: the JSON body doesn't match that status's schema

304, 429 and 5xx are exempt: a 304 only answers a conditional request,
the rate limiter can return a 429 from any endpoint, and a 5xx is a bug
rather than part of the contract. S035 is taken by
#130924.

This stands alone and doesn't touch the API guidelines work in
#131117 → #131088 →
#131135 → #131407. Findings use the same
signature (endpoint file, `EndpointClass.method`, `status:<code>`,
owner) and entry shape as that stack's `exceptions.json`, which is where
the baseline goes once the stack lands.

The pytest plugin is opt-in, with two modes. Report mode records
findings and annotates endpoints whose findings aren't baselined. Strict
mode also fails the test that got one. The schema is generated while
xdist workers start, so it always matches the code and doesn't need
node.

A new baseline tool adds a run's findings to a baseline file. It only
touches the endpoint methods that run called, and keeps reviewed
statuses.

Backend CI runs in report mode, so nothing blocks merges. CI moves to
strict mode together with the baseline.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:local%3Aweb%3A3bcd89ea85721d16b9af505e -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/local%3Aweb%3A3bcd89ea85721d16b9af505e)
[[Sentry]](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A3bcd89ea85721d16b9af505e/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants