Repository navigation
ref(typing)!: enforce strict mypy across Sentry's Python codebase (types only) - #129614
Merged
Merged
Conversation
sentry-junior
Bot
force-pushed
the
josh/typing-strict-types-only
branch
from
November 3, 2026 00:12
82096e2 to
9fda5d0
Compare
Contributor
decision-model-linterapi
audit
decision-model-linter: 3420 calls on 1213 files, 7,315,688 input tokens, $0.31, model typesafe/jev-1.13-20260917 |
This was referenced Nov 3, 2026
|
|
||
| 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
Bot
force-pushed
the
josh/typing-strict-types-only
branch
from
November 3, 2026 00:31
9fda5d0 to
73fa505
Compare
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
Bot
requested review from
msonnb and
stephanie-anderson
and removed request for
a team
November 3, 2026 00:40
joshuarli
marked this pull request as draft
November 3, 2026 02:16
joshuarli
marked this pull request as ready for review
November 3, 2026 02:17
joshuarli
approved these changes
Nov 3, 2026
# 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
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
SSIA Cleanup #129614 `apigw` parts.
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.
This is the types-only version of #129447. It turns on
strict = truefor 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 = truewithwarn_return_any = false. Theno-any-returnerrors were most of the work, and fixing them addedreturn cast(...)calls,isinstance/raise TypeErrorguards, and# justification:comments. Those are gone.cast, anAny, or a scoped# type: ignore[...]. Examples:order_btypo is still there behind# type: ignore[attr-defined]. fix(api): Reverse previous-page ordering for descending paginators #129615 fixes it.or 0, coercions withstr()/int()/bool(), defensive copies that changed in-place mutation, and serializer output are back to master.get_mapping,post_mappingandget_sequenceinshared_integrations/client/base.pyare pure casts. They no longer raiseApiErrorwhen a response has an unexpected shape.Bounded*Fieldare 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 asAny, as they do on master.check_typing_campaign.pywith its hook and tests, the weaklist sort tooling, the.github/workflows/pre-commit.ymlrewrite, and theinviteStatusnullability change instatic/app/types/organization.tsx.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 infixtures/stubs-for-mypy(PGAccessExclusive/PGLock, two selenium exceptions,WebDriverWait.untilacceptingLiteral[False]) and annotations on a handful of new tests.Deliberately left in
assert x is not Nonelines for type narrowing. I haven't checked each one against master behavior.UNBOUNDED_DATETIME = cast("datetime", None)intests/snuba/search/test_backend.py. Wideningsnuba_searchtodatetime | Nonespreads intorun_eap_group_searchand_prepare_params_for_categories.Stack (all based on this branch, land after it):
order_bytypo (was fix(api): Reverse previous-page ordering for descending paginators #127799)#129433 isn't restacked. Master's
owned_by_acting_user()already returnsQ(pk__in=[])for anonymous users, so those queries are skipped there.No getsentry change needed. getsentry's
backend typingflagged 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_cachedreturnAnyagain, as on master. Theget_mapping/get_sequencehelpers keep their typed returns.OAuth2Provider.get_oauth_client_id()returnsAny. getsentry overrides it with an option typedstr | int.AbstractFile.getfile()returnsAny. getsentry's uploader treats it as aBufferedIOBase.BidirectionalMappingis generic in its values (BidirectionalMapping[KT, VT]), so lookups inferstrinstead ofobject.BitFieldsubclassesBigIntegerField[Any, Any], sosubscription.flags.<name>resolves the way it does on master.The
BitFieldfix also restores two master behaviors the earlier push had changed: plain string flags are added tolabelsagain, and_arg_flagsholds the normalized flag list again, which is whatdeconstruct()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 --checkon the changed Python files, plusruff --select F821,F401acrosssrcandtests.scripts.*anddevlocalmodules missing in my sandbox) and 3 are already ingetsentry/jobs/migrate_legacy_seer.py. None come from this PR.Supersedes #129447 (fork branch, so I couldn't push to it).
via @joshuarli.
--
View Session [Sentry]