Skip to content

Print the RERUNS summary from public report fields - #202412

Closed
ezyang wants to merge 2 commits into
mainfrom
ptq/20261028-pytorch-adhoc-beedc0
Closed

ezyang wants to merge 2 commits into
mainfrom
ptq/20261028-pytorch-adhoc-beedc0

Conversation

@ezyang

@ezyang ezyang commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Human Note

Claude removed the tb=line branch since it doesn't trigger in CI, and claims the teardown sections stuff never worked even on older pytest. I don't really have a bone in this fight.

Agent Report

test/conftest.py's RERUNS section (#86831) prints why each rerun attempt
failed, since pytest-rerunfailures itself only lists reruns. It did so through
four private TerminalReporter methods (_getcrashline, _getfailureheadline,
_outrep_summary, _handle_teardown_sections). pytest 9.2 changed
_handle_teardown_sections to take a NodeId, so the teardown part silently
printed nothing.

This builds the same output from public API: each rerun report's head_line,
toterminal() (onto config.get_terminal_writer()) and sections, filtered by
--show-capture like pytest's FAILURES section. With --tb=line it still
prints one crash line per attempt, now from the public
rep.longrepr.reprcrash (falling back to the start of str(longrepr), as
_getcrashline did, for a plain-string longrepr such as an xdist worker
crash's).

One part is dropped: the teardown sections. They were looked up by node id, so
they printed the teardown output of every attempt of the test (including the
one that passed) under each failed attempt.

Test plan: a flaky test that prints in call and teardown, a test that fails all
attempts, and a passing test, run with --reruns=1 under pytest 7.3.2, 9.1.1
and 9.2.0, with --tb=native and --tb=long --color=yes --showlocals. The new
RERUNS section is identical to the old one except for the dropped teardown
sections. With --tb=line (adding a setup error and a pytrace=False failure)
under 7.3.2 and 9.2.0, it prints one line per attempt, matching the old
conftest except where the two pytest versions format reprcrash differently.

cd test && PYTHONPATH=<pytest==$V overlay> python -m pytest -p no:cacheprovider zz_scratch_reruns.py --reruns=1

Authored with an AI assistant (Claude).

Agent Worklog

This PR was generated by ptq with human review.

test/conftest.py's RERUNS section (#86831) prints why each rerun attempt
failed, since pytest-rerunfailures itself only lists reruns. It did so through
four private TerminalReporter methods (`_getcrashline`, `_getfailureheadline`,
`_outrep_summary`, `_handle_teardown_sections`). pytest 9.2 changed
`_handle_teardown_sections` to take a `NodeId`, so the teardown part silently
printed nothing.

This builds the same output from public API: each rerun report's `head_line`,
`toterminal()` (onto `config.get_terminal_writer()`) and `sections`, filtered by
`--show-capture` like pytest's FAILURES section. Two parts are dropped:

- the `--tb=line` branch (one crash line per attempt): CI runs with
  `--tb=native`, or `--tb=long` with `--showlocals`;
- the teardown sections: they were looked up by node id, so they printed the
  teardown output of every attempt of the test (including the one that
  passed) under each failed attempt.

Test plan: a flaky test that prints in call and teardown, a test that fails all
attempts, and a passing test, run with `--reruns=1` under pytest 7.3.2, 9.1.1
and 9.2.0, with `--tb=native` and `--tb=long --color=yes --showlocals`. The new
RERUNS section is identical to the old one except for the dropped teardown
sections.

```
cd test && PYTHONPATH=<pytest==$V overlay> python -m pytest -p no:cacheprovider zz_scratch_reruns.py --reruns=1
```

Authored with an AI assistant (Claude).
@ezyang ezyang added the topic: not user facing topic category label Oct 28, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR rebuilds the RERUNS section of test/conftest.py from public pytest report
fields. Before, it called private TerminalReporter methods, and pytest 9.2
quietly broke that part so it printed nothing. The review found no issues and
its Recommendation is Approve: the change only touches test-harness reporting,
and its output matches the old code apart from the dropped teardown sections and
two fallback differences.

Reviewed commit: 7955b35

Review run

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/202412

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 Unclassified Failures

As of commit 7955b35 with merge base 21d72b9 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Rewrites the pytest_terminal_summary hook in test/conftest.py, the test runner config that every test class excludes
    • Not a runtime no-op or mechanical refactor: it swaps private TerminalReporter helpers for rep.toterminal() and rep.sections
  • Behavior removed
    • Drops the --tb=line branch that printed _getcrashline per rerun; the PR justifies this only by current CI flags
    • Drops _handle_teardown_sections output and adds new --show-capture filtering of rep.sections
  • Socialization
    • Changes the shape of the RERUNS block in CI logs, which log classifiers and Dr. CI read from outside this repo
    • handle_log_file in test/run_test.py keys on === RERUNS ===; the header is kept, but a human should confirm the body change
  • Tests
    • No test in the diff covers the new output; it was only checked manually per the PR body

reason: not_trivial
Reviewed commit: c06e412 (NOT the current head 7955b35)

Inference job

🐛 Report a wrong verdict

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

  • .github/workflows/trunk.yml (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

    AI verdict: AI verdict: inconclusive

    The signal has no events, so there is no failure log, job ID or baseline to look at, and the PR shows no failed checks. The suspect does change test/conftest.py, which every test job loads, so a link is possible but can't be shown.

    Full reasoning on HUD →

  • .github/workflows/tsan.yml (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    AI verdict: AI verdict: pending

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@ezyang
ezyang marked this pull request as ready for review October 28, 2026 16:49
@ezyang ezyang added the mergedog mergedog is watching this PR label Oct 28, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 28, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 28, 2026
github-actions[bot]

This comment was marked as outdated.

@ezyang ezyang added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 28, 2026
@ezyang

ezyang commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

mergedog handoff

Note

This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.

All CI is green (or skipped). Ready for human review and @pytorchbot merge.

Current PR head: c06e41274ec8e84f070919d6e1f46281cacf601e.

Autonomous changes pushed

  • None.

CI notes at handoff

mergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:

  • macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Warning: mergedog's suppressed check list differs from the latest Dr. CI summary.

Suppressed by mergedog but not marked unrelated by Dr. CI:

  • macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)
Latest Dr. CI summary
## PR Status: in progress

A maintainer requested changes. Please address their feedback before the PR returns to maintainer review.

To become ready for review, the change must pass automated review and every maintainer comment must be addressed, either with a code change or a reply explaining why no change is needed. A fresh automated review checks that the feedback has been addressed. All CI must finish and Dr. CI must classify every failure as unrelated to your PR. Fix the failures it attributes to your PR (see status below in this comment). Workflows waiting for a maintainer to approve their run do not block this.

To minimize iteration time, feel free to run the pr-review skill from the repo locally. If you address comments without pushing, comment `@pytorchbot review` to re-run the automated review. To bypass automated review, please add the “no automated review” label.


<details><summary>🟡 <b>AUTOMATED REVIEW</b> - Changes requested:</summary><p>

The PR rebuilds the RERUNS section in test/conftest.py from public report fields
(head_line, toterminal(), sections) in place of four private TerminalReporter
methods, one of which broke silently in pytest 9.2. One problem: dropping the
--tb=line branch changes what users of that flag see, and the drop wasn't needed
to get off private API. Recommendation: Request Changes.


**Findings (1):**

[major] test/conftest.py:293
With --tb=line, RERUNS now prints full long tracebacks. For --tb=line, pytest's
Node._repr_failure_py builds each report's longrepr in long style (only short
gets its own style). The new loop calls rep.toterminal(...) regardless of style,
so every rerun attempt prints a full long traceback plus captured output, while
pytest's own FAILURES section prints one crash line per test in that mode. This
undercuts the new comment ("like pytest's FAILURES section") and is a regression
for anyone running --tb=line locally to keep output short (CI only uses
native/long, but local runs aren't limited to those). Removing private API
didn't require this: the old branch only called _getcrashline, which is just
str(rep.longrepr.reprcrash) with a fallback, and reprcrash is public. Suggested
fix: keep the branch without private API:

if config.option.tbstyle == "line":
crash = getattr(rep.longrepr, "reprcrash", None)
terminalreporter.write_line(str(crash) if crash is not None else
str(rep.longrepr)[:50])
continue

Then update the PR description, which lists this branch as dropped.


Reviewed commit: `c06e412`

[Review run](https://github.com/pytorch/pytorch/actions/runs/40731975174)

</p></details>

## :link: Helpful Links
### :test_tube: See artifacts and rendered test results at [hud.pytorch.org/pr/202412](https://hud.pytorch.org/pr/202412)
* :page_facing_up: Preview [Python docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/202412/index.html)
* :page_facing_up: Preview [C++ docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/202412/cppdocs/index.html)
* :question: Need help or want to give feedback on the CI? Visit the [bot commands wiki](https://github.com/pytorch/pytorch/wiki/Bot-commands)

Note: Links to docs will display an error until the docs builds have been completed.


## :x: 1 New Failure
As of commit c06e41274ec8e84f070919d6e1f46281cacf601e with merge base 21d72b9ee2e8241ae337470efd0903a1afb50a8f (<sub><sub><img alt="image" width=70 src="https://img.shields.io/date/1793197495?label=&color=FFFFFF&style=flat-square"></sub></sub>):
<details><summary>🟡 <b>GREEN LIGHT</b> - PR requires human review:</summary><p>

<ul><li><b>Triviality</b><ul><li>Rewrites the <code>pytest_terminal_summary</code> hook in <code>test/conftest.py</code>, the test runner config that every test class excludes</li><li>Not a runtime no-op or mechanical refactor: it swaps private <code>TerminalReporter</code> helpers for <code>rep.toterminal()</code> and <code>rep.sections</code></li></ul></li><li><b>Behavior removed</b><ul><li>Drops the <code>--tb=line</code> branch that printed <code>_getcrashline</code> per rerun; the PR justifies this only by current CI flags</li><li>Drops <code>_handle_teardown_sections</code> output and adds new <code>--show-capture</code> filtering of <code>rep.sections</code></li></ul></li><li><b>Socialization</b><ul><li>Changes the shape of the RERUNS block in CI logs, which log classifiers and Dr. CI read from outside this repo</li><li><code>handle_log_file</code> in <code>test/run_test.py</code> keys on <code>=== RERUNS ===</code>; the header is kept, but a human should confirm the body change</li></ul></li><li><b>Tests</b><ul><li>No test in the diff covers the new output; it was only checked manually per the PR body</li></ul></li></ul>

reason: `not_trivial`
Reviewed commit: `c06e412`

[Inference job](https://github.com/pytorch/test-infra/actions/runs/40730353655)

[:bug: Report a wrong verdict](https://hud.pytorch.org/pytorch/pytorch/pull/202412?sha=c06e41274ec8e84f070919d6e1f46281cacf601e&greenlightReport=1)

</p></details>
<details open><summary><b>NEW FAILURE</b> - The following job has failed:</summary><p>

* [trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)](https://hud.pytorch.org/pr/pytorch/pytorch/202412#123031170751) ([gh](https://github.com/pytorch/pytorch/actions/runs/40740750758/job/123031170751))
    `python_native/test_rmsnorm_cutedsl`
  <details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/202412#123031170751"><img alt="AI verdict: probably not related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=c06e41274ec8e84f070919d6e1f46281cacf601e&job=trunk+%2F+macos-py3-arm64+%2F+test+%28default%2C+1%2C+3%2C+macos-m1-stable%29&since=2026-10-28T21%3A15%3A10.000000000Z"></a></summary><blockquote>

  The suspect only rewrites the RERUNS terminal-summary hook in test/conftest.py, which runs only after a pytest session finishes. The failing process died with SIGBUS about 0.2s after launch, before pytest recorded its first test. The same test file, with the same conftest, passed earlier in the same job.

  <a href="https://hud.pytorch.org/pr/pytorch/pytorch/202412#123031170751">Full reasoning on HUD &rarr;</a>
  </blockquote></details>
</p></details>


This comment was automatically generated by Dr. CI and updates every 15 minutes.

During shepherding, the configured LLM was invoked 1 time. If any CI shows red, it judged that failure unrelated to this PR's changes — please verify below before merging.

Session 1 — fix-CI (2026-10-29T14:42:46+00:00)

  • Before: c06e41274ec8
  • Verdict: judged failures spurious (no commit) — failing jobs: macos-py3-arm64 / test (default, 1, 3, macos-m1-stable); rationale: Dismissing: macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) -- python_native/test_rmsnorm_cutedsl The PR only edits the pytest_terminal_summary RERUNS hook in test/conftest.py, which runs after a pytest session finishes. Dr. CI reports that the failing process died with SIGBUS about 0.2s after launch, before pytest recorded any test. The same test file, using the same conftest, passed earlier in the same job. A SIGBUS at process startup on a macOS runner is a native crash or runner/infra problem. A Python-level change to the end-of-session reporting hook cannot cause it, and the failure is limited to one shard on one platform.
LLM transcript
claude session 5eaacc26
claude → Bash: git diff --stat 21d72b9ee2e HEAD && head -c 3000 /home/ezyang/.mergedog/contexts/202412.md
claude → Bash: cat > .mergedog-spurious <<'EOF'
               Dismissing: macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) -- python_native/test_rmsnorm_cutedsl
               
               The PR only edits the pytest_terminal_summary RERUNS hook in test/conftest.py,
               which runs after a pytest session finishes. Dr. CI reports that the failing
               process died with SIGBUS about 0.2s after launch, before pytest recorded any
               test. The same test file, using the same conftest, passed earlier in the same
               job. A SIGBUS at process startup on a macOS runner is a native crash or
               runner/infra problem. A Python-level change to the end-of-session reporting
               hook cannot cause it, and the failure is limited to one shard on one platform.
               EOF
claude: I marked the one failing check as spurious and wrote the reason to `.mergedog-spurious`. I made no commit.
claude: **Failing check:** `macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)`, in `python_native/test_rmsnorm_cutedsl`.
claude: **Why I think it's unrelated:**
claude: - **What the PR changes:** it only edits the hook in `test/conftest.py` that prints the RERUNS summary, and that hook runs after a pytest session finishes.
claude: - **How the test died:** Dr. CI reports that the process crashed with a bus error (SIGBUS) about 0.2s after launch, before pytest recorded any test. I couldn't confirm this from the raw log excerpt, which cuts off before that point.
claude: - **Same code passed earlier:** the same test file, with the same `conftest.py`, passed earlier in the same job.
claude: - **Scope:** the failure is on one shard of one platform. A native crash at startup like this points to the runner, not to a Python change in end-of-session reporting.
claude: **Not addressed:** the automated review is still requesting changes. It wants the `--tb=line` branch restored using the public `reprcrash` field. That is review feedback, not a CI failure, so I didn't touch it. It needs a human decision.
claude finished: success (cost $0.3712)

Address the automated review: with --tb=line, print one crash line per rerun
attempt, as before, instead of the long traceback. The old branch called the
private _getcrashline, which is str(rep.longrepr.reprcrash) with a fallback;
use that public field directly.

Test plan: a flaky test, a test that fails all attempts, a setup error and a
pytest.fail() run with --reruns=1 --tb=line under pytest 7.3.2 and 9.2.0. The
RERUNS section has one line per attempt, matching the old conftest except
where the two pytest versions format reprcrash differently.

Authored with an AI assistant (Claude).
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Oct 29, 2026

@github-actions github-actions 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.

Automated review of 7955b35: nothing blocking; ready for human review.

The PR rebuilds the RERUNS section of test/conftest.py from public pytest report fields. Before, it called private TerminalReporter methods, and pytest 9.2 quietly broke that part so it printed nothing. The review found no issues and its Recommendation is Approve: the change only touches test-harness reporting, and its output matches the old code apart from the dropped teardown sections and two fallback differences.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@github-actions
github-actions Bot dismissed their stale review October 29, 2026 16:17

Withdrawn: the automated review of 7955b35 found nothing blocking.

@ezyang

ezyang commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 jobs have failed, first few of them are: .github/workflows/trunk.yml, .github/workflows/tsan.yml

Details for Dev Infra team

Raised by workflow job

pytorchmergebot pushed a commit that referenced this pull request Oct 30, 2026
## Human Note
I tried getting rid of the custom class entirely but Claude persuaded me it was useful. So we're just going to subclass from pytest so we can track upstream more easily.

## Agent Report
### Problem

With pytest 9.2.0, any test run that writes `--junit-xml-reruns` (every CI test shard) aborts with an INTERNALERROR at the first test's teardown:

```
File "test/conftest.py", line 254, in pytest_runtest_logreport
  super().pytest_runtest_logreport(report)
File "_pytest/junitxml.py", line 544, in finalize
  reporter = self.node_reporters.pop((node_id, workernode))
KeyError: (NodeId(path='test/test_pytree.py', names=('TestGenericPytree', 'test_aligned_public_apis'), params=None), None)
```

### Root cause

`LogXMLReruns.node_reporter` was a copy of pytest's `LogXML.node_reporter`. The copy only differed in building a `_NodeReporterReruns` and stored reporters under `(report.nodeid, workernode)`, with `nodeid` as a string. pytest 9.2 keys `node_reporters` by a new `NodeId` dataclass (`report.id`), and `LogXML.finalize` pops with that key. A `NodeId` never equals a string, so the pop fails.

### Fix

Call `super().node_reporter(report)` so pytest builds the key and the reporter in whatever form that version uses, check that `_NodeReporterReruns` subclasses the returned type, then set the reporter's `__class__` to `_NodeReporterReruns`. The class docstring now says it may only override methods, not add state or change how instance data is represented. The subclass only overrides output methods (`_prepare_content`, `_write_content`, `append_skipped`) and adds no state, so switching the class in place is safe, and it removes the copy of pytest internals that went stale. I also added a docstring to `_NodeReporterReruns` explaining why it exists. pytest.ini sets `junit_logging_reruns = all`, and with the stock `_NodeReporter` every testcase, including passing tests that print nothing, gets a headed `<system-out>` and `<system-err>` element (skipped tests get both twice). The subclass writes captured output raw and omits empty streams. Regenerating the goldens without the subclass shows exactly that difference. The other option, branching on the pytest version to build the right key type, would keep the copy and break again the next time pytest changes the key.

This also reverts #202385, which pinned `pytest==9.1.1` in the inductor-benchmarks images as a stopgap for this crash (TorchBench's requirements pull in an unpinned pytest). The other pytest 9.2 fixes still open shouldn't affect those images: #202406 (`--subprocess` test ids) only matters for the few test modules that `run_test.py` runs with `--subprocess`, which are CUDA-init and distributed tests the inductor configs don't run, and #202412 only restores the teardown part of the RERUNS terminal summary.

### Test

`TestJunitXml` (test/test_testing.py) used to skip on every pytest version except the goldens' (the CI pins), so no test could see this crash. `setUpClass` now records that skip reason instead of raising and still runs the fixture suite; only the exact golden comparisons skip on other versions. The tag counts move out of `test_pytest_outcome_shapes` into `test_pytest_outcome_counts`, which runs on every version and also checks for INTERNALERROR. On pytest 9.2.0 the counts test passes with this change and fails without it; on 7.3.2 (the CI pin) all three tests pass.

#### Where the versions come from

Running the fixture suite on every version means `setUpClass` now depends on the environment in ways the old blanket skip hid, so the version checks have to describe the process that actually runs the suite. That process is a child (`sys.executable -m pytest`) with `PYTHONPATH` removed, so the parent's view can be wrong. Asking the parent with `importlib.metadata` would mean:

- With pytest only on the parent's `PYTHONPATH`, the parent sees pytest, the child doesn't, writes no XML, and `setUpClass` raises instead of skipping (the case the automated review hit, where pytest is missing entirely, is the simplest instance).
- With a different pytest on the parent's `PYTHONPATH`, the golden header check compares the goldens against one version while the child produces XML with another, and the golden tests fail.

So `setUpClass` first runs a small probe, `_junit_child_versions()`, in the child's interpreter and environment: it prints the pytest and pytest-rerunfailures versions (or null) as JSON via `importlib.metadata`, without importing torch. That one result decides all three things: the class skips when pytest is missing, the counts test skips when pytest-rerunfailures is missing, and the golden header is built from it. The probe costs about 60 ms once per class, next to roughly 3.5 s for the fixture suite run the class already does. The alternatives were matching `No module named pytest` in the fixture run's stderr (covers only the missing-pytest case and leaves the golden mismatch) or parsing the `plugins:` line from pytest's console header (fragile, and only saves those 60 ms).

The child also drops `PYTEST_PLUGINS` and `PYTEST_DISABLE_PLUGIN_AUTOLOAD`, as it already drops `PYTEST_ADDOPTS`, so it loads the installed plugins as CI does; with autoload off, pytest-rerunfailures was importable but never loaded and the counts were wrong.

Checked in throwaway environments that really have each version (a `PYTHONPATH` overlay only changes the parent):

| Child environment | Result |
|---|---|
| no pytest | class skipped |
| pytest 9.1.1, no pytest-rerunfailures | all three skip |
| pytest 9.2.0 + pytest-rerunfailures 14.0 | counts pass, goldens skip; counts fail with the old conftest |
| pytest 7.3.2 + pytest-rerunfailures 14.0 | all three pass |
| job venv with pytest 7.3.2 on the parent's `PYTHONPATH`, or `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` | counts pass, goldens skip |

```
cd test && CUDA_VISIBLE_DEVICES= python test_testing.py -k TestJunitXml
```

### Validation

A minimal test file covering pass, skip, a flaky test that passes on rerun, a consistent failure with reruns, and an expected failure, run with `--reruns=2 --junit-xml-reruns`, serially and with `-n 2`, under pytest 7.3.2 (requirements-ci pin), 9.1.1 and 9.2.0. pytest-rerunfailures 14.0 and pytest-xdist 3.3.1 are the CI versions. In all six configurations the testcase/rerun/skipped/failure elements of the rerun XML match those the unmodified conftest produces under 9.1.1. Unmodified conftest under 9.2.0 crashes with the KeyError above.

```
PYTHONPATH=<overlay with pytest==$V pytest-rerunfailures==14.0 pytest-xdist==3.3.1> python -m pytest -q -p no:cacheprovider test_mini.py --reruns=2 [-n 2] --junit-xml-reruns=out/r.xml
```

Real test file with each pytest version: 251 passed and 251 testcases in the XML, no INTERNALERROR. The same command with the old conftest on 9.2.0 crashes after the first test.

```
cd test && PYTHONPATH=<overlay pytest==$V> python -m pytest -q -p no:cacheprovider test_pytree.py --reruns=2 -x --junit-xml-reruns=/tmp/rr/r.xml
```

The existing golden fixture `test/junit_xml_testdata/pytest_suite.py` (13 outcome shapes, normalized the same way `TestJunitXml` in `test/test_testing.py` does):
- pytest 7.3.2: the new conftest output matches the committed golden `expected/pytest.xml`, which was recorded with pytest 7.3.2.
- pytest 9.1.1: the new conftest output is identical to the old conftest's.
- pytest 9.2.0: the new conftest output is identical to the old conftest's output under 9.1.1. The old conftest crashes with 81 INTERNALERRORs.

The change was reviewed by two fresh agents (correctness and quality) before this update; their findings are addressed above.

`lintrunner test/conftest.py` is clean.

<details>
<summary>Agent Worklog</summary>

# Worklog

- 2026-10-28: Diffed pytest 9.1.1 and 9.2.0 `_pytest/junitxml.py`. `node_reporters` is now keyed by a `NodeId` dataclass (`report.id`); `finalize` pops `(report.id, workernode)`. conftest's copied `node_reporter` used string nodeids, so it fails at the first teardown, not only on reruns.
- Reproduced with a minimal test file under overlays of pytest 7.3.2/9.1.1/9.2.0 on the job venv's torch.
- Fix: delegate to `super().node_reporter` and set `__class__ = _NodeReporterReruns`. The XML matches the old behavior under all three versions, serial and with xdist. `test_pytree.py` passes under all three. lintrunner is clean.
- Golden fixture junit_xml_testdata/pytest_suite.py: new==golden on 7.3.2, new==old on 9.1.1, new on 9.2.0 == old on 9.1.1.
- 2026-10-29: (superseded) C1 test change moved to its own PR, see below.
- 2026-10-29: split the C1 test change into job 20261029-pytorch-adhoc-7dcc5b (new PR below this one); this branch now sits on ptq/20261029-pytorch-adhoc-7dcc5b. Counts test passes on 9.2.0 with this fix. Not pushed.
- 2026-10-29: now on the refactor 7879242; this PR moves the version skip onto the goldens and runs the counts (plus an INTERNALERROR check) on every version. Commit d334d9d. 9.2.0: counts pass with the fix, fail without.
- 2026-10-29: shrank the test change: setUpClass unchanged except it records the version-mismatch reason (golden_skip) instead of raising, and keeps proc output; goldens skip on it; counts add an INTERNALERROR check. Commit 980d40eddfd. 7.3.2 all pass; 9.2.0 counts pass (fail without the conftest fix), goldens skip.
- 2026-10-29: consolidated (Edward OK): #202597 closed, this PR retargeted to main, single commit de4b8db pushed, body Test section updated.
- 2026-10-29: automated review flagged the pytest==9.1.1 pin from #202385 in install_inductor_benchmark_deps.sh as stale. Rebased onto origin/main 92264e2 and removed the pin (exact revert of #202385). TestJunitXml: 9.1.1 venv and 9.2.0 overlay pass (goldens skip); the 7.3.2 golden diffs I saw were my overlay run missing the repo-root pytest.ini; the PR-review agent confirmed old and new conftest match the goldens on 7.3.2 run in place. Not pushed.
- 2026-10-30: Edward approved; pushed 1d11f93 via git (ssh). PR body not yet regenerated: gh on devgpu013 is logged out (~/.config/gh/hosts.yml emptied 2026-10-30 06:20). Body regenerated with ptq pr on 2026-10-30 after gh re-auth.
- 2026-10-30: automated review of 1d11f93: without pytest installed, TestJunitXml errored (subprocess ran, no XML) instead of skipping. setUpClass now raises SkipTest first when pytest is missing. Verified with _junit_provenance patched to "pytest missing" (class skipped, subprocess not run); 9.1.1 venv and 9.2.0 overlay unchanged; lint clean.
- 2026-10-30: per Edward, replaced the provenance-string checks: setUpClass skips when the child stderr has "No module named pytest" (no XML), and the counts test probes `import pytest_rerunfailures` with the child env. Note: earlier PYTHONPATH-overlay runs of TestJunitXml only changed the parent; the child drops PYTHONPATH and used the venv pytest 9.1.1. Re-verified with symlinked throwaway venvs: 9.2.0 counts pass (fail with origin/main conftest), 7.3.2 all pass, no pytest -> class skipped, no rerunfailures -> all skip.
- 2026-10-30: replaced the stderr match and import probe with one child probe (_junit_child_versions, JSON of pytest/rerunfailures versions under _JUNIT_CHILD_ENV): it drives the class skip, has_rerunfailures, and the golden provenance (fixes parent/child mismatch under PYTHONPATH). Child env also drops PYTEST_PLUGINS/PYTEST_DISABLE_PLUGIN_AUTOLOAD. Verified: no pytest -> class skip; no rerunfailures -> 3 skips; 9.2.0 counts pass (fail with origin/main conftest); 7.3.2 all pass; job venv with PYTHONPATH=ov-7.3.2 or PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 -> OK.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue) with human review.*
Pull Request resolved: #202390
Approved by: https://github.com/nWEIdia, https://github.com/atalman, https://github.com/huydhn, https://github.com/jeanschmidt
@ezyang

ezyang commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: trunk, .github/workflows/tsan.yml

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…h#202390)

## Human Note
I tried getting rid of the custom class entirely but Claude persuaded me it was useful. So we're just going to subclass from pytest so we can track upstream more easily.

## Agent Report
### Problem

With pytest 9.2.0, any test run that writes `--junit-xml-reruns` (every CI test shard) aborts with an INTERNALERROR at the first test's teardown:

```
File "test/conftest.py", line 254, in pytest_runtest_logreport
  super().pytest_runtest_logreport(report)
File "_pytest/junitxml.py", line 544, in finalize
  reporter = self.node_reporters.pop((node_id, workernode))
KeyError: (NodeId(path='test/test_pytree.py', names=('TestGenericPytree', 'test_aligned_public_apis'), params=None), None)
```

### Root cause

`LogXMLReruns.node_reporter` was a copy of pytest's `LogXML.node_reporter`. The copy only differed in building a `_NodeReporterReruns` and stored reporters under `(report.nodeid, workernode)`, with `nodeid` as a string. pytest 9.2 keys `node_reporters` by a new `NodeId` dataclass (`report.id`), and `LogXML.finalize` pops with that key. A `NodeId` never equals a string, so the pop fails.

### Fix

Call `super().node_reporter(report)` so pytest builds the key and the reporter in whatever form that version uses, check that `_NodeReporterReruns` subclasses the returned type, then set the reporter's `__class__` to `_NodeReporterReruns`. The class docstring now says it may only override methods, not add state or change how instance data is represented. The subclass only overrides output methods (`_prepare_content`, `_write_content`, `append_skipped`) and adds no state, so switching the class in place is safe, and it removes the copy of pytest internals that went stale. I also added a docstring to `_NodeReporterReruns` explaining why it exists. pytest.ini sets `junit_logging_reruns = all`, and with the stock `_NodeReporter` every testcase, including passing tests that print nothing, gets a headed `<system-out>` and `<system-err>` element (skipped tests get both twice). The subclass writes captured output raw and omits empty streams. Regenerating the goldens without the subclass shows exactly that difference. The other option, branching on the pytest version to build the right key type, would keep the copy and break again the next time pytest changes the key.

This also reverts pytorch#202385, which pinned `pytest==9.1.1` in the inductor-benchmarks images as a stopgap for this crash (TorchBench's requirements pull in an unpinned pytest). The other pytest 9.2 fixes still open shouldn't affect those images: pytorch#202406 (`--subprocess` test ids) only matters for the few test modules that `run_test.py` runs with `--subprocess`, which are CUDA-init and distributed tests the inductor configs don't run, and pytorch#202412 only restores the teardown part of the RERUNS terminal summary.

### Test

`TestJunitXml` (test/test_testing.py) used to skip on every pytest version except the goldens' (the CI pins), so no test could see this crash. `setUpClass` now records that skip reason instead of raising and still runs the fixture suite; only the exact golden comparisons skip on other versions. The tag counts move out of `test_pytest_outcome_shapes` into `test_pytest_outcome_counts`, which runs on every version and also checks for INTERNALERROR. On pytest 9.2.0 the counts test passes with this change and fails without it; on 7.3.2 (the CI pin) all three tests pass.

#### Where the versions come from

Running the fixture suite on every version means `setUpClass` now depends on the environment in ways the old blanket skip hid, so the version checks have to describe the process that actually runs the suite. That process is a child (`sys.executable -m pytest`) with `PYTHONPATH` removed, so the parent's view can be wrong. Asking the parent with `importlib.metadata` would mean:

- With pytest only on the parent's `PYTHONPATH`, the parent sees pytest, the child doesn't, writes no XML, and `setUpClass` raises instead of skipping (the case the automated review hit, where pytest is missing entirely, is the simplest instance).
- With a different pytest on the parent's `PYTHONPATH`, the golden header check compares the goldens against one version while the child produces XML with another, and the golden tests fail.

So `setUpClass` first runs a small probe, `_junit_child_versions()`, in the child's interpreter and environment: it prints the pytest and pytest-rerunfailures versions (or null) as JSON via `importlib.metadata`, without importing torch. That one result decides all three things: the class skips when pytest is missing, the counts test skips when pytest-rerunfailures is missing, and the golden header is built from it. The probe costs about 60 ms once per class, next to roughly 3.5 s for the fixture suite run the class already does. The alternatives were matching `No module named pytest` in the fixture run's stderr (covers only the missing-pytest case and leaves the golden mismatch) or parsing the `plugins:` line from pytest's console header (fragile, and only saves those 60 ms).

The child also drops `PYTEST_PLUGINS` and `PYTEST_DISABLE_PLUGIN_AUTOLOAD`, as it already drops `PYTEST_ADDOPTS`, so it loads the installed plugins as CI does; with autoload off, pytest-rerunfailures was importable but never loaded and the counts were wrong.

Checked in throwaway environments that really have each version (a `PYTHONPATH` overlay only changes the parent):

| Child environment | Result |
|---|---|
| no pytest | class skipped |
| pytest 9.1.1, no pytest-rerunfailures | all three skip |
| pytest 9.2.0 + pytest-rerunfailures 14.0 | counts pass, goldens skip; counts fail with the old conftest |
| pytest 7.3.2 + pytest-rerunfailures 14.0 | all three pass |
| job venv with pytest 7.3.2 on the parent's `PYTHONPATH`, or `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` | counts pass, goldens skip |

```
cd test && CUDA_VISIBLE_DEVICES= python test_testing.py -k TestJunitXml
```

### Validation

A minimal test file covering pass, skip, a flaky test that passes on rerun, a consistent failure with reruns, and an expected failure, run with `--reruns=2 --junit-xml-reruns`, serially and with `-n 2`, under pytest 7.3.2 (requirements-ci pin), 9.1.1 and 9.2.0. pytest-rerunfailures 14.0 and pytest-xdist 3.3.1 are the CI versions. In all six configurations the testcase/rerun/skipped/failure elements of the rerun XML match those the unmodified conftest produces under 9.1.1. Unmodified conftest under 9.2.0 crashes with the KeyError above.

```
PYTHONPATH=<overlay with pytest==$V pytest-rerunfailures==14.0 pytest-xdist==3.3.1> python -m pytest -q -p no:cacheprovider test_mini.py --reruns=2 [-n 2] --junit-xml-reruns=out/r.xml
```

Real test file with each pytest version: 251 passed and 251 testcases in the XML, no INTERNALERROR. The same command with the old conftest on 9.2.0 crashes after the first test.

```
cd test && PYTHONPATH=<overlay pytest==$V> python -m pytest -q -p no:cacheprovider test_pytree.py --reruns=2 -x --junit-xml-reruns=/tmp/rr/r.xml
```

The existing golden fixture `test/junit_xml_testdata/pytest_suite.py` (13 outcome shapes, normalized the same way `TestJunitXml` in `test/test_testing.py` does):
- pytest 7.3.2: the new conftest output matches the committed golden `expected/pytest.xml`, which was recorded with pytest 7.3.2.
- pytest 9.1.1: the new conftest output is identical to the old conftest's.
- pytest 9.2.0: the new conftest output is identical to the old conftest's output under 9.1.1. The old conftest crashes with 81 INTERNALERRORs.

The change was reviewed by two fresh agents (correctness and quality) before this update; their findings are addressed above.

`lintrunner test/conftest.py` is clean.

<details>
<summary>Agent Worklog</summary>

# Worklog

- 2026-10-28: Diffed pytest 9.1.1 and 9.2.0 `_pytest/junitxml.py`. `node_reporters` is now keyed by a `NodeId` dataclass (`report.id`); `finalize` pops `(report.id, workernode)`. conftest's copied `node_reporter` used string nodeids, so it fails at the first teardown, not only on reruns.
- Reproduced with a minimal test file under overlays of pytest 7.3.2/9.1.1/9.2.0 on the job venv's torch.
- Fix: delegate to `super().node_reporter` and set `__class__ = _NodeReporterReruns`. The XML matches the old behavior under all three versions, serial and with xdist. `test_pytree.py` passes under all three. lintrunner is clean.
- Golden fixture junit_xml_testdata/pytest_suite.py: new==golden on 7.3.2, new==old on 9.1.1, new on 9.2.0 == old on 9.1.1.
- 2026-10-29: (superseded) C1 test change moved to its own PR, see below.
- 2026-10-29: split the C1 test change into job 20261029-pytorch-adhoc-7dcc5b (new PR below this one); this branch now sits on ptq/20261029-pytorch-adhoc-7dcc5b. Counts test passes on 9.2.0 with this fix. Not pushed.
- 2026-10-29: now on the refactor 7879242; this PR moves the version skip onto the goldens and runs the counts (plus an INTERNALERROR check) on every version. Commit d334d9d. 9.2.0: counts pass with the fix, fail without.
- 2026-10-29: shrank the test change: setUpClass unchanged except it records the version-mismatch reason (golden_skip) instead of raising, and keeps proc output; goldens skip on it; counts add an INTERNALERROR check. Commit 980d40eddfd. 7.3.2 all pass; 9.2.0 counts pass (fail without the conftest fix), goldens skip.
- 2026-10-29: consolidated (Edward OK): pytorch#202597 closed, this PR retargeted to main, single commit de4b8db pushed, body Test section updated.
- 2026-10-29: automated review flagged the pytest==9.1.1 pin from pytorch#202385 in install_inductor_benchmark_deps.sh as stale. Rebased onto origin/main 92264e2 and removed the pin (exact revert of pytorch#202385). TestJunitXml: 9.1.1 venv and 9.2.0 overlay pass (goldens skip); the 7.3.2 golden diffs I saw were my overlay run missing the repo-root pytest.ini; the PR-review agent confirmed old and new conftest match the goldens on 7.3.2 run in place. Not pushed.
- 2026-10-30: Edward approved; pushed 1d11f93 via git (ssh). PR body not yet regenerated: gh on devgpu013 is logged out (~/.config/gh/hosts.yml emptied 2026-10-30 06:20). Body regenerated with ptq pr on 2026-10-30 after gh re-auth.
- 2026-10-30: automated review of 1d11f93: without pytest installed, TestJunitXml errored (subprocess ran, no XML) instead of skipping. setUpClass now raises SkipTest first when pytest is missing. Verified with _junit_provenance patched to "pytest missing" (class skipped, subprocess not run); 9.1.1 venv and 9.2.0 overlay unchanged; lint clean.
- 2026-10-30: per Edward, replaced the provenance-string checks: setUpClass skips when the child stderr has "No module named pytest" (no XML), and the counts test probes `import pytest_rerunfailures` with the child env. Note: earlier PYTHONPATH-overlay runs of TestJunitXml only changed the parent; the child drops PYTHONPATH and used the venv pytest 9.1.1. Re-verified with symlinked throwaway venvs: 9.2.0 counts pass (fail with origin/main conftest), 7.3.2 all pass, no pytest -> class skipped, no rerunfailures -> all skip.
- 2026-10-30: replaced the stderr match and import probe with one child probe (_junit_child_versions, JSON of pytest/rerunfailures versions under _JUNIT_CHILD_ENV): it drives the class skip, has_rerunfailures, and the golden provenance (fixes parent/child mismatch under PYTHONPATH). Child env also drops PYTEST_PLUGINS/PYTEST_DISABLE_PLUGIN_AUTOLOAD. Verified: no pytest -> class skip; no rerunfailures -> 3 skips; 9.2.0 counts pass (fail with origin/main conftest); 7.3.2 all pass; job venv with PYTHONPATH=ov-7.3.2 or PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 -> OK.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue) with human review.*
Pull Request resolved: pytorch#202390
Approved by: https://github.com/nWEIdia, https://github.com/atalman, https://github.com/huydhn, https://github.com/jeanschmidt
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
## Human Note
Claude removed the tb=line branch since it doesn't trigger in CI, and claims the teardown sections stuff never worked even on older pytest. I don't really have a bone in this fight.

## Agent Report
test/conftest.py's RERUNS section (pytorch#86831) prints why each rerun attempt
failed, since pytest-rerunfailures itself only lists reruns. It did so through
four private TerminalReporter methods (`_getcrashline`, `_getfailureheadline`,
`_outrep_summary`, `_handle_teardown_sections`). pytest 9.2 changed
`_handle_teardown_sections` to take a `NodeId`, so the teardown part silently
printed nothing.

This builds the same output from public API: each rerun report's `head_line`,
`toterminal()` (onto `config.get_terminal_writer()`) and `sections`, filtered by
`--show-capture` like pytest's FAILURES section. With `--tb=line` it still
prints one crash line per attempt, now from the public
`rep.longrepr.reprcrash` (falling back to the start of `str(longrepr)`, as
`_getcrashline` did, for a plain-string longrepr such as an xdist worker
crash's).

One part is dropped: the teardown sections. They were looked up by node id, so
they printed the teardown output of every attempt of the test (including the
one that passed) under each failed attempt.

Test plan: a flaky test that prints in call and teardown, a test that fails all
attempts, and a passing test, run with `--reruns=1` under pytest 7.3.2, 9.1.1
and 9.2.0, with `--tb=native` and `--tb=long --color=yes --showlocals`. The new
RERUNS section is identical to the old one except for the dropped teardown
sections. With `--tb=line` (adding a setup error and a `pytrace=False` failure)
under 7.3.2 and 9.2.0, it prints one line per attempt, matching the old
conftest except where the two pytest versions format `reprcrash` differently.

```
cd test && PYTHONPATH=<pytest==$V overlay> python -m pytest -p no:cacheprovider zz_scratch_reruns.py --reruns=1
```

Authored with an AI assistant (Claude).

<details>
<summary>Agent Worklog</summary>

- 2026-10-28: split out of pytorch#202390 (C). Verified on 7.3.2/9.1.1/9.2.0.
- 2026-10-29: kept the `--tb=line` branch (automated review), via public `reprcrash`.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue) with human review.*

Pull Request resolved: pytorch#202412
Approved by: https://github.com/Skylion007
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…h#202390)

## Human Note
I tried getting rid of the custom class entirely but Claude persuaded me it was useful. So we're just going to subclass from pytest so we can track upstream more easily.

## Agent Report
### Problem

With pytest 9.2.0, any test run that writes `--junit-xml-reruns` (every CI test shard) aborts with an INTERNALERROR at the first test's teardown:

```
File "test/conftest.py", line 254, in pytest_runtest_logreport
  super().pytest_runtest_logreport(report)
File "_pytest/junitxml.py", line 544, in finalize
  reporter = self.node_reporters.pop((node_id, workernode))
KeyError: (NodeId(path='test/test_pytree.py', names=('TestGenericPytree', 'test_aligned_public_apis'), params=None), None)
```

### Root cause

`LogXMLReruns.node_reporter` was a copy of pytest's `LogXML.node_reporter`. The copy only differed in building a `_NodeReporterReruns` and stored reporters under `(report.nodeid, workernode)`, with `nodeid` as a string. pytest 9.2 keys `node_reporters` by a new `NodeId` dataclass (`report.id`), and `LogXML.finalize` pops with that key. A `NodeId` never equals a string, so the pop fails.

### Fix

Call `super().node_reporter(report)` so pytest builds the key and the reporter in whatever form that version uses, check that `_NodeReporterReruns` subclasses the returned type, then set the reporter's `__class__` to `_NodeReporterReruns`. The class docstring now says it may only override methods, not add state or change how instance data is represented. The subclass only overrides output methods (`_prepare_content`, `_write_content`, `append_skipped`) and adds no state, so switching the class in place is safe, and it removes the copy of pytest internals that went stale. I also added a docstring to `_NodeReporterReruns` explaining why it exists. pytest.ini sets `junit_logging_reruns = all`, and with the stock `_NodeReporter` every testcase, including passing tests that print nothing, gets a headed `<system-out>` and `<system-err>` element (skipped tests get both twice). The subclass writes captured output raw and omits empty streams. Regenerating the goldens without the subclass shows exactly that difference. The other option, branching on the pytest version to build the right key type, would keep the copy and break again the next time pytest changes the key.

This also reverts pytorch#202385, which pinned `pytest==9.1.1` in the inductor-benchmarks images as a stopgap for this crash (TorchBench's requirements pull in an unpinned pytest). The other pytest 9.2 fixes still open shouldn't affect those images: pytorch#202406 (`--subprocess` test ids) only matters for the few test modules that `run_test.py` runs with `--subprocess`, which are CUDA-init and distributed tests the inductor configs don't run, and pytorch#202412 only restores the teardown part of the RERUNS terminal summary.

### Test

`TestJunitXml` (test/test_testing.py) used to skip on every pytest version except the goldens' (the CI pins), so no test could see this crash. `setUpClass` now records that skip reason instead of raising and still runs the fixture suite; only the exact golden comparisons skip on other versions. The tag counts move out of `test_pytest_outcome_shapes` into `test_pytest_outcome_counts`, which runs on every version and also checks for INTERNALERROR. On pytest 9.2.0 the counts test passes with this change and fails without it; on 7.3.2 (the CI pin) all three tests pass.

#### Where the versions come from

Running the fixture suite on every version means `setUpClass` now depends on the environment in ways the old blanket skip hid, so the version checks have to describe the process that actually runs the suite. That process is a child (`sys.executable -m pytest`) with `PYTHONPATH` removed, so the parent's view can be wrong. Asking the parent with `importlib.metadata` would mean:

- With pytest only on the parent's `PYTHONPATH`, the parent sees pytest, the child doesn't, writes no XML, and `setUpClass` raises instead of skipping (the case the automated review hit, where pytest is missing entirely, is the simplest instance).
- With a different pytest on the parent's `PYTHONPATH`, the golden header check compares the goldens against one version while the child produces XML with another, and the golden tests fail.

So `setUpClass` first runs a small probe, `_junit_child_versions()`, in the child's interpreter and environment: it prints the pytest and pytest-rerunfailures versions (or null) as JSON via `importlib.metadata`, without importing torch. That one result decides all three things: the class skips when pytest is missing, the counts test skips when pytest-rerunfailures is missing, and the golden header is built from it. The probe costs about 60 ms once per class, next to roughly 3.5 s for the fixture suite run the class already does. The alternatives were matching `No module named pytest` in the fixture run's stderr (covers only the missing-pytest case and leaves the golden mismatch) or parsing the `plugins:` line from pytest's console header (fragile, and only saves those 60 ms).

The child also drops `PYTEST_PLUGINS` and `PYTEST_DISABLE_PLUGIN_AUTOLOAD`, as it already drops `PYTEST_ADDOPTS`, so it loads the installed plugins as CI does; with autoload off, pytest-rerunfailures was importable but never loaded and the counts were wrong.

Checked in throwaway environments that really have each version (a `PYTHONPATH` overlay only changes the parent):

| Child environment | Result |
|---|---|
| no pytest | class skipped |
| pytest 9.1.1, no pytest-rerunfailures | all three skip |
| pytest 9.2.0 + pytest-rerunfailures 14.0 | counts pass, goldens skip; counts fail with the old conftest |
| pytest 7.3.2 + pytest-rerunfailures 14.0 | all three pass |
| job venv with pytest 7.3.2 on the parent's `PYTHONPATH`, or `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` | counts pass, goldens skip |

```
cd test && CUDA_VISIBLE_DEVICES= python test_testing.py -k TestJunitXml
```

### Validation

A minimal test file covering pass, skip, a flaky test that passes on rerun, a consistent failure with reruns, and an expected failure, run with `--reruns=2 --junit-xml-reruns`, serially and with `-n 2`, under pytest 7.3.2 (requirements-ci pin), 9.1.1 and 9.2.0. pytest-rerunfailures 14.0 and pytest-xdist 3.3.1 are the CI versions. In all six configurations the testcase/rerun/skipped/failure elements of the rerun XML match those the unmodified conftest produces under 9.1.1. Unmodified conftest under 9.2.0 crashes with the KeyError above.

```
PYTHONPATH=<overlay with pytest==$V pytest-rerunfailures==14.0 pytest-xdist==3.3.1> python -m pytest -q -p no:cacheprovider test_mini.py --reruns=2 [-n 2] --junit-xml-reruns=out/r.xml
```

Real test file with each pytest version: 251 passed and 251 testcases in the XML, no INTERNALERROR. The same command with the old conftest on 9.2.0 crashes after the first test.

```
cd test && PYTHONPATH=<overlay pytest==$V> python -m pytest -q -p no:cacheprovider test_pytree.py --reruns=2 -x --junit-xml-reruns=/tmp/rr/r.xml
```

The existing golden fixture `test/junit_xml_testdata/pytest_suite.py` (13 outcome shapes, normalized the same way `TestJunitXml` in `test/test_testing.py` does):
- pytest 7.3.2: the new conftest output matches the committed golden `expected/pytest.xml`, which was recorded with pytest 7.3.2.
- pytest 9.1.1: the new conftest output is identical to the old conftest's.
- pytest 9.2.0: the new conftest output is identical to the old conftest's output under 9.1.1. The old conftest crashes with 81 INTERNALERRORs.

The change was reviewed by two fresh agents (correctness and quality) before this update; their findings are addressed above.

`lintrunner test/conftest.py` is clean.

<details>
<summary>Agent Worklog</summary>

# Worklog

- 2026-10-28: Diffed pytest 9.1.1 and 9.2.0 `_pytest/junitxml.py`. `node_reporters` is now keyed by a `NodeId` dataclass (`report.id`); `finalize` pops `(report.id, workernode)`. conftest's copied `node_reporter` used string nodeids, so it fails at the first teardown, not only on reruns.
- Reproduced with a minimal test file under overlays of pytest 7.3.2/9.1.1/9.2.0 on the job venv's torch.
- Fix: delegate to `super().node_reporter` and set `__class__ = _NodeReporterReruns`. The XML matches the old behavior under all three versions, serial and with xdist. `test_pytree.py` passes under all three. lintrunner is clean.
- Golden fixture junit_xml_testdata/pytest_suite.py: new==golden on 7.3.2, new==old on 9.1.1, new on 9.2.0 == old on 9.1.1.
- 2026-10-29: (superseded) C1 test change moved to its own PR, see below.
- 2026-10-29: split the C1 test change into job 20261029-pytorch-adhoc-7dcc5b (new PR below this one); this branch now sits on ptq/20261029-pytorch-adhoc-7dcc5b. Counts test passes on 9.2.0 with this fix. Not pushed.
- 2026-10-29: now on the refactor 7879242; this PR moves the version skip onto the goldens and runs the counts (plus an INTERNALERROR check) on every version. Commit d334d9d. 9.2.0: counts pass with the fix, fail without.
- 2026-10-29: shrank the test change: setUpClass unchanged except it records the version-mismatch reason (golden_skip) instead of raising, and keeps proc output; goldens skip on it; counts add an INTERNALERROR check. Commit 980d40eddfd. 7.3.2 all pass; 9.2.0 counts pass (fail without the conftest fix), goldens skip.
- 2026-10-29: consolidated (Edward OK): pytorch#202597 closed, this PR retargeted to main, single commit de4b8db pushed, body Test section updated.
- 2026-10-29: automated review flagged the pytest==9.1.1 pin from pytorch#202385 in install_inductor_benchmark_deps.sh as stale. Rebased onto origin/main 92264e2 and removed the pin (exact revert of pytorch#202385). TestJunitXml: 9.1.1 venv and 9.2.0 overlay pass (goldens skip); the 7.3.2 golden diffs I saw were my overlay run missing the repo-root pytest.ini; the PR-review agent confirmed old and new conftest match the goldens on 7.3.2 run in place. Not pushed.
- 2026-10-30: Edward approved; pushed 1d11f93 via git (ssh). PR body not yet regenerated: gh on devgpu013 is logged out (~/.config/gh/hosts.yml emptied 2026-10-30 06:20). Body regenerated with ptq pr on 2026-10-30 after gh re-auth.
- 2026-10-30: automated review of 1d11f93: without pytest installed, TestJunitXml errored (subprocess ran, no XML) instead of skipping. setUpClass now raises SkipTest first when pytest is missing. Verified with _junit_provenance patched to "pytest missing" (class skipped, subprocess not run); 9.1.1 venv and 9.2.0 overlay unchanged; lint clean.
- 2026-10-30: per Edward, replaced the provenance-string checks: setUpClass skips when the child stderr has "No module named pytest" (no XML), and the counts test probes `import pytest_rerunfailures` with the child env. Note: earlier PYTHONPATH-overlay runs of TestJunitXml only changed the parent; the child drops PYTHONPATH and used the venv pytest 9.1.1. Re-verified with symlinked throwaway venvs: 9.2.0 counts pass (fail with origin/main conftest), 7.3.2 all pass, no pytest -> class skipped, no rerunfailures -> all skip.
- 2026-10-30: replaced the stderr match and import probe with one child probe (_junit_child_versions, JSON of pytest/rerunfailures versions under _JUNIT_CHILD_ENV): it drives the class skip, has_rerunfailures, and the golden provenance (fixes parent/child mismatch under PYTHONPATH). Child env also drops PYTEST_PLUGINS/PYTEST_DISABLE_PLUGIN_AUTOLOAD. Verified: no pytest -> class skip; no rerunfailures -> 3 skips; 9.2.0 counts pass (fail with origin/main conftest); 7.3.2 all pass; job venv with PYTHONPATH=ov-7.3.2 or PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 -> OK.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue) with human review.*
Pull Request resolved: pytorch#202390
Approved by: https://github.com/nWEIdia, https://github.com/atalman, https://github.com/huydhn, https://github.com/jeanschmidt
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
## Human Note
Claude removed the tb=line branch since it doesn't trigger in CI, and claims the teardown sections stuff never worked even on older pytest. I don't really have a bone in this fight.

## Agent Report
test/conftest.py's RERUNS section (pytorch#86831) prints why each rerun attempt
failed, since pytest-rerunfailures itself only lists reruns. It did so through
four private TerminalReporter methods (`_getcrashline`, `_getfailureheadline`,
`_outrep_summary`, `_handle_teardown_sections`). pytest 9.2 changed
`_handle_teardown_sections` to take a `NodeId`, so the teardown part silently
printed nothing.

This builds the same output from public API: each rerun report's `head_line`,
`toterminal()` (onto `config.get_terminal_writer()`) and `sections`, filtered by
`--show-capture` like pytest's FAILURES section. With `--tb=line` it still
prints one crash line per attempt, now from the public
`rep.longrepr.reprcrash` (falling back to the start of `str(longrepr)`, as
`_getcrashline` did, for a plain-string longrepr such as an xdist worker
crash's).

One part is dropped: the teardown sections. They were looked up by node id, so
they printed the teardown output of every attempt of the test (including the
one that passed) under each failed attempt.

Test plan: a flaky test that prints in call and teardown, a test that fails all
attempts, and a passing test, run with `--reruns=1` under pytest 7.3.2, 9.1.1
and 9.2.0, with `--tb=native` and `--tb=long --color=yes --showlocals`. The new
RERUNS section is identical to the old one except for the dropped teardown
sections. With `--tb=line` (adding a setup error and a `pytrace=False` failure)
under 7.3.2 and 9.2.0, it prints one line per attempt, matching the old
conftest except where the two pytest versions format `reprcrash` differently.

```
cd test && PYTHONPATH=<pytest==$V overlay> python -m pytest -p no:cacheprovider zz_scratch_reruns.py --reruns=1
```

Authored with an AI assistant (Claude).

<details>
<summary>Agent Worklog</summary>

- 2026-10-28: split out of pytorch#202390 (C). Verified on 7.3.2/9.1.1/9.2.0.
- 2026-10-29: kept the `--tb=line` branch (automated review), via public `reprcrash`.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue) with human review.*

Pull Request resolved: pytorch#202412
Approved by: https://github.com/Skylion007
jeffdaily pushed a commit to ROCm/pytorch that referenced this pull request Dec 1, 2026
…est 9.2 (pytorch#202390) (#3936)

## Human Note
I tried getting rid of the custom class entirely but Claude persuaded me
it was useful. So we're just going to subclass from pytest so we can
track upstream more easily.

## Agent Report
### Problem

With pytest 9.2.0, any test run that writes `--junit-xml-reruns` (every
CI test shard) aborts with an INTERNALERROR at the first test's
teardown:

```
File "test/conftest.py", line 254, in pytest_runtest_logreport
  super().pytest_runtest_logreport(report)
File "_pytest/junitxml.py", line 544, in finalize
  reporter = self.node_reporters.pop((node_id, workernode))
KeyError: (NodeId(path='test/test_pytree.py', names=('TestGenericPytree', 'test_aligned_public_apis'), params=None), None)
```

### Root cause

`LogXMLReruns.node_reporter` was a copy of pytest's
`LogXML.node_reporter`. The copy only differed in building a
`_NodeReporterReruns` and stored reporters under `(report.nodeid,
workernode)`, with `nodeid` as a string. pytest 9.2 keys
`node_reporters` by a new `NodeId` dataclass (`report.id`), and
`LogXML.finalize` pops with that key. A `NodeId` never equals a string,
so the pop fails.

### Fix

Call `super().node_reporter(report)` so pytest builds the key and the
reporter in whatever form that version uses, check that
`_NodeReporterReruns` subclasses the returned type, then set the
reporter's `__class__` to `_NodeReporterReruns`. The class docstring now
says it may only override methods, not add state or change how instance
data is represented. The subclass only overrides output methods
(`_prepare_content`, `_write_content`, `append_skipped`) and adds no
state, so switching the class in place is safe, and it removes the copy
of pytest internals that went stale. I also added a docstring to
`_NodeReporterReruns` explaining why it exists. pytest.ini sets
`junit_logging_reruns = all`, and with the stock `_NodeReporter` every
testcase, including passing tests that print nothing, gets a headed
`<system-out>` and `<system-err>` element (skipped tests get both
twice). The subclass writes captured output raw and omits empty streams.
Regenerating the goldens without the subclass shows exactly that
difference. The other option, branching on the pytest version to build
the right key type, would keep the copy and break again the next time
pytest changes the key.

This also reverts pytorch#202385, which pinned `pytest==9.1.1` in the
inductor-benchmarks images as a stopgap for this crash (TorchBench's
requirements pull in an unpinned pytest). The other pytest 9.2 fixes
still open shouldn't affect those images: pytorch#202406 (`--subprocess` test
ids) only matters for the few test modules that `run_test.py` runs with
`--subprocess`, which are CUDA-init and distributed tests the inductor
configs don't run, and pytorch#202412 only restores the teardown part of the
RERUNS terminal summary.

### Test

`TestJunitXml` (test/test_testing.py) used to skip on every pytest
version except the goldens' (the CI pins), so no test could see this
crash. `setUpClass` now records that skip reason instead of raising and
still runs the fixture suite; only the exact golden comparisons skip on
other versions. The tag counts move out of `test_pytest_outcome_shapes`
into `test_pytest_outcome_counts`, which runs on every version and also
checks for INTERNALERROR. On pytest 9.2.0 the counts test passes with
this change and fails without it; on 7.3.2 (the CI pin) all three tests
pass.

#### Where the versions come from

Running the fixture suite on every version means `setUpClass` now
depends on the environment in ways the old blanket skip hid, so the
version checks have to describe the process that actually runs the
suite. That process is a child (`sys.executable -m pytest`) with
`PYTHONPATH` removed, so the parent's view can be wrong. Asking the
parent with `importlib.metadata` would mean:

- With pytest only on the parent's `PYTHONPATH`, the parent sees pytest,
the child doesn't, writes no XML, and `setUpClass` raises instead of
skipping (the case the automated review hit, where pytest is missing
entirely, is the simplest instance).
- With a different pytest on the parent's `PYTHONPATH`, the golden
header check compares the goldens against one version while the child
produces XML with another, and the golden tests fail.

So `setUpClass` first runs a small probe, `_junit_child_versions()`, in
the child's interpreter and environment: it prints the pytest and
pytest-rerunfailures versions (or null) as JSON via
`importlib.metadata`, without importing torch. That one result decides
all three things: the class skips when pytest is missing, the counts
test skips when pytest-rerunfailures is missing, and the golden header
is built from it. The probe costs about 60 ms once per class, next to
roughly 3.5 s for the fixture suite run the class already does. The
alternatives were matching `No module named pytest` in the fixture run's
stderr (covers only the missing-pytest case and leaves the golden
mismatch) or parsing the `plugins:` line from pytest's console header
(fragile, and only saves those 60 ms).

The child also drops `PYTEST_PLUGINS` and
`PYTEST_DISABLE_PLUGIN_AUTOLOAD`, as it already drops `PYTEST_ADDOPTS`,
so it loads the installed plugins as CI does; with autoload off,
pytest-rerunfailures was importable but never loaded and the counts were
wrong.

Checked in throwaway environments that really have each version (a
`PYTHONPATH` overlay only changes the parent):

| Child environment | Result |
|---|---|
| no pytest | class skipped |
| pytest 9.1.1, no pytest-rerunfailures | all three skip |
| pytest 9.2.0 + pytest-rerunfailures 14.0 | counts pass, goldens skip;
counts fail with the old conftest |
| pytest 7.3.2 + pytest-rerunfailures 14.0 | all three pass |
| job venv with pytest 7.3.2 on the parent's `PYTHONPATH`, or
`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` | counts pass, goldens skip |

```
cd test && CUDA_VISIBLE_DEVICES= python test_testing.py -k TestJunitXml
```

### Validation

A minimal test file covering pass, skip, a flaky test that passes on
rerun, a consistent failure with reruns, and an expected failure, run
with `--reruns=2 --junit-xml-reruns`, serially and with `-n 2`, under
pytest 7.3.2 (requirements-ci pin), 9.1.1 and 9.2.0.
pytest-rerunfailures 14.0 and pytest-xdist 3.3.1 are the CI versions. In
all six configurations the testcase/rerun/skipped/failure elements of
the rerun XML match those the unmodified conftest produces under 9.1.1.
Unmodified conftest under 9.2.0 crashes with the KeyError above.

```
PYTHONPATH=<overlay with pytest==$V pytest-rerunfailures==14.0 pytest-xdist==3.3.1> python -m pytest -q -p no:cacheprovider test_mini.py --reruns=2 [-n 2] --junit-xml-reruns=out/r.xml
```

Real test file with each pytest version: 251 passed and 251 testcases in
the XML, no INTERNALERROR. The same command with the old conftest on
9.2.0 crashes after the first test.

```
cd test && PYTHONPATH=<overlay pytest==$V> python -m pytest -q -p no:cacheprovider test_pytree.py --reruns=2 -x --junit-xml-reruns=/tmp/rr/r.xml
```

The existing golden fixture `test/junit_xml_testdata/pytest_suite.py`
(13 outcome shapes, normalized the same way `TestJunitXml` in
`test/test_testing.py` does):
- pytest 7.3.2: the new conftest output matches the committed golden
`expected/pytest.xml`, which was recorded with pytest 7.3.2.
- pytest 9.1.1: the new conftest output is identical to the old
conftest's.
- pytest 9.2.0: the new conftest output is identical to the old
conftest's output under 9.1.1. The old conftest crashes with 81
INTERNALERRORs.

The change was reviewed by two fresh agents (correctness and quality)
before this update; their findings are addressed above.

`lintrunner test/conftest.py` is clean.

<details>
<summary>Agent Worklog</summary>

# Worklog

- 2026-10-28: Diffed pytest 9.1.1 and 9.2.0 `_pytest/junitxml.py`.
`node_reporters` is now keyed by a `NodeId` dataclass (`report.id`);
`finalize` pops `(report.id, workernode)`. conftest's copied
`node_reporter` used string nodeids, so it fails at the first teardown,
not only on reruns.
- Reproduced with a minimal test file under overlays of pytest
7.3.2/9.1.1/9.2.0 on the job venv's torch.
- Fix: delegate to `super().node_reporter` and set `__class__ =
_NodeReporterReruns`. The XML matches the old behavior under all three
versions, serial and with xdist. `test_pytree.py` passes under all
three. lintrunner is clean.
- Golden fixture junit_xml_testdata/pytest_suite.py: new==golden on
7.3.2, new==old on 9.1.1, new on 9.2.0 == old on 9.1.1.
- 2026-10-29: (superseded) C1 test change moved to its own PR, see
below.
- 2026-10-29: split the C1 test change into job
20261029-pytorch-adhoc-7dcc5b (new PR below this one); this branch now
sits on ptq/20261029-pytorch-adhoc-7dcc5b. Counts test passes on 9.2.0
with this fix. Not pushed.
- 2026-10-29: now on the refactor 7879242; this PR moves the version
skip onto the goldens and runs the counts (plus an INTERNALERROR check)
on every version. Commit d334d9d. 9.2.0: counts pass with the fix,
fail without.
- 2026-10-29: shrank the test change: setUpClass unchanged except it
records the version-mismatch reason (golden_skip) instead of raising,
and keeps proc output; goldens skip on it; counts add an INTERNALERROR
check. Commit 980d40eddfd. 7.3.2 all pass; 9.2.0 counts pass (fail
without the conftest fix), goldens skip.
- 2026-10-29: consolidated (Edward OK): pytorch#202597 closed, this PR
retargeted to main, single commit de4b8db pushed, body Test section
updated.
- 2026-10-29: automated review flagged the pytest==9.1.1 pin from
pytorch#202385 in install_inductor_benchmark_deps.sh as stale. Rebased onto
origin/main 92264e2 and removed the pin (exact revert of pytorch#202385).
TestJunitXml: 9.1.1 venv and 9.2.0 overlay pass (goldens skip); the
7.3.2 golden diffs I saw were my overlay run missing the repo-root
pytest.ini; the PR-review agent confirmed old and new conftest match the
goldens on 7.3.2 run in place. Not pushed.
- 2026-10-30: Edward approved; pushed 1d11f93 via git (ssh). PR body
not yet regenerated: gh on devgpu013 is logged out
(~/.config/gh/hosts.yml emptied 2026-10-30 06:20). Body regenerated with
ptq pr on 2026-10-30 after gh re-auth.
- 2026-10-30: automated review of 1d11f93: without pytest installed,
TestJunitXml errored (subprocess ran, no XML) instead of skipping.
setUpClass now raises SkipTest first when pytest is missing. Verified
with _junit_provenance patched to "pytest missing" (class skipped,
subprocess not run); 9.1.1 venv and 9.2.0 overlay unchanged; lint clean.
- 2026-10-30: per Edward, replaced the provenance-string checks:
setUpClass skips when the child stderr has "No module named pytest" (no
XML), and the counts test probes `import pytest_rerunfailures` with the
child env. Note: earlier PYTHONPATH-overlay runs of TestJunitXml only
changed the parent; the child drops PYTHONPATH and used the venv pytest
9.1.1. Re-verified with symlinked throwaway venvs: 9.2.0 counts pass
(fail with origin/main conftest), 7.3.2 all pass, no pytest -> class
skipped, no rerunfailures -> all skip.
- 2026-10-30: replaced the stderr match and import probe with one child
probe (_junit_child_versions, JSON of pytest/rerunfailures versions
under _JUNIT_CHILD_ENV): it drives the class skip, has_rerunfailures,
and the golden provenance (fixes parent/child mismatch under
PYTHONPATH). Child env also drops
PYTEST_PLUGINS/PYTEST_DISABLE_PLUGIN_AUTOLOAD. Verified: no pytest ->
class skip; no rerunfailures -> 3 skips; 9.2.0 counts pass (fail with
origin/main conftest); 7.3.2 all pass; job venv with PYTHONPATH=ov-7.3.2
or PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 -> OK.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue)
with human review.*
Pull Request resolved: pytorch#202390
Approved by: https://github.com/nWEIdia, https://github.com/atalman,
https://github.com/huydhn, https://github.com/jeanschmidt


(cherry picked from commit 15e3725)

Co-authored-by: Edward Z. Yang <[email protected]>
jeffdaily pushed a commit to ROCm/pytorch that referenced this pull request Dec 1, 2026
…est 9.2 (pytorch#202390) (#3935)

## Human Note
I tried getting rid of the custom class entirely but Claude persuaded me
it was useful. So we're just going to subclass from pytest so we can
track upstream more easily.

## Agent Report
### Problem

With pytest 9.2.0, any test run that writes `--junit-xml-reruns` (every
CI test shard) aborts with an INTERNALERROR at the first test's
teardown:

```
File "test/conftest.py", line 254, in pytest_runtest_logreport
  super().pytest_runtest_logreport(report)
File "_pytest/junitxml.py", line 544, in finalize
  reporter = self.node_reporters.pop((node_id, workernode))
KeyError: (NodeId(path='test/test_pytree.py', names=('TestGenericPytree', 'test_aligned_public_apis'), params=None), None)
```

### Root cause

`LogXMLReruns.node_reporter` was a copy of pytest's
`LogXML.node_reporter`. The copy only differed in building a
`_NodeReporterReruns` and stored reporters under `(report.nodeid,
workernode)`, with `nodeid` as a string. pytest 9.2 keys
`node_reporters` by a new `NodeId` dataclass (`report.id`), and
`LogXML.finalize` pops with that key. A `NodeId` never equals a string,
so the pop fails.

### Fix

Call `super().node_reporter(report)` so pytest builds the key and the
reporter in whatever form that version uses, check that
`_NodeReporterReruns` subclasses the returned type, then set the
reporter's `__class__` to `_NodeReporterReruns`. The class docstring now
says it may only override methods, not add state or change how instance
data is represented. The subclass only overrides output methods
(`_prepare_content`, `_write_content`, `append_skipped`) and adds no
state, so switching the class in place is safe, and it removes the copy
of pytest internals that went stale. I also added a docstring to
`_NodeReporterReruns` explaining why it exists. pytest.ini sets
`junit_logging_reruns = all`, and with the stock `_NodeReporter` every
testcase, including passing tests that print nothing, gets a headed
`<system-out>` and `<system-err>` element (skipped tests get both
twice). The subclass writes captured output raw and omits empty streams.
Regenerating the goldens without the subclass shows exactly that
difference. The other option, branching on the pytest version to build
the right key type, would keep the copy and break again the next time
pytest changes the key.

This also reverts pytorch#202385, which pinned `pytest==9.1.1` in the
inductor-benchmarks images as a stopgap for this crash (TorchBench's
requirements pull in an unpinned pytest). The other pytest 9.2 fixes
still open shouldn't affect those images: pytorch#202406 (`--subprocess` test
ids) only matters for the few test modules that `run_test.py` runs with
`--subprocess`, which are CUDA-init and distributed tests the inductor
configs don't run, and pytorch#202412 only restores the teardown part of the
RERUNS terminal summary.

### Test

`TestJunitXml` (test/test_testing.py) used to skip on every pytest
version except the goldens' (the CI pins), so no test could see this
crash. `setUpClass` now records that skip reason instead of raising and
still runs the fixture suite; only the exact golden comparisons skip on
other versions. The tag counts move out of `test_pytest_outcome_shapes`
into `test_pytest_outcome_counts`, which runs on every version and also
checks for INTERNALERROR. On pytest 9.2.0 the counts test passes with
this change and fails without it; on 7.3.2 (the CI pin) all three tests
pass.

#### Where the versions come from

Running the fixture suite on every version means `setUpClass` now
depends on the environment in ways the old blanket skip hid, so the
version checks have to describe the process that actually runs the
suite. That process is a child (`sys.executable -m pytest`) with
`PYTHONPATH` removed, so the parent's view can be wrong. Asking the
parent with `importlib.metadata` would mean:

- With pytest only on the parent's `PYTHONPATH`, the parent sees pytest,
the child doesn't, writes no XML, and `setUpClass` raises instead of
skipping (the case the automated review hit, where pytest is missing
entirely, is the simplest instance).
- With a different pytest on the parent's `PYTHONPATH`, the golden
header check compares the goldens against one version while the child
produces XML with another, and the golden tests fail.

So `setUpClass` first runs a small probe, `_junit_child_versions()`, in
the child's interpreter and environment: it prints the pytest and
pytest-rerunfailures versions (or null) as JSON via
`importlib.metadata`, without importing torch. That one result decides
all three things: the class skips when pytest is missing, the counts
test skips when pytest-rerunfailures is missing, and the golden header
is built from it. The probe costs about 60 ms once per class, next to
roughly 3.5 s for the fixture suite run the class already does. The
alternatives were matching `No module named pytest` in the fixture run's
stderr (covers only the missing-pytest case and leaves the golden
mismatch) or parsing the `plugins:` line from pytest's console header
(fragile, and only saves those 60 ms).

The child also drops `PYTEST_PLUGINS` and
`PYTEST_DISABLE_PLUGIN_AUTOLOAD`, as it already drops `PYTEST_ADDOPTS`,
so it loads the installed plugins as CI does; with autoload off,
pytest-rerunfailures was importable but never loaded and the counts were
wrong.

Checked in throwaway environments that really have each version (a
`PYTHONPATH` overlay only changes the parent):

| Child environment | Result |
|---|---|
| no pytest | class skipped |
| pytest 9.1.1, no pytest-rerunfailures | all three skip |
| pytest 9.2.0 + pytest-rerunfailures 14.0 | counts pass, goldens skip;
counts fail with the old conftest |
| pytest 7.3.2 + pytest-rerunfailures 14.0 | all three pass |
| job venv with pytest 7.3.2 on the parent's `PYTHONPATH`, or
`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` | counts pass, goldens skip |

```
cd test && CUDA_VISIBLE_DEVICES= python test_testing.py -k TestJunitXml
```

### Validation

A minimal test file covering pass, skip, a flaky test that passes on
rerun, a consistent failure with reruns, and an expected failure, run
with `--reruns=2 --junit-xml-reruns`, serially and with `-n 2`, under
pytest 7.3.2 (requirements-ci pin), 9.1.1 and 9.2.0.
pytest-rerunfailures 14.0 and pytest-xdist 3.3.1 are the CI versions. In
all six configurations the testcase/rerun/skipped/failure elements of
the rerun XML match those the unmodified conftest produces under 9.1.1.
Unmodified conftest under 9.2.0 crashes with the KeyError above.

```
PYTHONPATH=<overlay with pytest==$V pytest-rerunfailures==14.0 pytest-xdist==3.3.1> python -m pytest -q -p no:cacheprovider test_mini.py --reruns=2 [-n 2] --junit-xml-reruns=out/r.xml
```

Real test file with each pytest version: 251 passed and 251 testcases in
the XML, no INTERNALERROR. The same command with the old conftest on
9.2.0 crashes after the first test.

```
cd test && PYTHONPATH=<overlay pytest==$V> python -m pytest -q -p no:cacheprovider test_pytree.py --reruns=2 -x --junit-xml-reruns=/tmp/rr/r.xml
```

The existing golden fixture `test/junit_xml_testdata/pytest_suite.py`
(13 outcome shapes, normalized the same way `TestJunitXml` in
`test/test_testing.py` does):
- pytest 7.3.2: the new conftest output matches the committed golden
`expected/pytest.xml`, which was recorded with pytest 7.3.2.
- pytest 9.1.1: the new conftest output is identical to the old
conftest's.
- pytest 9.2.0: the new conftest output is identical to the old
conftest's output under 9.1.1. The old conftest crashes with 81
INTERNALERRORs.

The change was reviewed by two fresh agents (correctness and quality)
before this update; their findings are addressed above.

`lintrunner test/conftest.py` is clean.

<details>
<summary>Agent Worklog</summary>

# Worklog

- 2026-10-28: Diffed pytest 9.1.1 and 9.2.0 `_pytest/junitxml.py`.
`node_reporters` is now keyed by a `NodeId` dataclass (`report.id`);
`finalize` pops `(report.id, workernode)`. conftest's copied
`node_reporter` used string nodeids, so it fails at the first teardown,
not only on reruns.
- Reproduced with a minimal test file under overlays of pytest
7.3.2/9.1.1/9.2.0 on the job venv's torch.
- Fix: delegate to `super().node_reporter` and set `__class__ =
_NodeReporterReruns`. The XML matches the old behavior under all three
versions, serial and with xdist. `test_pytree.py` passes under all
three. lintrunner is clean.
- Golden fixture junit_xml_testdata/pytest_suite.py: new==golden on
7.3.2, new==old on 9.1.1, new on 9.2.0 == old on 9.1.1.
- 2026-10-29: (superseded) C1 test change moved to its own PR, see
below.
- 2026-10-29: split the C1 test change into job
20261029-pytorch-adhoc-7dcc5b (new PR below this one); this branch now
sits on ptq/20261029-pytorch-adhoc-7dcc5b. Counts test passes on 9.2.0
with this fix. Not pushed.
- 2026-10-29: now on the refactor 7879242; this PR moves the version
skip onto the goldens and runs the counts (plus an INTERNALERROR check)
on every version. Commit d334d9d. 9.2.0: counts pass with the fix,
fail without.
- 2026-10-29: shrank the test change: setUpClass unchanged except it
records the version-mismatch reason (golden_skip) instead of raising,
and keeps proc output; goldens skip on it; counts add an INTERNALERROR
check. Commit 980d40eddfd. 7.3.2 all pass; 9.2.0 counts pass (fail
without the conftest fix), goldens skip.
- 2026-10-29: consolidated (Edward OK): pytorch#202597 closed, this PR
retargeted to main, single commit de4b8db pushed, body Test section
updated.
- 2026-10-29: automated review flagged the pytest==9.1.1 pin from
pytorch#202385 in install_inductor_benchmark_deps.sh as stale. Rebased onto
origin/main 92264e2 and removed the pin (exact revert of pytorch#202385).
TestJunitXml: 9.1.1 venv and 9.2.0 overlay pass (goldens skip); the
7.3.2 golden diffs I saw were my overlay run missing the repo-root
pytest.ini; the PR-review agent confirmed old and new conftest match the
goldens on 7.3.2 run in place. Not pushed.
- 2026-10-30: Edward approved; pushed 1d11f93 via git (ssh). PR body
not yet regenerated: gh on devgpu013 is logged out
(~/.config/gh/hosts.yml emptied 2026-10-30 06:20). Body regenerated with
ptq pr on 2026-10-30 after gh re-auth.
- 2026-10-30: automated review of 1d11f93: without pytest installed,
TestJunitXml errored (subprocess ran, no XML) instead of skipping.
setUpClass now raises SkipTest first when pytest is missing. Verified
with _junit_provenance patched to "pytest missing" (class skipped,
subprocess not run); 9.1.1 venv and 9.2.0 overlay unchanged; lint clean.
- 2026-10-30: per Edward, replaced the provenance-string checks:
setUpClass skips when the child stderr has "No module named pytest" (no
XML), and the counts test probes `import pytest_rerunfailures` with the
child env. Note: earlier PYTHONPATH-overlay runs of TestJunitXml only
changed the parent; the child drops PYTHONPATH and used the venv pytest
9.1.1. Re-verified with symlinked throwaway venvs: 9.2.0 counts pass
(fail with origin/main conftest), 7.3.2 all pass, no pytest -> class
skipped, no rerunfailures -> all skip.
- 2026-10-30: replaced the stderr match and import probe with one child
probe (_junit_child_versions, JSON of pytest/rerunfailures versions
under _JUNIT_CHILD_ENV): it drives the class skip, has_rerunfailures,
and the golden provenance (fixes parent/child mismatch under
PYTHONPATH). Child env also drops
PYTEST_PLUGINS/PYTEST_DISABLE_PLUGIN_AUTOLOAD. Verified: no pytest ->
class skip; no rerunfailures -> 3 skips; 9.2.0 counts pass (fail with
origin/main conftest); 7.3.2 all pass; job venv with PYTHONPATH=ov-7.3.2
or PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 -> OK.

</details>

---
*This PR was generated by [ptq](https://github.com/drisspg/pt_job_queue)
with human review.*
Pull Request resolved: pytorch#202390
Approved by: https://github.com/nWEIdia, https://github.com/atalman,
https://github.com/huydhn, https://github.com/jeanschmidt


(cherry picked from commit 15e3725)

Co-authored-by: Edward Z. Yang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

autoland ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes in progress PR is being worked on by the author, until the automated review accepts it mergedog mergedog is watching this PR mergedX1 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants