← Back to Pull requests

fix(ci_visibility): run each pytest retry on a new test class instance #22105

Closed
unknown closed this pull request without merging on Nov 26, 2026 09:26 UTC
View on GitHub
unknown unknown commented on Nov 25, 2026 19:41 UTC
Author

Description

Early Flake Detection, Auto Test Retries, Attempt to Fix and the out-of-session retry run a test again by calling runtestprotocol() on the same pytest item. Since pytest 7 an item creates its test class instance once and keeps it, in item._instance from pytest 8.2 and in item._obj, the test method bound to it. runtestprotocol() only resets the fixture request when an item runs again, so every attempt ran on the first attempt's self and saw whatever earlier attempts left there.

SQLAlchemy's test suite shows what that breaks. Its RemovesEvents fixture keeps the listeners a test adds in a set it creates on self the first time, and removes them all after each test without clearing the set. On the reused instance a retry removes the first attempt's listener a second time and fails its teardown with InvalidRequestError: No listeners found for event. Depending on the set's iteration order, the retry's own listener can stay registered, and it then breaks the rest of the class: against PostgreSQL 16, 28 later tests of SessionTransactionTest failed with Can't roll back to savepoint, which is the error that leftover listener raises, and a leftover column_reflect listener renamed columns for the reflection tests that ran after ColumnEventsTest.

Before an item runs again, this PR makes a new instance with the class's newinstance(), the call pytest makes for every test. If item.obj is a method bound to an instance of exactly that class, the method's own function is bound to the new instance, so an item keeps a method its collector gave it under another name, and item._instance, which the fixtures use, is updated where pytest has it. If item.obj is still the class's own staticmethod or classmethod, only item._instance changes. Instances are compared with type(), which no metaclass can change; instances of a subclass are left alone on purpose.

This happens in _do_one_test_run(), right before runtestprotocol(), and only when pytest's own re-run signal is set: runtestprotocol() leaves item._request falsy after a run and checks it the same way. Every retry handler and the out-of-session rerun go through that call, and it comes after anything that puts the test method back before an attempt. #21860 restores the test function at the top of _do_one_test_run(), so with both changes the method it restores gets the new instance, and either PR can land first.

Everything else runs as before: an item.obj that isn't a method of an instance of exactly the class (a collector's plain function, a subclass's method, a wrapper a plugin left there), unittest items, which already get a new TestCase on each run, and pytest 6, which makes a new instance in every setup. If the class can't make an instance of itself, including when its constructor calls pytest.skip() or pytest.fail(), the error is logged at debug level and the attempt runs on the current instance, with the method bound to the instance the fixtures use. KeyboardInterrupt, SystemExit, GeneratorExit and pytest.exit() propagate.

pytest-rerunfailures fixed the same problem for its reruns in 16.5 (pytest-dev/pytest-rerunfailures PR 268) by dropping the item's _instance and _obj, so that pytest looks the method up again by the item's name. That breaks an item whose collector gave it a method under another name, and on pytest 7.0 to 8.1, which have no _instance, the instance stays.

Customer impact

Retries of tests in pytest classes no longer see state from earlier attempts. Suites whose fixtures keep per-test state on self stop failing retries that should pass, and stop failing the class's other tests after a retry. The release note covers it.

Testing

tests/testing/internal/pytest/test_pytest_retry_class_instance.py adds 21 tests. Each checks that an attempt's body, its fixtures and its setup_method see one instance that no earlier attempt touched, or that an item the fix leaves alone keeps working:

  • SQLAlchemy's pattern in an xunit-style class with setup_class, with the listeners kept on self or in a dictionary keyed by the instance: a new test gets 10 EFD retries, then a known test of the same class checks that no listener was left behind and that setup_class ran once.

  • EFD, ATR with a failing first attempt, ATR exhausted followed by the out-of-session retry, and a unittest.TestCase under EFD: each attempt's setup finds no earlier state, and the body runs on the instance its setup prepared.

  • Items a collector gives their own test function: a plain function, a method of the class under another name, or a subclass's method.

  • __slots__ in the test class and in a base, a function-scoped fixture that sets an attribute on request.instance, the fixtures of staticmethod and classmethod tests, and a metaclass that sets the instance up.

  • A wrapper a plugin left in item.obj of a method, staticmethod or classmethod test, which keeps its instance (a direct call of the helper on a real item), and a classmethod test under a metaclass whose __instancecheck__ takes the class for an instance, which keeps its class.

  • A class that can't make a new instance, with an exception and with pytest.skip(): all 11 attempts still run, and the test method stays bound to the instance the fixtures use.
  • What ran, on macOS arm64 with main's CI wheels for this branch's base and the change applied, outside riot:

  • The new tests: on pytest 8.4.2 and 9.2.0 all 21 pass with the change, and 14 fail without it; on 7.4.4 and 8.1.2, 19 pass and 2 are skipped (they need pytest 8.2), and 12 fail without the change. The 7 that pass without it are the unittest, plain-function, subclass-method, fixture and metaclass-classmethod cases and the two failing-class cases, which check behavior the fix must keep. On pytest 6.2.5 (Python 3.9), 10 pass and 11 are skipped with or without the change.

  • The whole tests/testing/ suite, with the change: pytest 9.2.0, 1,644 passed and 15 skipped; 8.4.2, 1,645 passed and 14 skipped; 8.1.2 and 7.4.4, 1,643 passed and 16 skipped. On pytest 6.2.5, 145 tests fail with and without the change in my environment, where inner runs can't parse --ddtrace.

  • scripts/lint checks, scripts/lint typing, scripts/lint suitespec-check and scripts/lint type-comments-check pass.

  • sqlalchemy at 57ddc05 against PostgreSQL 16, test/orm/test_transaction.py and test/engine/test_reflection.py, with EFD and ATR forced on through a local settings cache: on main, three runs failed 36, 8 and 36 first attempts, each after a failed retry in the same file; with this change, 361 tests pass and 2 skip, the same as without the plugin.

  • #21860, merged locally into main with this branch, in both orders: both give the same tree, without conflicts. There all 27 tests of the two PRs pass on pytest 9.2.0, 25 pass and 2 are skipped on 7.4.4 and 8.1.2, the tests/testing/ suite passes on 9.2.0, and the sqlalchemy run above passes too.
  • What didn't run: dd-trace-py's CI and riot environments, Linux and x86_64 for the unit tests (the sqlalchemy run was on Linux aarch64), Python versions other than 3.9 and 3.12, and the internal multi-node run where the failures were first seen.

    Risks

    A retry doesn't see attributes a plugin set on the first instance before the first attempt; neither does a new test, nor do pytest 6 and pytest-rerunfailures' reruns. Without #21860, a class test whose item.obj a plugin replaces on every call keeps reusing its instance, as on main. The change reads pytest's private item._obj, item._instance and item._request (the last one the way runtestprotocol() itself reads it) and imports TestCaseFunction from _pytest.unittest. In a microbenchmark it adds about 0.7 microseconds per retry.

    Additional Notes

    #21860 needs no change for the two to work together: it restores the test method at the top of _do_one_test_run(), and this PR binds the method it restored to a new instance a few lines later.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: gnufede Review duration: 824m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #22105"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%