Skip to content

ci(mypy): Enable warn_unreachable - #8293

Draft
sentry-junior[bot] wants to merge 1 commit into
masterfrom
ci/mypy-warn-unreachable
Draft

sentry-junior[bot] wants to merge 1 commit into
masterfrom
ci/mypy-warn-unreachable

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Description

Turns on mypy's warn_unreachable. It flags code that mypy proves can never run given the annotations, for example a branch behind an isinstance check that can't match. Two things come out of that: dead code, and annotations that are narrower than what the code really gets at runtime. It found 92 errors in sentry_sdk. They were fixed like this:

  • Annotation fixes. Where the annotation was wrong, it now matches what the code gets at runtime:
    • capture_internal_exceptions() now returns CaptureInternalException, whose __exit__ returns bool. Before, it was typed as a plain ContextManager, so mypy assumed exceptions always propagate past the with block. As a result, it treated the code after the block as unreachable, or didn't see paths that fall through.
    • Optional or union spans in sqlalchemy, langgraph, and the rust_tracing on_close/on_record callbacks.
    • str | bytes headers in aiohttp, str messages in openai, Optional _messages in anthropic, list[Any] prompt messages in mcp (this also removes two old ignores), an Optional debug dict in Django templates, the otel instrumentor map, and the Flask request, which is a Request and not a callable.
  • Equivalent restructure. close_async()/flush_async() check isinstance(self.transport, AsyncHttpTransport) directly instead of _has_async_transport(), so mypy narrows the transport. This removes two blanket # type: ignores.
  • Targeted # type: ignore[unreachable]. Most findings are defensive checks where runtime values are wider than the annotations: isinstance and None guards on user or third-party input (mostly the AI integrations), optional-import fallbacks, double-checked locking in _patch_drf, and enum fallbacks. These checks stay, each with a short reason.
  • Removed dead code. Only where it is dead at runtime, not just in the types:
    • The isinstance(span, StreamedSpan) check in Scope.start_span. Scope.span never returns a StreamedSpan, and the comment said the check was only there for mypy.
    • The request is None check in the Flask event processor. It was left over from when a weakref was passed in.

Bugs found

  • The legacy @sentry_sdk.trace decorator never warned in span streaming mode. fix: Introduce _get_current_streamed_span() to keep types backwards compatible #6177 changed Scope.span to return None when it holds a StreamedSpan. After that, the isinstance(current_span, StreamedSpan) branch could never match, so the decorator only logged "Cannot create a child span" at debug level. The check now uses the streamed span getter, so the intended DeprecationWarning fires again. This changes behavior a little (a warning that was supposed to be emitted now is), so please check that it's wanted.
  • The GNU backtrace event processor could drop events. If _process_gnu_backtrace raised, capture_internal_exceptions() swallowed the error and the processor returned None, which drops the event. It now returns the original event in that case.

StarletteRequestExtractor.extract_request_info() also gets an explicit return None for the same swallowed-exception path. Its callers already handled None.

Follow-up from #8281.

via @sentrivana.

--

View Session [Sentry]

Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown
Contributor

Coverage Results 📊

✅ 139283 passed | ⏭️ 7853 skipped | Total: 147136 | Pass Rate: 94.66% | Execution Time: 423m 42s

📊 Comparison with Base Branch

Metric Change
Total Tests 📈 +17
Passed Tests 📈 +17
Failed Tests —
Skipped Tests —

All tests are passing successfully.

❌ Patch coverage is 57.50% (46 of 80 changed executable lines covered; target 80%).
Project statement coverage is 90.23% (up 0.02 percentage points from base (4c1a136) to head (443d83d)).

Changed files with executable lines (27)
File Patch coverage Changed executable lines
sentry_sdk/ai/_openai_completions_api.py 0.00% 0/8 covered; missed: 29, 41, 60, 64, 81, 86, 94, 115
sentry_sdk/ai/_openai_responses_api.py 0.00% 0/5 covered; missed: 43, 47, 54, 73, 78
sentry_sdk/tracing_utils.py 62.50% 5/8 covered; missed: 88, 1089, 1094; partial branches: 1088
sentry_sdk/integrations/mcp.py 71.43% 5/7 covered; missed: 368, 598; partial branches: 623
sentry_sdk/client.py 83.33% 5/6 covered; missed: 1129; partial branches: 1128
sentry_sdk/integrations/django/templates.py 75.00% 3/4 covered; missed: 181; partial branches: 49
sentry_sdk/integrations/google_genai/utils.py 85.71% 6/7 covered; missed: 889; partial branches: 978
sentry_sdk/integrations/huggingface_hub.py 50.00% 1/2 covered; missed: 380; partial branches: 379
sentry_sdk/integrations/rust_tracing.py 33.33% 1/3 covered; missed: 73, 142
sentry_sdk/integrations/starlette.py 0.00% 0/2 covered; missed: 863, 876
sentry_sdk/ai/utils.py 87.50% 7/8 covered; missed: 686
sentry_sdk/feature_flags.py 100.00% 1/1 covered; partial branches: 44
sentry_sdk/integrations/aws_lambda.py 0.00% 0/1 covered; missed: 50
sentry_sdk/integrations/boto3/_services/bedrock.py 0.00% 0/1 covered; missed: 586
sentry_sdk/integrations/django/init.py 0.00% 0/1 covered; missed: 344
sentry_sdk/integrations/gnu_backtrace.py 0.00% 0/1 covered; missed: 38
sentry_sdk/integrations/langchain.py 0.00% 0/1 covered; missed: 1120
sentry_sdk/integrations/litellm.py 0.00% 0/1 covered; missed: 63
sentry_sdk/integrations/openai_agents/spans/ai_client.py 0.00% 0/1 covered; missed: 71
sentry_sdk/integrations/aiohttp.py 100.00% 2/2 covered
sentry_sdk/integrations/langgraph.py 100.00% 2/2 covered
sentry_sdk/integrations/openai.py 100.00% 2/2 covered
sentry_sdk/integrations/opentelemetry/integration.py 100.00% 1/1 covered
sentry_sdk/integrations/pydantic_ai/spans/utils.py 100.00% 1/1 covered
sentry_sdk/integrations/sqlalchemy.py 100.00% 1/1 covered
sentry_sdk/traces.py 100.00% 1/1 covered
sentry_sdk/utils.py 100.00% 2/2 covered
Coverage diff
@@            Coverage Diff             @@
##        master     #8293       +/-##
==========================================
+ Coverage    90.21%    90.23%    +0.02%
==========================================
  Files          203       203         —
  Tracked lines     27335     27334        -1
  Branches     10246     10242        -4
==========================================
+ Hits         24660     24664        +4
+ Misses        2675      2670        -5
+ Partials      1559      1553        -6

Generated by Coverage Action

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant