Skip to content

[torchci] Add a pytest plugin for test run reports - #200022

Closed
georgehong wants to merge 15 commits into
gh/georgehong/9/basefrom
gh/georgehong/9/head
Closed

georgehong wants to merge 15 commits into
gh/georgehong/9/basefrom
gh/georgehong/9/head

Conversation

@georgehong

@georgehong georgehong commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary
Adds a pytest plugin under torch/testing/_internal/torchci that writes one JSONL test run report per test process, for ingestion into the ClickHouse tests tables (schema: pytorch/test-infra jathu/ci-tables). Each report is a report line with the environment from #200339, then one line per test run.

  • It lives under torch/testing/_internal because every test process must import it. tools/ isn't on their sys.path, and adding the repo root would shadow the installed torch. It can move to a test-infra package once other repos use it.
  • report.py is the format (standard library only). plugin.py is the writer: it derives each test's identity from its pytest item, and it turns itself off on its first error so it never changes a test's outcome. environment.py ([torchci] Capture the test environment for test run reports #200339) is the only PyTorch-aware module.

Testing
python test/torchci/test_testing.py runs pytest with the plugin on test/junit_xml_testdata/pytest_suite.py and the fixture files in test/torchci/testdata/ and checks the lines it writes, plus unit tests of the helpers.

e2e:

cd test  # in a venv where torch imports
python -m pytest junit_xml_testdata/pytest_suite.py -p torch.testing._internal.torchci.plugin \
    --torchci-report-prefix=/tmp/torchci-demo/pytest_suite -p no:cacheprovider -q
jq . /tmp/torchci-demo/pytest_suite-*.report.jsonl

Authored with the help of an AI assistant (Claude).

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit d839896 with merge base 816fc3c (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New feature: adds a ~230-line pytest plugin torch/testing/_internal/torchci/plugin.py and format module report.py, outside every trivial class
    • ReportWriter._logreport holds new outcome, rerun, xdist and subtest logic whose design a reviewer would question
  • Socialization
    • README.md defines schema 0.1 of a JSONL format meant for the ClickHouse tests.* tables, a format external readers will parse
  • Scope
    • Diff also adds six fixture files under test/torchci/testdata/, including a conftest.py that monkeypatches the plugin, plus two subprocess-driven test classes in test/torchci/test_testing.py

reason: not_trivial
Reviewed commit: d839896

Inference job

🐛 Report a wrong verdict

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

[ghstack-poisoned]
georgehong added a commit that referenced this pull request Oct 7, 2026
Writes one JSONL file per test process for the tests.* tables
(pytorch/test-infra#8849): a report line, then a run line per test execution.
Nothing registers it yet.

It lives in torch/testing/_internal because every test process must import it,
including the pytest processes that run C++ tests.

Review order: report.py (format, test identity), environment.py (machine, flags,
properties; the only PyTorch-aware module), plugin.py (the writer, which turns
itself off on its first error so it never changes an outcome).

Test Plan:

```
python test/test_testing.py -k TestReport -k TestJunitXml
lintrunner
```

Authored with the help of an AI assistant (Claude).

ghstack-source-id: d4e8f0e
Pull-Request: #200022
[ghstack-poisoned]
georgehong added a commit that referenced this pull request Oct 7, 2026
Writes one JSONL file per test process for the tests.* tables
(pytorch/test-infra#8849): a report line, then a run line per test execution.
Nothing registers it yet.

It lives in torch/testing/_internal because every test process must import it,
including the pytest processes that run C++ tests.

Review order: report.py (format, test identity), environment.py (machine, flags,
properties; the only PyTorch-aware module), plugin.py (the writer, which turns
itself off on its first error so it never changes an outcome).

Test Plan:

```
python test/test_testing.py -k TestReport -k TestJunitXml
lintrunner
```

Authored with the help of an AI assistant (Claude).

ghstack-source-id: 315665b
Pull-Request: #200022
[ghstack-poisoned]
@georgehong
georgehong requested review from huydhn and jathu October 7, 2026 23:18
[ghstack-poisoned]
@georgehong georgehong added the topic: not user facing topic category label Oct 7, 2026
[ghstack-poisoned]
@georgehong

Copy link
Copy Markdown
Contributor Author

Latest push

  • Factory-made tests (e.g. create_test_func) no longer share the factory's inner name (test) as declared_case_name; they fall back to the collected name, so their device/dtype variants aren't grouped yet (follow-up)
  • A skip in teardown no longer replaces a failure's outcome_summary
  • README and include_in_repro docs match the code
  • Tests for env_var_values, writer failures inside logreport and an xdist worker, factory names, and skip after failure

@georgehong
georgehong marked this pull request as ready for review October 8, 2026 00:29
@georgehong
georgehong requested a review from a team as a code owner October 8, 2026 00:29
@georgehong georgehong added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 8, 2026
Comment thread torch/testing/_internal/common_utils.py Outdated
Comment on lines +273 to +276
# Value in effect of every include_in_repro env var: "1"/"0" for flags (implied
# included), the parsed value for settings ("" if unset). Read by
# torchci/environment.py.
env_var_values: dict = {}

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.

I think I understand the reason for this, but I don't think we should store this as a property. Instead, can we derive this via function?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you help me understand the motivation for turning this into a function? While we can read the env vars later on, we'd still need to track which ones we care about (PYTORCH_TEST_WITH_ASAN, PYTORCH_TEST_WITH_CROSSREF, ...) and how each is computed (e.g. PYTORCH_TEST_WITH_DYNAMO is implied by inductor). def_flag already does this for repro_env_vars, so caching the value there seemed reasonable.

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.

I agree the report needs more information than repro_env_vars currently contains, including defaults and implied flags. My concern is maintaining two separate dictionaries for different views of the same configuration.

Could def_flag/def_setting populate a single registry, then have functions derive both the repro command and the reporting dictionary from it? That would preserve the existing parsing and implication logic while avoiding separately maintaining repro_env_vars and env_var_values. Here’s an example: P2540760629

Thinking about it more, I think what you have here is also ok, so feel free to ignore

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the current size of the PR, could we defer the change to TestEnvironment? I do like the suggestion though.

Comment on lines +92 to +100
def _json_safe(value: Any) -> Any:
# Escape lone surrogates, which UTF-8 can't encode.
if isinstance(value, str):
return value.encode("utf-8", "backslashreplace").decode()
if isinstance(value, dict):
return {_json_safe(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [_json_safe(item) for item in value]
return value

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.

json.dumps doesn't handle this?

Comment on lines +86 to +87
"started_at": int(started * 1000),
"ended_at": int(ended * 1000),

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.

If we pass started as a datetime, we don't need to calculate this ourselves

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we use datetime, I think we'd have to serialize that to JSON. pytest start/stop are already epoch floats, so this seemed most straightforward, and users inspecting this could use jq utilities?

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.

The database itself expects a datetime though, so we will eventually need to convert it back

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ClickHouse provides fromUnixTimestamp64Milli(..., 'UTC'), which I think would work well here and keep the JSON writing simple.

"suite": test.suite,
"case_name": test.case_name,
"language": test.language,
"declared_case_name": declared_case_name or fallback_declared_case_name(nodeid),

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.

Do we really want to get into the business of determining the declared name? I think this can get messy right? For example, I don't think we use [ as partitions for everything?

Why would declared_case_name every be empty?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the scope of this PR, it shouldn't be empty.



def _job_id() -> int:
# The workflow's job-id lookup can fail.

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.

How can this fail?

@georgehong georgehong Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setup's get_workflow_job_id.py swallows GitHub API errors (we've seen 502s on the jobs endpoint) and leaves JOB_ID empty, and it's unset outside CI. This can propagate to the zipped filenames, unfortunately. Will describe that more precisely in the comment, and this may be propagate as a source of missing data and will need to be addressed/have redundancy.

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.

@georgehong georgehong Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think GITHUB_JOB is a text name, but it looks like the following might work if workflows are updated:

  JOB_ID: ${{ job.check_run_id }}

As a follow-up, maybe the get_workflow_job_id.py file can be removed as a dep

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.

Yup, let's create a follow up task

def report_path(directory: str, report_uuid: str) -> str:
"""``<directory>/<directory name>-<uuid>.jsonl``."""
name = os.path.basename(os.path.normpath(directory))
return os.path.join(directory, f"{name}-{report_uuid}{REPORT_SUFFIX}")

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.

If it's already in the directory, why are we prefixing it with the directory name?

Also, I thought the report would be <uuid>.report.jsonl

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed async, will prefer flatter structure, keeping file name for easy access as <directory>/file-<uuid>.report.jsonl. In the S3 prototype, it's .report.zip to narrow down on the lambda trigger, but we can use this more generally.

file: str
suite: str
case_name: str
language: str

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.

Shouldn't we store declared_case_name here too?

Comment on lines +24 to +31
def identity(nodeid: str) -> TestId:
"""Launched file, innermost class and parametrized name of a node id. Classes
that test_jit.py imports from jit/ keep test_jit.py as their file."""
path, _, rest = nodeid.partition("::")
head, bracket, params = rest.partition("[")
parts = head.split("::")
suite = parts[-2] if len(parts) > 1 else ""
return TestId(path, suite, parts[-1] + bracket + params, "python")

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.

Do you know if there is some builtin python/pytest function that can do this for us? This seems finicky.

I asked Codex and it also suggested relying more on the function objects to get this data:

import inspect
import pytest

from torch.testing._internal.torchci.report import TestId


def identity(item: pytest.Function) -> TestId:
    """Extract identity and the best available source name for a Python test."""
    module = item.getparent(pytest.Module)
    if module is None:
        raise ValueError("Expected a Python test with a module collector")

    cls = item.getparent(pytest.Class)
    case_name = item.name
    declared_case_name = item.originalname or case_name

    # originalname handles pytest parameters. Unwrap decorators to recover source
    # names for PyTorch-generated device/dtype variants, retaining the fallback
    # when the name is ambiguous or introspection fails.
    try:
        function = inspect.unwrap(item.obj)
        name = function.__name__
        qualname = getattr(function, "__qualname__", "<locals>")

        # Factory-generated functions can share an unrelated inner name.
        if "<locals>" not in qualname and (
            case_name == name
            or case_name.startswith((name + "_", name + "["))
        ):
            declared_case_name = name
    except Exception:
        pass

    return TestId(
        file=module.nodeid,
        suite=cls.name if cls is not None else "",
        case_name=case_name,
        language="python",
        declared_case_name=declared_case_name,
    )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think there's a public-facing utility to help with parsing the nodeids, but it looks like a pattern that's used in pytest. PR 1 is scoped only for Python files, but we'll need to support C++ tests as well, and oftentimes, the writer only has access to the nodeid.

In your snippet, it also looks like the declared_case_name extraction matches the current implementation in _item_declared_case_name closely.

Comment on lines +18 to +31
### Report line

| Field | Type | Meaning |
|---|---|---|
| `type` | string | `"report"` |
| `schema_version` | string | `"0.1"` |
| `repo` | string | `GITHUB_REPOSITORY`, or `""` outside CI |
| `github_workflow_job_id` | int | Numeric `JOB_ID`, or `0` when unset or invalid |
| `report_uuid` | string | The uuid4 in the file name |
| `environment` | object | Machine identity fields listed below |
| `flags` | object | `TestEnvironment` flags and settings, described below, sorted by env var |
| `properties` | object | Nonempty report properties listed below |

`environment` contains these fields in order:

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.

nit: what is the point of repeating the schema in the readme? I think just have these as comments in the living with the code is better for humans and agents (the types and field names are already there)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found it helpful in the stack to track what's implemented so far, as well as provide a high-level view in one place of what the jsonl reports look like. I'm happy to remove it as well.


def _accelerator() -> tuple[str, str]:
if torch.version.cuda:
return "cuda", ".".join(torch.version.cuda.split(".")[:2])

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.

Wait, why are we doing all of this? Why can't we just use torch.version.cuda?

if accelerator == "xpu":
return torch.xpu.device_count()
if accelerator == "mps":
return int(torch.backends.mps.is_available())

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.

Why can't we use torch.mps.device_count()? Also I think we can simplify this:

def _device_count(accelerator: str) -> int:
    if accelerator == "cpu":
        return 0

    backend = "cuda" if accelerator == "rocm" else accelerator
    try:
        # Explicit selection avoids global accelerator detection.
        return torch.get_device_module(backend).device_count()
    except Exception:
        return 0

I'm still curious why we need to make the exception for rocm — I wonder if it's because we aren't using a torch built against rocm, so the agents are unable to see the path? Please look into it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the code snippet, will incorporate.

why we need to make the exception for rocm

I believe this is described here: https://docs.pytorch.org/docs/2.14/notes/hip.html#hip-interfaces-reuse-the-cuda-interfaces

cuda0 = torch.device('cuda:0') # 'rocm' or 'hip' are not valid, use 'cuda'

@georgehong
georgehong marked this pull request as draft October 8, 2026 21:14
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@georgehong
georgehong marked this pull request as ready for review October 9, 2026 04:30
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #200023

pytorchmergebot pushed a commit that referenced this pull request Oct 9, 2026
**Summary**
Adds `torch/testing/_internal/torchci/environment.py`, which captures what a test run report records about its process: machine identity (OS, CPU, Python, compiler, accelerator, devices), `TestEnvironment` flags, and properties. Nothing calls it yet; #200022 writes it into each report.
 - `TestEnvironment.env_var_values` (`common_utils.py`) holds each `include_in_repro` flag and setting as its env var is set, e.g. `PYTORCH_CUDA_ALLOC_CONF: expandable_segments:True`. Unset ones are `""`, except a flag that's on by default or implication, which is `"1"`.
 - `capture()` runs in the test process before its tests, so it creates no device context (device names come from NVML, amdsmi or xpu-smi) and doesn't call `torch.accelerator`.

**Testing**
Unit tests added in this PR.

Authored with the help of an AI assistant (Claude).
Pull Request resolved: #200339
Approved by: https://github.com/jathu
pytorchmergebot pushed a commit that referenced this pull request Oct 9, 2026
…200023)

**Overview**
`--save-torchci-reports DIR` registers the torchci plugin, which writes each test process's report to `<DIR>/<file>-<uuid>.report.jsonl`. Off by default. *run_test.py* only forwards the flag when the installed torch has the writer, since tests sometimes run against a nightly.

**Test Plan**
```
python test/run_test.py -i test_type_info --save-torchci-reports /tmp/test/torchci-reports/
```

Authored with the help of an AI assistant (Claude).
Pull Request resolved: #200023
Approved by: https://github.com/jathu
ghstack dependencies: #200339, #200022
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…200339)

**Summary**
Adds `torch/testing/_internal/torchci/environment.py`, which captures what a test run report records about its process: machine identity (OS, CPU, Python, compiler, accelerator, devices), `TestEnvironment` flags, and properties. Nothing calls it yet; pytorch#200022 writes it into each report.
 - `TestEnvironment.env_var_values` (`common_utils.py`) holds each `include_in_repro` flag and setting as its env var is set, e.g. `PYTORCH_CUDA_ALLOC_CONF: expandable_segments:True`. Unset ones are `""`, except a flag that's on by default or implication, which is `"1"`.
 - `capture()` runs in the test process before its tests, so it creates no device context (device names come from NVML, amdsmi or xpu-smi) and doesn't call `torch.accelerator`.

**Testing**
Unit tests added in this PR.

Authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#200339
Approved by: https://github.com/jathu
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
**Summary**
Adds a pytest plugin under `torch/testing/_internal/torchci` that writes one JSONL test run report per test process, for ingestion into the ClickHouse tests tables (schema: pytorch/test-infra `jathu/ci-tables`). Each report is a report line with the environment from pytorch#200339, then one line per test run.
- It lives under `torch/testing/_internal` because every test process must import it. `tools/` isn't on their `sys.path`, and adding the repo root would shadow the installed torch. It can move to a test-infra package once other repos use it.
- `report.py` is the format (standard library only). `plugin.py` is the writer: it derives each test's identity from its pytest item, and it turns itself off on its first error so it never changes a test's outcome. `environment.py` (pytorch#200339) is the only PyTorch-aware module.

**Testing**
`python test/torchci/test_testing.py` runs pytest with the plugin on `test/junit_xml_testdata/pytest_suite.py` and the fixture files in `test/torchci/testdata/` and checks the lines it writes, plus unit tests of the helpers.

*e2e*:
```
cd test  # in a venv where torch imports
python -m pytest junit_xml_testdata/pytest_suite.py -p torch.testing._internal.torchci.plugin \
    --torchci-report-prefix=/tmp/torchci-demo/pytest_suite -p no:cacheprovider -q
jq . /tmp/torchci-demo/pytest_suite-*.report.jsonl
```

Authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#200022
Approved by: https://github.com/jathu
ghstack dependencies: pytorch#200339
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ytorch#200023)

**Overview**
`--save-torchci-reports DIR` registers the torchci plugin, which writes each test process's report to `<DIR>/<file>-<uuid>.report.jsonl`. Off by default. *run_test.py* only forwards the flag when the installed torch has the writer, since tests sometimes run against a nightly.

**Test Plan**
```
python test/run_test.py -i test_type_info --save-torchci-reports /tmp/test/torchci-reports/
```

Authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#200023
Approved by: https://github.com/jathu
ghstack dependencies: pytorch#200339, pytorch#200022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants