fix(ci_visibility): run each pytest retry on a new test class instance #22105
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
gnufede
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, initem._instancefrom pytest 8.2 and initem._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'sselfand saw whatever earlier attempts left there.SQLAlchemy's test suite shows what that breaks. Its
RemovesEventsfixture keeps the listeners a test adds in a set it creates onselfthe 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 withInvalidRequestError: 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 ofSessionTransactionTestfailed withCan't roll back to savepoint, which is the error that leftover listener raises, and a leftovercolumn_reflectlistener renamed columns for the reflection tests that ran afterColumnEventsTest.Before an item runs again, this PR makes a new instance with the class's
newinstance(), the call pytest makes for every test. Ifitem.objis 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, anditem._instance, which the fixtures use, is updated where pytest has it. Ifitem.objis still the class's ownstaticmethodorclassmethod, onlyitem._instancechanges. Instances are compared withtype(), which no metaclass can change; instances of a subclass are left alone on purpose.This happens in
_do_one_test_run(), right beforeruntestprotocol(), and only when pytest's own re-run signal is set:runtestprotocol()leavesitem._requestfalsy 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.objthat 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 newTestCaseon 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 callspytest.skip()orpytest.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,GeneratorExitandpytest.exit()propagate.pytest-rerunfailures fixed the same problem for its reruns in 16.5 (
pytest-dev/pytest-rerunfailuresPR 268) by dropping the item's_instanceand_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
selfstop 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.pyadds 21 tests. Each checks that an attempt's body, its fixtures and itssetup_methodsee one instance that no earlier attempt touched, or that an item the fix leaves alone keeps working:setup_class, with the listeners kept onselfor 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 thatsetup_classran once.unittest.TestCaseunder EFD: each attempt's setup finds no earlier state, and the body runs on the instance its setup prepared.__slots__in the test class and in a base, a function-scoped fixture that sets an attribute onrequest.instance, the fixtures ofstaticmethodandclassmethodtests, and a metaclass that sets the instance up.item.objof 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.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:
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-checkandscripts/lint type-comments-checkpass.test/orm/test_transaction.pyandtest/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.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.obja plugin replaces on every call keeps reusing its instance, as on main. The change reads pytest's privateitem._obj,item._instanceanditem._request(the last one the wayruntestprotocol()itself reads it) and importsTestCaseFunctionfrom_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.