Skip to content

ref(typing)!: enforce strict mypy across Sentry's Python codebase (types only) - #129614

Merged
joshuarli merged 3 commits into
masterfrom
josh/typing-strict-types-only
Nov 3, 2026
Merged

joshuarli merged 3 commits into
masterfrom
josh/typing-strict-types-only

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

This is the types-only version of #129447. It turns on strict = true for the whole codebase and empties the mypy weaklist. It keeps today's master runtime behavior. The behavior fixes that were folded into #129447 come back as separate PRs stacked on this branch.

Changes from #129447

  • strict = true with warn_return_any = false. The no-any-return errors were most of the work, and fixing them added return cast(...) calls, isinstance/raise TypeError guards, and # justification: comments. Those are gone.
  • Where strict types and master behavior conflict, master behavior stays and the types give way: a cast, an Any, or a scoped # type: ignore[...]. Examples:
  • get_mapping, post_mapping and get_sequence in shared_integrations/client/base.py are pure casts. They no longer raise ApiError when a response has an unexpected shape.
  • Bounded*Field are bare subclasses again, with # type: ignore[type-arg] on 7 class lines. The [int | None, int | None] subscripts are gone from call sites. These fields type-check as Any, as they do on master.
  • These are removed and can come back as separate PRs if we still want them: check_typing_campaign.py with its hook and tests, the weaklist sort tooling, the .github/workflows/pre-commit.yml rewrite, and the inviteStatus nullability change in static/app/types/organization.tsx.
  • I tried allow_redefinition = true. Under mypy 2.1 it adds about 150 errors in existing code, so it's off and the variable renames stay.

Rebased on master (e39c07b6). Conflicts were resolved in master's favor, with types added on top. Master code added since the old base needed a few more stub entries in fixtures/stubs-for-mypy (PGAccessExclusive/PGLock, two selenium exceptions, WebDriverWait.until accepting Literal[False]) and annotations on a handful of new tests.

Deliberately left in

  • About 95 assert x is not None lines for type narrowing. I haven't checked each one against master behavior.
  • UNBOUNDED_DATETIME = cast("datetime", None) in tests/snuba/search/test_backend.py. Widening snuba_search to datetime | None spreads into run_eap_group_search and _prepare_params_for_categories.

Stack (all based on this branch, land after it):

#129433 isn't restacked. Master's owned_by_acting_user() already returns Q(pk__in=[]) for anonymous users, so those queries are skipped there.

No getsentry change needed. getsentry's backend typing flagged 7 errors against an earlier push of this branch. Each one was a Sentry signature this PR had made narrower than master's contract, so they're fixed here, not in getsentry:

  • BaseApiClient.request/get/get_cached/post/put/patch/delete/head_cached return Any again, as on master. The get_mapping/get_sequence helpers keep their typed returns.
  • OAuth2Provider.get_oauth_client_id() returns Any. getsentry overrides it with an option typed str | int.
  • AbstractFile.getfile() returns Any. getsentry's uploader treats it as a BufferedIOBase.
  • BidirectionalMapping is generic in its values (BidirectionalMapping[KT, VT]), so lookups infer str instead of object.
  • BitField subclasses BigIntegerField[Any, Any], so subscription.flags.<name> resolves the way it does on master.

The BitField fix also restores two master behaviors the earlier push had changed: plain string flags are added to labels again, and _arg_flags holds the normalized flag list again, which is what deconstruct() writes into migrations.

getsentry/getsentry#22868 is no longer needed for this PR.

Verification

  • mypy (full repo, strict): Success: no issues found in 8527 source files, on this branch and on this branch with all 10 stacked PRs applied.
  • ruff check / ruff format --check on the changed Python files, plus ruff --select F821,F401 across src and tests.
  • getsentry master's mypy run against this branch reports the same 9 errors it reports against Sentry master: 6 are local-checkout gaps (scripts.* and devlocal modules missing in my sandbox) and 3 are already in getsentry/jobs/migrate_legacy_seer.py. None come from this PR.
  • I did not run pytest locally because there's no Postgres or Redis in my sandbox. CI is the test signal.

Supersedes #129447 (fork branch, so I couldn't push to it).

via @joshuarli.

--

View Session [Sentry]

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 3, 2026
@sentry-junior
sentry-junior Bot force-pushed the josh/typing-strict-types-only branch from 82096e2 to 9fda5d0 Compare November 3, 2026 00:12
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

decision-model-linter

api

src/sentry/core/endpoints/project_details.py

  • warn readsRequestBodyOutsideSerializer = TRUE (0.84): Request body values should be read from a serializer's validated_data. This file reads a value directly from request.data or request.POST.

src/sentry/integrations/gitlab/webhooks.py

  • warn readsWebhookPayloadOutsideSerializer = TRUE (0.71): Third-party webhook payloads should be validated with a serializer or typed schema before their fields are read. This file reads fields directly from the incoming payload.

src/sentry/integrations/msteams/webhook.py

  • warn readsWebhookPayloadOutsideSerializer = TRUE (0.81): Third-party webhook payloads should be validated with a serializer or typed schema before their fields are read. This file reads fields directly from the incoming payload.

src/sentry/integrations/slack/requests/event.py

  • warn readsWebhookPayloadOutsideSerializer = TRUE (0.84): Third-party webhook payloads should be validated with a serializer or typed schema before their fields are read. This file reads fields directly from the incoming payload.

src/sentry/preprod/api/endpoints/project_preprod_artifact_assemble_generic.py

  • warn readsRequestBodyOutsideSerializer = TRUE (0.73): Request body values should be read from a serializer's validated_data. This file reads a value directly from request.data or request.POST.

src/sentry/releases/endpoints/project_release_files.py

  • warn readsRequestBodyOutsideSerializer = TRUE (0.88): Request body values should be read from a serializer's validated_data. This file reads a value directly from request.data or request.POST.

audit

src/sentry/web/frontend/setup_wizard.py

  • warn issuesOrRevokesTokenWithoutRecord = TRUE (0.75): Token changes should be logged with create_audit_entry for org tokens or capture_security_activity for personal tokens. This file creates, revokes, or rescopes a token, but neither call was found in it. Ignore this if a function the file calls already logs the change.

decision-model-linter: 3420 calls on 1213 files, 7,315,688 input tokens, $0.31, model typesafe/jev-1.13-20260917


try:
# grab the filter out of the brackets of the string that looks
# like so: members[value eq "123124"]
regex_search = re.search(r"\[(.*?)\]", operation["path"])
regex_search = re.search(r"\[(.*?)\]", cast(str, operation["path"]))
Turn on `strict = true` for the whole codebase and empty the mypy
weaklist. This change is types only and keeps master's runtime
behavior. Behavior fixes land as separate PRs on top.

- `strict = true` with `warn_return_any = false`. There are no
  `return cast(...)` calls or runtime guards that exist only to satisfy
  `no-any-return`.
- Where strict typing and master behavior conflict, master wins: use a
  cast, `Any`, or a scoped `# type: ignore[...]`, for example the
  paginator `order_b` typo that #127799 fixes.
- The `get_mapping`/`post_mapping`/`get_sequence` client helpers are
  pure casts and never raise for an unexpected shape.
- `Bounded*Field` stay bare subclasses (`# type: ignore[type-arg]`), so
  call sites don't need `[int | None, int | None]` subscripts.

Co-Authored-By: Joshua Li <[email protected]>
@sentry-junior
sentry-junior Bot force-pushed the josh/typing-strict-types-only branch from 9fda5d0 to 73fa505 Compare November 3, 2026 00:31
@sentry-junior
sentry-junior Bot marked this pull request as ready for review November 3, 2026 00:39
@sentry-junior
sentry-junior Bot requested review from a team as code owners November 3, 2026 00:39
@cursor

cursor Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

This PR is too large for Bugbot to review. It changes 24,218 lines and 3,674,192 characters. Split the change into smaller pull requests to get a review.

@sentry-junior
sentry-junior Bot requested review from a team as code owners November 3, 2026 00:39
@sentry-junior
sentry-junior Bot requested a review from a team as a code owner November 3, 2026 00:40
@sentry-junior
sentry-junior Bot requested review from msonnb and stephanie-anderson and removed request for a team November 3, 2026 00:40
@joshuarli
joshuarli marked this pull request as draft November 3, 2026 02:16
@joshuarli
joshuarli requested a review from armenzg November 3, 2026 02:17
@joshuarli
joshuarli marked this pull request as ready for review November 3, 2026 02:17

@armenzg armenzg left a comment

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.

Bravo!

# Conflicts:
#	src/sentry/integrations/gitlab/client.py
#	src/sentry/integrations/gitlab/tasks.py
#	tests/sentry/integrations/gitlab/tasks/test_update_all_project_webhooks.py
#	tests/sentry/issue_detection/test_utils.py
@joshuarli
joshuarli merged commit ae29b66 into master Nov 3, 2026
96 of 99 checks passed
@joshuarli
joshuarli deleted the josh/typing-strict-types-only branch November 3, 2026 14:41
jamieQ added a commit that referenced this pull request Nov 3, 2026
Retain upstream strict typing from #129614 alongside the five dead-code
removals. Resolve the overlapping imports and keep the orphaned grouping
helper deleted.
joshuarli added a commit that referenced this pull request Nov 3, 2026
`backend typing` is red on master. It first failed on 56e837a
(#129330), but that commit isn't the cause.

The cause is #129322, which added six unannotated test methods to
`test_organization_pull_request_files.py`. It merged after strict mypy
was turned on in #129614, so the two PRs raced and CI started reporting
`no-untyped-def` on master.

This adds `MagicMock` / `-> None` annotations to those methods, the same
way the rest of the file already does it. Only type hints change. Test
behavior stays the same.

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

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AD0BQC9WSQ2E%3A1793720276.363209 -->

--

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

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

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Joshua Li <[email protected]>
joshuarli added a commit that referenced this pull request Nov 3, 2026
EmptyDecimalField and EmptyIntegerField both convert a blank string to
None in run_validation, which DRF calls before to_internal_value. The
blank check in their to_internal_value overrides could not be reached
through DRF, but #129614 typed it by casting None to Decimal and int, so
both overrides claimed a non-null result while holding a None branch.

Dropping the overrides leaves run_validation (typed `Decimal | None` /
`int | None`) as the only blank path, and to_internal_value inherits
DRF's honest `Decimal` / `int` contract. MissedMarginField now uses that
contract instead of `Any -> Any`.

New tests pin the blank-to-None behavior that project resolveAge,
monitor fields and getsentry promo codes depend on.
joshuarli added a commit that referenced this pull request Nov 3, 2026
EmptyDecimalField and EmptyIntegerField both convert a blank string to
None in run_validation, which DRF calls before to_internal_value. The
blank check in their to_internal_value overrides could not be reached
through DRF, but #129614 typed it by casting None to Decimal and int, so
both overrides claimed a non-null result while holding a None branch.

Dropping the overrides leaves run_validation (typed `Decimal | None` /
`int | None`) as the only blank path, and to_internal_value inherits
DRF's honest `Decimal` / `int` contract. MissedMarginField now uses that
contract instead of `Any -> Any`.
billyvg added a commit that referenced this pull request Nov 3, 2026
Resolve conflicts with strict mypy (#129614) and the idempotency
declaration requirement (#129238):

- hooks.py: keep master's types on the shared hooks alongside the
  internal build's keyword parameters. Require idempotent_methods only
  for published methods, so the internal build, which admits every
  method, doesn't fail on private endpoints.
- spectacular_ports.py: keep both import sets and the wider Mapping
  match. Drop Sequence from the iterable case, which master's list
  case now handles first.

Type the internal build's untyped drf-spectacular calls as master does
in CustomGenerator, and declare PUT idempotent on the test endpoint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gricha added a commit that referenced this pull request Nov 3, 2026
#129614 annotated helpers that endpoints pass request.user to. Once
request.user includes ServiceAccountPrincipal, those call sites need
the helpers to take a RequestPrincipal:

- SnubaTSResultSerializer and the TimeSeriesLookup protocol, which only
  forward the caller (and no lookup is implemented in sentry).
- get_homepage_query, which only builds owned_by_acting_user().
- Project.objects.get_for_user, which checks is_authenticated and passes
  the caller to Team.objects.get_for_user (already a RequestPrincipal).
- ApiTokenSerializer, which only forwards the caller to serialize().

primary_email_verification_required now reads the email check off the
user from require_user() instead of request.user. Type-only for users,
agents and token callers.
gricha added a commit that referenced this pull request Nov 3, 2026
#129614 added annotations to helpers that endpoints pass `request.user`
to. Once #129402 types `request.user` to include service accounts, those
call sites no longer type-check, so the helpers now take a
`RequestPrincipal`:

- `SnubaTSResultSerializer` and the `TimeSeriesLookup` protocol only
forward the caller. Sentry has no lookup implementation.
- `get_homepage_query` only builds `owned_by_acting_user()`.
- `Project.objects.get_for_user` checks `is_authenticated` and passes
the caller on to `Team.objects.get_for_user`, which already takes a
`RequestPrincipal`.
- `ApiTokenSerializer` only forwards the caller.

`primary_email_verification_required` now passes the user from
`require_user()` to `PrimaryEmailVerificationRequired` instead of
`request.user`.

No behavior change.
jamieQ added a commit that referenced this pull request Nov 4, 2026
… test (#129854)

Master's `backend typing` job is red. The cause is
`test_create_repositories__scopes_lookups_to_external_ids`, which passes
an `Organization` to
`IntegrationRepositoryProvider.create_repositories`, but that method
takes an `RpcOrganization`:

```
tests/sentry/plugins/test_integration_repository.py:340: error: Argument 2 to "create_repositories" of "IntegrationRepositoryProvider" has incompatible type "Organization"; expected "RpcOrganization"  [arg-type]
```

This is a semantic merge conflict. The test came in with #129473, whose
typing check ran before strict mypy was enabled in #129614. This PR
passes `self.rpc_organization` instead, the same way the other
`create_repositories` tests in this file already do.

The red typing check is also failing `checks` on the getsentry-backend
deploy pipelines, so they are blocked until this lands.

<!-- junior-request-attribution:start -->
via **jamieq**.
<!-- junior-request-attribution:end -->

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

--

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

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

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Jamie Quadri <[email protected]>
gi0baro added a commit that referenced this pull request Nov 4, 2026
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