Repository navigation
[torchci] Add a pytest plugin for test run reports - #200022
georgehong wants to merge 15 commits into
Conversation
🔗 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 FailuresAs of commit d839896 with merge base 816fc3c ( 🟡 GREEN LIGHT - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
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
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
|
Latest push
|
| # 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 = {} |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Given the current size of the PR, could we defer the change to TestEnvironment? I do like the suggestion though.
| 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 |
There was a problem hiding this comment.
json.dumps doesn't handle this?
| "started_at": int(started * 1000), | ||
| "ended_at": int(ended * 1000), |
There was a problem hiding this comment.
If we pass started as a datetime, we don't need to calculate this ourselves
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
The database itself expects a datetime though, so we will eventually need to convert it back
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
In the scope of this PR, it shouldn't be empty.
|
|
||
|
|
||
| def _job_id() -> int: | ||
| # The workflow's job-id lookup can fail. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Wait, what — GitHub provides these as envvars no? https://docs.github.com/en/actions/reference/workflows-and-actions/variables#default-environment-variables
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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}") |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Shouldn't we store declared_case_name here too?
| 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") |
There was a problem hiding this comment.
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,
)There was a problem hiding this comment.
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.
| ### 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: |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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]) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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 0I'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.
There was a problem hiding this comment.
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'
|
Starting merge as part of PR stack under #200023 |
**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
…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
…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
**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
…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
Stack from ghstack (oldest at bottom):
Summary
Adds a pytest plugin under
torch/testing/_internal/torchcithat writes one JSONL test run report per test process, for ingestion into the ClickHouse tests tables (schema: pytorch/test-infrajathu/ci-tables). Each report is a report line with the environment from #200339, then one line per test run.torch/testing/_internalbecause every test process must import it.tools/isn't on theirsys.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.pyis the format (standard library only).plugin.pyis 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.pyruns pytest with the plugin ontest/junit_xml_testdata/pytest_suite.pyand the fixture files intest/torchci/testdata/and checks the lines it writes, plus unit tests of the helpers.e2e:
Authored with the help of an AI assistant (Claude).