Skip to content

chore(ci): Add a flake8 rule for usage of .first() - #123790

Closed
leeandher wants to merge 1 commit into
masterfrom
leanderrodrigues/inc-2510-flake8
Closed

leeandher wants to merge 1 commit into
masterfrom
leanderrodrigues/inc-2510-flake8

Conversation

@leeandher

Copy link
Copy Markdown
Member

Adds S025 to prevent using .first() after .filter() without an explicit .order_by().

This makes it more explicit to the dev that .first() will add ordering, and to include that if its relevant to the code, or suggest just using .get_or_none() if it was only added to avoid handling a DoesNotExist exception.

I added the script to generate the current exception list + the list itself, which uses fingerprints instead of line numbers since there are a lot of files in it and I figured it'd be annoying to raise on unrelated changes in the same file. I don't know if this is preferred to # noqa comments instead, but it avoided making changes to like 180 locations.

@leeandher
leeandher requested a review from wedamija September 8, 2026 16:15
@linear-code

linear-code Bot commented Sep 8, 2026

Copy link
Copy Markdown

INC-2510

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Sep 8, 2026
@leeandher
leeandher marked this pull request as ready for review September 8, 2026 16:23
@leeandher
leeandher requested a review from a team as a code owner September 8, 2026 16:23
Comment thread tools/flake8_plugin.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c830560. Configure here.

Comment thread tools/flake8_plugin.py Resolved

@vaind vaind left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I like the rule itself. The part I'd rethink is how we grandfather the existing call sites. I ran this branch's plugin over a fresh sentry and getsentry checkout, and a few things fall out:

1. It'll break other people's PRs. CI only lints changed files, so nothing shows up here, but there are ~137 .filter().first() calls in sentry tests/ and ~215 in getsentry (getsentry uses this plugin via paths = ../sentry) that aren't in the exception list. Each of those will fail lint the next time someone touches the file for an unrelated reason. Six more landed in src/sentry on master in the ~16 hours since the list was last regenerated, so it's already out of date.

2. The exception file can't work for getsentry. It lives in sentry, and the docstring says not to add to it, so getsentry has no way to opt out its own code.

So my ask: swap the fingerprint list for noqa comments, decide explicitly what to do with tests/ (probably just tests/*: S025 in setup.cfg), land a getsentry prep PR before this merges, and widen the chain match if you're up for it.

Comment thread tools/flake8_plugin.py Outdated
return False


def _is_filter_first_chain(node: ast.Call) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only matches .first() sitting right after .filter(). Anything in between (select_related, values, values_list, only) or .exclude(...).first() isn't caught, and Django still adds ORDER BY id in all of those. Walking up the chain (like _has_order_by_in_chain already does) and flagging any .first() that never hits order_by would catch a lot more with no extra machinery.

One small edge: .order_by() with no args clears ordering, so .order_by().filter().first() would be suppressed here but still gets the pk sort.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wonder if we should write this as part of the manager instead of as a lint rule. Django can just inspect itself, and we can raise an exception during tests etc. I guess the downside of that is that if there's no test for the given path it can slip through.

Comment thread tools/flake8_plugin.py Outdated
from datetime import datetime, timezone
from typing import Any

from tools.flake8_helpers.s025_exceptions import S025_EXCEPTIONS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

getsentry loads this plugin straight from the sentry checkout (paths = ../sentry in its setup.cfg), so S025 goes live there the moment sentry is bumped. There are ~215 .filter().first() calls in getsentry with no exceptions, so we'd want a getsentry PR (noqa comments, or a per-file-ignore) landed first.

Comment thread tools/flake8_helpers/s025_exceptions.py Outdated
filter on an exempt statement changes its fingerprint, so it must be reviewed
and re-added (or the statement fixed) before S025 stops flagging it.

DO NOT ADD NEW ENTRIES TO THIS LIST.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two things worry me about this list:

  • It only grows. When someone fixes or deletes one of these call sites, nothing tells them to remove the entry (S024 has a stale-safelist check for exactly this).
  • Running the regenerate script adds every violation that exists at that moment, so "do not add new entries" isn't really enforceable. Master already has 6 new ones since this was last generated.

Also the fingerprint is a hash of the expression, not a location, so copy-pasting an exempt line elsewhere in the same file is silently exempt too (8 fingerprints already match across multiple files).

# noqa: S025 on each line sidesteps all of this and works in getsentry too.

REPO_ROOT = Path(__file__).resolve().parent.parent.parent
SRC_DIR = REPO_ROOT / "src" / "sentry"
EXCEPTIONS_FILE = Path(__file__).resolve().parent / "s025_exceptions.py"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only scans src/sentry, but tests/* isn't ignoring S025 in setup.cfg, so there are ~137 test call sites that'll start failing lint one file at a time as people touch them. Probably easiest to add tests/*: S025 to the per-file-ignores and skip scanning tests entirely.

Comment thread tools/flake8_helpers/s025_exceptions.py Outdated
DO NOT ADD NEW ENTRIES TO THIS LIST.
"""

S025_EXCEPTIONS: frozenset[tuple[str, str]] = frozenset(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tbh, I'd encourage us to swap out all the uses of first for get_or_none instead of keeping this allowlist. Probably we could just have an agent churn over this and break them into prs of 100-200 line changes that are easy to review.

That'd also save us the hassle of getting the allowlist to work in getsentry

Comment thread tools/flake8_plugin.py Outdated
return False


def _is_filter_first_chain(node: ast.Call) -> bool:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wonder if we should write this as part of the manager instead of as a lint rule. Django can just inspect itself, and we can raise an exception during tests etc. I guess the downside of that is that if there's no test for the given path it can slip through.

@leeandher
leeandher marked this pull request as draft September 11, 2026 15:14
@leeandher
leeandher force-pushed the leanderrodrigues/inc-2510-flake8 branch from 8fdecda to 4e8348e Compare September 11, 2026 15:15
@getsantry

getsantry Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

This issue has gone three weeks without activity. In another week, I will close it.

But! If you comment or otherwise update it, I will reset the clock, and if you remove the label Waiting for: Community, I will leave it alone ... forever!


"A weed is but an unloved flower." ― Ella Wheeler Wilcox 🥀

@getsantry getsantry Bot added the Stale label Oct 3, 2026
@getsantry getsantry Bot closed this Oct 10, 2026
leeandher added a commit that referenced this pull request Nov 18, 2026
…0924)

Final PR for the new lint rule, this will be merged last in this stack
ofc, but also after getsentry/getsentry#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.


<details>
<summary><b>AI Commentary</b></summary>

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 #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.

</details>

Refs ISWF-3679
@leeandher
leeandher deleted the leanderrodrigues/inc-2510-flake8 branch November 18, 2026 18:16
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 Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants