Repository navigation
feat(lint): Flag .first() on querysets with no explicit ordering - #130924
Merged
Conversation
leeandher
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
from
November 12, 2026 19:49
4a7a022 to
9ebbcdf
Compare
leeandher
changed the base branch from
master
to
leanderrodrigues/iswf-3679-noqa-product
November 12, 2026 19:50
This was referenced Nov 12, 2026
leeandher
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
from
November 16, 2026 20:29
9ebbcdf to
5cbabf1
Compare
leeandher
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
from
November 16, 2026 20:50
5cbabf1 to
05358bd
Compare
leeandher
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
2 times, most recently
from
November 17, 2026 17:46
41b6388 to
632b5fb
Compare
leeandher
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
2 times, most recently
from
November 17, 2026 18:40
1e2fde9 to
53da4be
Compare
Contributor
Sentry Snapshot Testing
|
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
marked this pull request as ready for review
November 17, 2026 20:34
malwilley
reviewed
Nov 17, 2026
wedamija
approved these changes
Nov 17, 2026
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
force-pushed
the
leanderrodrigues/iswf-3679-add-some-repo-level-detector-to
branch
from
November 18, 2026 17:41
327d8f2 to
fb71c99
Compare
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
malwilley
approved these changes
Nov 18, 2026
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]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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:
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
DoesNotExistexceptions and getNoneinstead, butget_or_noneis more explicit about thisORDER BY pkto the query, and on the wrong table without an index this can break things, like the whole db for exampleAI 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 addORDER 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 orNone", which.get_or_none()says directly without adding the ordering.What the rule flags.
.first()through known QuerySet methods (filter,exclude,select_related,values_list,select_for_update, …) to a manager:Model.objectsor a reverse*_setmanager.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..firstline, so in a multi-line chain# noqa: S035goes on that line.What it deliberately doesn't flag, and why.
get_queryset().first()orRelease.objects.filter_by_semver(v).first(). These often order the queryset themselves, and a single-file lint can't see inside them.qs.first(). Nothing in the expression shows it's a queryset, or that it isn't already ordered.testutils/is exempt for the same reason..agents/. Agent skill scripts only query a local dev database. It's exempted insetup.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) andafirst().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 anorder_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. Flaggingid/pkorderings could be a later tightening, butorder_by("-id").first()is sometimes a real "latest row" lookup, so that has its own cost.Rollout.
.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.paths = ../sentry), so its existing call sites must be marked before its sentry pin picks up the rule.flake8 --select S035 .over the whole repo just before merging; flake8 also lints paths outsidesrc/sentry, such as.agents/. This has already happened: four Supabase primary-key lookups and a newget_seer_run()inseer/autofix/pr_iteration/run_markers.pylanded after the noqa PRs. This PR converts the Supabase calls toget_or_none()(all four filter on the primary key) and marksget_seer_run()with# noqa: S035, since its unique field is nullable.Refs ISWF-3679