Skip to content

Don't record GeneratorExit as an error when a generator is closed early - #2785

Merged
alexmojaki merged 2 commits into
pydantic:mainfrom
astroknot-sheep:fix/generator-exit-not-error
Nov 12, 2026
Merged

alexmojaki merged 2 commits into
pydantic:mainfrom
astroknot-sheep:fix/generator-exit-not-error

Conversation

@astroknot-sheep

@astroknot-sheep astroknot-sheep commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

When a generator that has a span open (either with logfire.span(...) inside it, or @logfire.instrument(allow_generator=True)) is closed before it finishes, for example the caller does break, or a streaming response's client disconnects, Python throws GeneratorExit into it. Right now the span records that as an exception and gets ERROR status, so a normal early stop shows up as a failed span.

OpenTelemetry's use_span only records Exception subclasses for this exact reason (open-telemetry/opentelemetry-python#4484). This change skips GeneratorExit in LogfireSpan.__exit__ and in the wrapped SDK span's __exit__. Other BaseExceptions like KeyboardInterrupt are still recorded.

Repro:

def stream():
    with logfire.span('streaming'):
        yield 1
        yield 2

for x in stream():
    break  # span ends with status ERROR and an 'exception' event

Tests: added test_generator_closed_early_is_not_an_error (instrumented and manual span), and updated the GeneratorExit + propagate case of test_instrument_asynccontextmanager_exception to expect UNSET. tests/test_logfire.py and tests/test_metrics.py pass locally.

I used an AI assistant while working on this; I reproduced the issue, reviewed the change and ran the tests myself.

View guided diff

@veria-ai

veria-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

PR overview

No security issues were found in this pull request.

Reviews

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

View guided diff | Re-trigger cubic

@github-actions

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  logfire-sdk/logfire/_internal
  main.py
  tracer.py
Project Total  

This report was generated by python-coverage-comment-action

@alexmojaki
alexmojaki added this pull request to the merge queue Nov 12, 2026
Merged via the queue into pydantic:main with commit daf3683 Nov 12, 2026
30 checks passed
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.

2 participants