Repository navigation
[dynamo] Add offline sync check for test/cpython/v3_13 *.diff files (… - #191767
PrabinDevkota wants to merge 12 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/191767
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit ae1e59b with merge base 3601a49 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
| # Fallback for older adapted files missing the source URL comment. | ||
| rel = py_path.relative_to(CPYTHON_DIR).as_posix() | ||
| if rel.startswith("test_unittest/"): | ||
| tag, upstream = "v3.13.5", f"Lib/test/{rel}" |
There was a problem hiding this comment.
Could we avoid hardcoding the tag here??
| proc = subprocess.run(cmd, cwd=root, capture_output=True, text=True) | ||
| if proc.returncode != 0: | ||
| # Retry with whitespace tolerance for older noisy hunks. | ||
| cmd2 = ["git", "apply", "--ignore-whitespace"] |
There was a problem hiding this comment.
do we need --ignore-whitespace?
| header (e.g. v3.13.5); tags may differ across files. Do not assume a single | ||
| global tag from this note alone. |
There was a problem hiding this comment.
I think we should stick with a single tag. Could you update all test files to use the same tag?
|
This is the review from claude: |
|
Thanks @guilhermeleobas — went through the review and cleaned this up. |
guilhermeleobas
left a comment
There was a problem hiding this comment.
Many thanks for working on this @PrabinDevkota. I've made another review.
| raise AssertionError("test_bool.py pair not found") | ||
|
|
||
|
|
||
| class CPythonDiffSyncTests(unittest.TestCase): |
There was a problem hiding this comment.
This should use torch.testing._internal.common_utils.TestCase
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
There was a problem hiding this comment.
Use run_tests() instead
There was a problem hiding this comment.
Move this file to /test/cpython?
| try: | ||
| pristine = diff_sync._git_apply( | ||
| drifted, diff_text, repo_rel, reverse=True | ||
| ) | ||
| except RuntimeError: | ||
| return # reverse-apply rejecting drifted content is a valid failure mode |
There was a problem hiding this comment.
Do we need to catch the RuntimeError? Or we should let it propagate?
| for diff_path in sorted(CPYTHON_DIR.rglob("*.diff")): | ||
| py_path = diff_path.with_suffix(".py") | ||
| if not py_path.is_file(): | ||
| raise FileNotFoundError(f"diff without matching .py: {diff_path}") |
There was a problem hiding this comment.
I think you should return a LintMessage here with the severity=LintSeverity.ERROR?
There was a problem hiding this comment.
This file should be on /tools/ I think
| def test_all_pairs_share_single_upstream_tag(self): | ||
| tags = {diff_sync.parse_header(py)[0] for py, _ in diff_sync.iter_diff_pairs()} | ||
| self.assertEqual(tags, {"v3.13.5"}, tags) |
There was a problem hiding this comment.
We plan to migrate the tests for Python 3.15 once it is released. Hardcoding v3.13.5 might not be a good idea here
| def _load_diff_sync(): | ||
| path = Path(__file__).resolve().parent / "cpython" / "diff_sync.py" | ||
| spec = importlib.util.spec_from_file_location("torch_cpython_diff_sync", path) | ||
| assert spec is not None and spec.loader is not None |
There was a problem hiding this comment.
use raise AssertionError instead of plain assert
| import sys | ||
| import tempfile | ||
| from pathlib import Path | ||
| from types import ModuleType |
There was a problem hiding this comment.
>>> Lint for tools/regenerate_cpython_diffs.py:
Warning (RUFF) TC003
Move standard library import `types.ModuleType` into a type-checking
block.
See https://beta.ruff.rs/docs/rules/.
To disable, use ` # noqa: TC003`
14 |import sys
15 |import tempfile
16 |from pathlib import Path
>>> 17 |from types import ModuleType
18 |
19 |
20 |REPO_ROOT = Path(__file__).resolve().parents[1]
There was a problem hiding this comment.
Claude suggested we might not need this json file:
Alternative: drop upstream_manifest.json, use git diff --full-index
The problem being solved
Each adapted test has two checked-in files:
test_bool.py— the adapted version (upstream + Dynamo modifications)test_bool.diff— supposedly the exact delta between pristine upstream
test_bool.py(from CPython tag v3.13.5) and the adapted file
The invariant: applying the .diff to the pristine upstream file yields exactly
the adapted file. Drift happens when someone edits test_bool.py and forgets to
regenerate test_bool.diff. The pristine file itself is not in the repo —
that's the whole difficulty. To detect drift offline, you need some way to know
what the pristine file was. This PR solves that by storing a sha256 of the
pristine file in a new upstream_manifest.json. But the JSON file isn't needed:
the diff file itself can carry the fingerprints.
What the index line is
When git produces a diff, the header looks like this:
diff --git a/test/cpython/v3_13/test_bool.py b/test/cpython/v3_13/test_bool.py
index a1b2c3d4...e5f6a7b8 100644
--- a/test/cpython/v3_13/test_bool.py
+++ b/test/cpython/v3_13/test_bool.py
@@ -1,5 +1,9 @@
...
The second line — index <hash1>..<hash2> — records the identity of the
entire file on each side of the diff:
<hash1>= git's hash of the before file (here: the pristine upstream file)<hash2>= git's hash of the after file (here: the adapted file)
These are blob SHAs — the same content-addressed hashes git uses internally for
every file it stores. You can compute one for any file with
git hash-object <file>; same bytes always give the same hash. By default git
truncates them in diff output, but git diff --full-index writes them in full.
The PR's diff-generation code currently deletes this line from the diffs it
writes (elif line.startswith("index "): continue). Keeping it replaces the
manifest.
How verification works with it
With the index line preserved, checking sync needs no manifest and no network:
-
Drift check. Run
git hash-object test_bool.pyon the adapted file in
the repo. Compare with<hash2>from the index line intest_bool.diff.
If someone edited the adapted file after the diff was last generated —
anywhere in the file, even far from any diff hunk — its hash no longer
equals<hash2>. Mismatch → "stale diff, regenerate." This one comparison
is the entire drift detection, and it's cheap: no patch application, just
hashing a file. -
Integrity check. Reverse-apply the diff onto the adapted file (the same
git apply -Rthe PR already does), reconstructing the pristine upstream
file. Hash the result and compare against<hash1>. This proves the diff
really corresponds to that specific upstream file, not some arbitrary base. -
Provenance (optional, network, not in CI).
<hash1>is a real git
object ID that exists in CPython's own repository. A periodic job (or the
regen tool) can ask GitHub's API for the blob SHA of
Lib/test/test_bool.pyat tag v3.13.5 and confirm it matches — without
even downloading the file. CI never does this; it's the same
trust-on-first-use position the manifest design has.
Why this beats the JSON manifest
Same guarantees, less machinery:
- One artifact instead of two. The PR stores tag/path in each
.pyheader,
hashes in a central JSON, and then needs code to cross-check that the
manifest and headers agree, plus handle "entry in manifest but file deleted,"
"file exists but no entry," etc. With the index line, each.py/.diffpair
is self-contained — that whole reconciliation category disappears. - The fingerprint can't get separated from the diff. Regenerating a diff
withgit diff --full-indexautomatically embeds the correct hashes; there
is no second file to forget to update. - Verification gets cheaper. The common case (nothing drifted) is decided
by step 1 alone — onehash-objectper file instead of a reverse-apply per
file.
|
Thanks @guilhermeleobas, I have addressed the latest review.
|
guilhermeleobas
left a comment
There was a problem hiding this comment.
Thanks again @PrabinDevkota.
| self.assertNotEqual(corrupted, text) | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| tmp_diff = Path(tmp) / "test_bool.diff" | ||
| tmp_diff.write_text(corrupted, encoding="utf-8", newline="\n") |
There was a problem hiding this comment.
new_line= kwarg is available on Python 3.10+ but CI runs on 3.9. I had to change this (and other) lines to:
| tmp_diff.write_text(corrupted, encoding="utf-8", newline="\n") | |
| tmp_diff.write_bytes(corrupted.encode("utf-8")) |
| INDEX_RE = re.compile( | ||
| r"^index ([0-9a-f]+)\.\.([0-9a-f]+)(?:\s+\d+)?$", re.MULTILINE | ||
| ) |
There was a problem hiding this comment.
| INDEX_RE = re.compile( | |
| r"^index ([0-9a-f]+)\.\.([0-9a-f]+)(?:\s+\d+)?$", re.MULTILINE | |
| ) | |
| INDEX_RE = re.compile(r"^index ([0-9a-f]+)\.\.([0-9a-f]+)(?:\s+\d+)?$", re.MULTILINE) |
| with urllib.request.urlopen(url, timeout=timeout) as resp: | ||
| return normalize_bytes(resp.read()) |
There was a problem hiding this comment.
Could we avoid fetching anything from the web? This can be a security risk if this link gets updated in a future PR and we don't see it. We could instead print an error message "Download the file again with wget / curl <URL>
|
By the way, could you also run |
|
Thank you @guilhermeleobas, I have addressed in the latest push:
|
|
From the test failures, there are two things missing now:
|
|
@guilhermeleobas ,addressed the CI gaps you called out:
|
|
Thanks @PrabinDevkota. I'll wait CI to finish and try to merge. |
|
Hi @PrabinDevkota, there is a conflict now. Could you rebase / merge your PR with |
|
@claude please review this PR. Is there any corner case we didn't look? |
|
Claude finished @guilhermeleobas's task in 25m 21s —— View job Corner-case reviewDesign is sound and much tighter than the first iteration — the Details — 9 corner cases, ordered by severity1.
|
|
Hi, addressed the corner-case review:
|
|
I've approved this before but Claude caught one failure:
|
There was a problem hiding this comment.
I think we cannot add this here. The 2000 LOC limit exists for a security reason. I'll remove it and someone from Meta must review and add the skip-sanity-check label.
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Rebase failed due to Command |
|
@PrabinDevkota can you rebase this PR with upstream/viable/strict? |
Main landed string_tests/test_bytes diffs with abbreviated index lines; rewrite them via regenerate so the offline sync checker can verify.
viable/strict updated the adapted test with TEST_WITH_TORCHDYNAMO. Keep the v3.13.5 index before hash. Test Plan: python tools/regenerate_cpython_diffs.py --check Authored with an AI assistant.
a0cf069 to
ae1e59b
Compare
|
@guilhermeleobas rebased onto viable/strict. The bot conflict was .lintrunner.toml (kept CODEOWNERS_TAXONOMY and CPYTHON_DIFF_SYNC). |
guilhermeleobas
left a comment
There was a problem hiding this comment.
Thanks @PrabinDevkota
|
@pytorchbot merge |
Merge startedYour 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 |
pytorch#191767) ## Summary - Add an offline check that each `test/cpython/v3_13` adapted test and its `.diff` stay in sync: reverse-apply the diff, match `sha256(pristine)` from `upstream_manifest.json` (tag/path taken from each file header), and assert `apply(pristine, diff) == adapted`. - Add `tools/regenerate_cpython_diffs.py` to fetch upstream sources, regenerate stale diffs, and refresh the manifest. - Regenerate drifted `.diff` files, add the missing source URL on `test_unittest/test_assertions.py`, and fix three headers that pointed at the wrong upstream file (`test_binop`, `test_heapq`, `test_patma`). Fixes pytorch#189607 ## Test plan - [x] `python tools/regenerate_cpython_diffs.py --check` - [ ] `python test/dynamo/test_cpython_diff_sync.py CPythonDiffSyncTests` - [ ] Confirm CI runs the new dynamo sync test Pull Request resolved: pytorch#191767 Approved by: https://github.com/guilhermeleobas, https://github.com/williamwen42 Co-authored-by: Guilherme Leobas <[email protected]>
pytorch#191767) ## Summary - Add an offline check that each `test/cpython/v3_13` adapted test and its `.diff` stay in sync: reverse-apply the diff, match `sha256(pristine)` from `upstream_manifest.json` (tag/path taken from each file header), and assert `apply(pristine, diff) == adapted`. - Add `tools/regenerate_cpython_diffs.py` to fetch upstream sources, regenerate stale diffs, and refresh the manifest. - Regenerate drifted `.diff` files, add the missing source URL on `test_unittest/test_assertions.py`, and fix three headers that pointed at the wrong upstream file (`test_binop`, `test_heapq`, `test_patma`). Fixes pytorch#189607 ## Test plan - [x] `python tools/regenerate_cpython_diffs.py --check` - [ ] `python test/dynamo/test_cpython_diff_sync.py CPythonDiffSyncTests` - [ ] Confirm CI runs the new dynamo sync test Pull Request resolved: pytorch#191767 Approved by: https://github.com/guilhermeleobas, https://github.com/williamwen42 Co-authored-by: Guilherme Leobas <[email protected]>
Summary
test/cpython/v3_13adapted test and its.diffstay in sync: reverse-apply the diff, matchsha256(pristine)fromupstream_manifest.json(tag/path taken from each file header), and assertapply(pristine, diff) == adapted.tools/regenerate_cpython_diffs.pyto fetch upstream sources, regenerate stale diffs, and refresh the manifest..difffiles, add the missing source URL ontest_unittest/test_assertions.py, and fix three headers that pointed at the wrong upstream file (test_binop,test_heapq,test_patma).Fixes #189607
Test plan
python tools/regenerate_cpython_diffs.py --checkpython test/dynamo/test_cpython_diff_sync.py CPythonDiffSyncTestscc @albanD @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98