Skip to content

[dynamo] Add offline sync check for test/cpython/v3_13 *.diff files (… - #191767

Closed
PrabinDevkota wants to merge 12 commits into
pytorch:mainfrom
PrabinDevkota:cpython-diff-sync
Closed

PrabinDevkota wants to merge 12 commits into
pytorch:mainfrom
PrabinDevkota:cpython-diff-sync

Conversation

@PrabinDevkota

@PrabinDevkota PrabinDevkota commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

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 #189607

Test plan

  • python tools/regenerate_cpython_diffs.py --check
  • python test/dynamo/test_cpython_diff_sync.py CPythonDiffSyncTests
  • Confirm CI runs the new dynamo sync test

cc @albanD @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

🔗 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 Failures

As of commit ae1e59b with merge base 3601a49 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 3, 2026
Comment thread test/cpython/diff_sync.py Outdated
# 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}"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we avoid hardcoding the tag here??

Comment thread test/cpython/diff_sync.py Outdated
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"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

do we need --ignore-whitespace?

Comment thread test/cpython/v3_13/CHANGES.txt Outdated
Comment on lines +3 to +4
header (e.g. v3.13.5); tags may differ across files. Do not assume a single
global tag from this note alone.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think we should stick with a single tag. Could you update all test files to use the same tag?

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

This is the review from claude:

Summary

Adds an offline check that test/cpython/v3_13/*.diff stay in sync with adapted tests via checked-in pristine hashes, plus a regen tool, plus regenerated drifted diffs. Core design sound and the check has teeth (confirmed: append a line to test_bool.py -> fails). But it ships ~50 lines dead on landing, one step of the verification is a no-op, a --ignore-whitespace fallback silently weakens the guarantee, and the two "structural" tests assert nothing.

Code Quality

test/cpython/diff_sync.py _git_apply — the --ignore-whitespace retry defeats the point. Instrumented on the PR's own tree: 126 strict git apply calls, 0 fallback calls. Comment says "for older noisy hunks" but this PR regenerates every diff, so no noisy hunks remain. Dead path that can only ever mask real drift. Also concatenates both attempts' stderr, so failures print duplicated error: patch does not apply. Delete it.

verify_pair forward-apply step is vacuous. apply(reverse_apply(X, D), D) == X is an identity for strict git apply (no fuzz). Confirmed above. It's only non-vacuous because of the whitespace fallback — i.e. it fires only when the check is already weakened. Delete the fallback, then delete this step; halves subprocess count for zero signal.

parse_header fallback hardcodes tag="v3.13.5" for test_unittest/. test_assertions.py is the only file in that dir and this PR gives it the URL, so the branch is dead now — and for any future file it silently guesses a tag instead of erroring. Delete; let it raise.

tools/regenerate_cpython_diffs.py — ASSERTIONS_HEADER_SNIPPET, fix_assertions_header(), --write-header-assertions are one-shot migration code, already applied in this PR (function now early-returns). ~40 lines dead on landing. Delete.

regenerate() never prunes manifest entries. verify_all reports "<x>: in manifest but no .py/.diff pair on disk", but the regen tool only ever does manifest["files"][rel] = ... — it cannot clear a stale entry, so the user must hand-edit JSON to fix an error the tool told them to fix with the tool.

regenerate() calls save_manifest() unconditionally, including when failures > 0. A network flake mid-run persists a partially-updated manifest.

normalize_bytes CRLF-normalizes before hashing, so manifest sha256 is not the sha256 of the upstream file. Nobody can reproduce it with curl url | sha256sum. The manifest is a checked-in contract — document this in its docstring.

CHANGES.txt keeps Upstream release reference (historical): .../tag/v3.13.0. No file uses v3.13.0 — 61 at v3.13.5, test_enum.py at v3.13.12, test_isinstance.py at v3.13.13. Issue #189607 explicitly asked to remove exactly this confusion; the PR preserves it and labels it "historical". Delete the line.

Two import styles for one module: the tool does sys.path.insert(0, "test") + from cpython.diff_sync import ... (injecting a top-level cpython name), the test uses importlib.util.spec_from_file_location. Pick one.

Infrastructure

Wrong home. This is repo hygiene, not a Dynamo test — it never touches Dynamo. tools/linter/adapters/ is the established place (precedent: nativefunctions_linter.py, workflow_consistency_linter.py, testowners_linter.py): runs on changed files only, inline lintrunner output, and lintrunner -a can wire the regen as autofix. As test/dynamo/test_cpython_diff_sync.py it runs in every dynamo shard × config, requires a git binary in the test env, and offers no autofix.

Nothing ever validates the manifest against real upstream in CI — the whole chain trusts whoever last ran the regen tool locally. Issue option (c) (periodic network job) would close it; at minimum state the gap in the docstring.

Testing

test_every_adapted_file_has_matching_diff asserts nothing. It iterates *.diff and asserts the .py exists, but iter_diff_pairs() already raises FileNotFoundError in that case, so both assertTrue calls are unreachable. The name claims the other direction — adapted .py with no .diff — which is never checked. Note if you add it: 13 files under typinganndata/ have no .diff and need an explicit exclusion.

test_headers_point_at_matching_upstream_basename duplicates the ValueError already raised inside parse_header, which verify_all calls.

No negative test. Nothing asserts the checker fails on drift. I verified both directions by hand; those two cases belong in the test file, otherwise a future refactor can silently neuter the check (see the vacuous forward-apply step for how easy that is).

Test plan has 2 of 3 boxes unchecked, including python test/dynamo/test_cpython_diff_sync.py — the test being added was not run.

Recommendation

Request Changes

Blockers: unrun test + no negative test; --ignore-whitespace fallback; ~50 lines dead-olint adapter is the one design point worth settling before the cleanup, since it changeswhere the code lives.

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

Thanks @guilhermeleobas — went through the review and cleaned this up.
Dropped the whitespace fallback and the no-op forward-apply check, removed the hardcoded tag / one-shot migration code, and made regen prune + only write on success. All adapted files now pin v3.13.5.
Also moved this out of the Dynamo test suite into a lintrunner adapter, with some negative tests in test/test_cpython_diff_sync.py.

@guilhermeleobas guilhermeleobas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Many thanks for working on this @PrabinDevkota. I've made another review.

Comment thread test/test_cpython_diff_sync.py Outdated
raise AssertionError("test_bool.py pair not found")


class CPythonDiffSyncTests(unittest.TestCase):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This should use torch.testing._internal.common_utils.TestCase

Comment thread test/test_cpython_diff_sync.py Outdated


if __name__ == "__main__":
unittest.main()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Use run_tests() instead

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Move this file to /test/cpython?

Comment thread test/test_cpython_diff_sync.py Outdated
Comment on lines +65 to +70
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we need to catch the RuntimeError? Or we should let it propagate?

Comment thread test/cpython/diff_sync.py Outdated
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}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think you should return a LintMessage here with the severity=LintSeverity.ERROR?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This file should be on /tools/ I think

Comment thread test/test_cpython_diff_sync.py Outdated
Comment on lines +81 to +83
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Comment thread test/test_cpython_diff_sync.py Outdated
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

use raise AssertionError instead of plain assert

Comment thread tools/regenerate_cpython_diffs.py Outdated
import sys
import tempfile
from pathlib import Path
from types import ModuleType

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

>>> 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]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. Drift check. Run git hash-object test_bool.py on the adapted file in
    the repo. Compare with <hash2> from the index line in test_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.

  2. Integrity check. Reverse-apply the diff onto the adapted file (the same
    git apply -R the 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.

  3. 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.py at 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 .py header,
    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/.diff pair
    is self-contained — that whole reconciliation category disappears.
  • The fingerprint can't get separated from the diff. Regenerating a diff
    with git diff --full-index automatically 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 — one hash-object per file instead of a reverse-apply per
    file.

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

Thanks @guilhermeleobas, I have addressed the latest review.

  • Tests now use TestCase / run_tests(), live under test/cpython/, and no longer hardcode v3.13.5 (only that all pairs share one tag).
  • Moved the helper to tools/cpython_diff_sync.py.
  • Dropped upstream_manifest.json in favor of git diff --full-index index lines (cheap adapted-hash drift check + reverse-apply integrity). Regenerated all 63 diffs.
  • Orphan .diff files show up as lintrunner ERRORs instead of raising out of the adapter.
  • Fixed the TC003 import nit.

@guilhermeleobas guilhermeleobas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks again @PrabinDevkota.

Comment thread test/cpython/test_diff_sync.py Outdated
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")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

new_line= kwarg is available on Python 3.10+ but CI runs on 3.9. I had to change this (and other) lines to:

Suggested change
tmp_diff.write_text(corrupted, encoding="utf-8", newline="\n")
tmp_diff.write_bytes(corrupted.encode("utf-8"))

Comment thread tools/cpython_diff_sync.py Outdated
Comment on lines +40 to +42
INDEX_RE = re.compile(
r"^index ([0-9a-f]+)\.\.([0-9a-f]+)(?:\s+\d+)?$", re.MULTILINE
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
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)

Comment thread tools/cpython_diff_sync.py Outdated
Comment on lines +103 to +104
with urllib.request.urlopen(url, timeout=timeout) as resp:
return normalize_bytes(resp.read())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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>

@guilhermeleobas

guilhermeleobas commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

By the way, could you also run lintrunner -a before committing?

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

Thank you @guilhermeleobas, I have addressed in the latest push:

  • Replaced write_text(..., newline=) with write_bytes / a Py3.9-safe write_utf8 helper (CI is on 3.9)
  • Put INDEX_RE on one line
  • Removed in-process network fetch; regen is offline-only (reverse-apply). If that fails, it prints curl/wget instructions and supports --pristine with --only
    Also ran lintrunner -a on the touched files (via WSL).

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

From the test failures, there are two things missing now:

  1. I think you need to add 'CPYTHON_DIFF_SYNC' to .spin/cmds.py
  2. Update scripts/lint_urls.sh to include ':(exclude,glob)test/cpython/**'

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

@guilhermeleobas ,addressed the CI gaps you called out:

  1. Added CPYTHON_DIFF_SYNC to SLOW_LINTERS in .spin/cmds.py
  2. Excluded test/cpython/** from scripts/lint_urls.sh
    Also marked test/cpython/v3_13/** as linguist-generated so pr-sanity LOC stays under 2000, and fixed a truncated raw.githubusercontent URL in tools/cpython_diff_sync.py that lint-urls was fetching as 404.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Thanks @PrabinDevkota. I'll wait CI to finish and try to merge.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

Hi @PrabinDevkota, there is a conflict now. Could you rebase / merge your PR with upstream/viable/strict?

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@claude please review this PR. Is there any corner case we didn't look?

@claude

claude Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Claude finished @guilhermeleobas's task in 25m 21s —— View job


Corner-case review

Design is sound and much tighter than the first iteration — the index <before>..<after> approach is the right call. I focused only on corner cases not yet raised in previous rounds. The big one: test/cpython/test_diff_sync.py almost certainly never runs in CI, and the linter has a triggering gap that lets exactly the drift you're guarding against slip through.

Details — 9 corner cases, ordered by severity

1. test/cpython/test_diff_sync.py is excluded from CI by run_test.py (blocker)

test/run_test.py:1890-1901 unconditionally excludes every discovered test under cpython/ that isn't under the current interpreter's version prefix:

current_cpython_prefix = f"cpython/v{sys.version_info.major}_{sys.version_info.minor}/"
options.exclude.extend([
    test for test in selected_tests
    if test.startswith("cpython/") and not test.startswith(current_cpython_prefix)
])

Your file discovers as cpython/test_diff_sync. It starts with cpython/ but not with cpython/v3_13/ (it's one directory up), so it is excluded on every Python version — 3.13 included. Note exclude_tests() uses startswith, so the exclusion definitely lands.

Second, independent problem: even if that filter didn't exist, the only job that runs cpython tests is test_dynamo_cpython() (.ci/pytorch/test.sh:561), which passes --include-cpython-tests, filtering to CPYTHON_TESTS (run_test.py:438) and --dynamo — so your test would be run under the Dynamo wrapper, which is meaningless for a git/subprocess hygiene test.

Net effect: the test file is dead weight in CI. Either move it to test/test_cpython_diff_sync.py (top level, discovers as test_cpython_diff_sync, picked up by the normal pull shards) or add it to run_test.py's explicit include set. Worth actually verifying, since the test plan checkbox for running it is still unchecked:

python -c "from tools.testing.discover_tests import TESTS; print([t for t in TESTS if 'diff_sync' in t])"

Fix this →

2. The linter doesn't fire when the only changed file is a .diff under a subdirectory... and worse, include_patterns misses .diff-only edits in general

.lintrunner.toml:1082-1085 includes test/cpython/v3_13/** — that does cover .diff files. But combined with SLOW_LINTERS semantics in .spin/cmds.py:433,447-455, CPYTHON_DIFF_SYNC runs on changed files only unless --all-files is passed. CI's lintrunner.sh passes ${CHANGED_FILES} and only substitutes --all-files when GitHub reports the changed-file list as *.

The consequence is a real hole: since verify_all() ignores its filenames argument and always checks the whole tree, correctness is fine when it runs. But it does not run at all if a PR touches, say, only torch/_dynamo/ — which is exactly the case where someone regenerates nothing and the tree is already in sync, so that's benign. The non-benign case is the inverse and it's covered. Conclusion: this is OK, but only by accident — it's worth a one-line comment in the adapter noting that verify_all() is whole-tree by design so the include-pattern set only needs to be a trigger, not a complete file list. Otherwise a future reader will "optimize" it to per-file and silently narrow coverage.

3. git apply is sensitive to user/CI git config — core.autocrlf, core.safecrlf, diff.noprefix, apply.whitespace

_git_apply (tools/cpython_diff_sync.py:120-150) and make_unified_diff (:167) run git in a temp dir, but git still reads ~/.gitconfig and /etc/gitconfig. Three specific hazards:

  • diff.noprefix = true (a fairly common user setting) makes git diff --no-index emit --- test/... instead of --- a/test/.... Your header-rewriting loop at :203-212 rewrites --- /+++ lines unconditionally so the output is fine, but git apply on the reading side will strip one leading path component by default (-p1); a diff generated under noprefix and committed by one dev could fail to apply for another.
  • core.autocrlf = true (Windows contributors) makes git apply write CRLF into the working file. You do normalize_bytes() on the result at :150, so this is handled — good.
  • apply.whitespace = fix would silently mutate patch application, defeating the strict-apply guarantee that makes the reverse-apply check meaningful.

Cheap, complete fix: run all git subprocesses with an isolated config.

GIT_ENV = {
    **os.environ,
    "GIT_CONFIG_GLOBAL": os.devnull,
    "GIT_CONFIG_SYSTEM": os.devnull,
    "GIT_CONFIG_NOSYSTEM": "1",
}

and pass env=GIT_ENV in git_hash_object, _git_apply, and make_unified_diff. This also protects git hash-object. Add -c core.autocrlf=false -c apply.whitespace=nowarn for belt-and-braces.

Fix this →

4. git binary is a hard, undeclared dependency of a test

verify_all() shells out to git hash-object and git apply. In a source tarball / conda-build / any sandbox without git (or without a .git dir — git hash-object --stdin works outside a repo, but git apply outside a work tree needs --unsafe-paths in some git versions), the test errors rather than skipping. Since this is repo hygiene enforced by the linter anyway, the test should skipIf when shutil.which("git") is None. Same reasoning applies to the pristine_download_hint path.

5. verify_all() is O(N) subprocesses × 2 and runs on every lintrunner invocation that touches the dir

63 pairs × (1 hash-object + 1 apply + 1 hash-object) ≈ 190 subprocess spawns plus 63 tempdir create/teardowns, on any change under test/cpython/v3_13/** — including a one-character edit to CHANGES.txt. The docstring claims the drift check is "cheap: no patch application, just hashing a file," but verify_pair (:239-249) always does the reverse-apply too, even when the cheap hash check already passed. If the intent was cheap-common-case, the reverse-apply should be gated behind an opt-in (--strict / the test), leaving the linter to do hash-only. As written you pay the full cost every time; SLOW_LINTERS membership acknowledges this, but the docstring oversells it.

6. normalize_bytes only handles CRLF, not lone CR or a UTF-8 BOM

data.replace(b"\r\n", b"\n") leaves a lone \r (old-Mac line ending) intact and leaves a BOM in place. More subtly, git hash-object hashes exactly the bytes you feed it, but git apply's notion of a "line" and Python's str.splitlines() (used in make_unified_diff :203) disagree: splitlines() also splits on \x0b, \x0c, \x1c-\x1e, \x85, 
, 
. I checked the current tree and none of the 63 .py or .diff files contain any of those, nor any \r, so this is latent rather than live. But CPython test files legitimately contain exotic literals (test_float.py, test_patma.py, test_sys.py are candidates on a future tag bump), and the failure mode is a corrupted regenerated diff rather than a clean error. Use text.split("\n") instead of splitlines() at :203 to make it byte-exact.

Fix this →

7. --binary in make_unified_diff can produce a diff the checker cannot verify

make_unified_diff passes --binary (:185). If a future upstream file trips git's binary heuristic (a NUL byte, or invalid UTF-8), git emits a GIT binary patch block instead of hunks. That still carries an index line, so parse_index succeeds and verify_pair "passes" — but the checked-in .diff is now an opaque base85 blob, which defeats the entire point of keeping a human-readable delta for review. Either drop --binary (so regen fails loudly on a binary file) or explicitly reject GIT binary patch in make_unified_diff. Currently no file trips it, so this is about failing loudly on the next tag bump.

8. --only substring matching can silently regenerate the wrong set

regenerate() :77-82 filters with only in py.relative_to(...).as_posix() or only in py.name. --only test_int.py matches only test_int.py, but --only test_int also matches test_int_literal.py; --only test_set matches test_set.py only, fine; --only test_list matches test_list.py and list_tests.py? No — "test_list" in "list_tests.py" is False, OK. But --only test_ matches all 63. Combined with --pristine, the guard at :87-92 catches the multi-match case with a clear error, so the dangerous combination is handled. The remaining risk is --force --only test_int quietly rewriting test_int_literal.diff too. Printing the matched set before acting (or requiring an exact relative-path/basename match) would remove the surprise.

9. Smaller notes

  • parse_header reads only the first 5000 chars (:87). All current headers are at line 8, so fine — but if someone prepends a long license block the URL falls off the end and you get "no cpython source URL in header," which reads as a missing-URL bug rather than a truncation. Cheap to just read the whole file, or scan only the leading comment block.
  • errors="replace" on read_text (:87, :156, :163) means a file with invalid UTF-8 gets silently mangled into U+FFFD instead of erroring. For a checker whose whole job is byte-exactness, errors="strict" is the more honest choice; the .diff reads in particular feed straight into _git_apply.
  • Adapter path-guessing at cpython_diff_sync_linter.py:63-68 parses the error string back into a path with err.split(":", 1)[0]. This is fragile — verify_pair returns messages already prefixed with the rel path, but parse_header's ValueError at :90 is formatted as f"no cpython source URL in header: {py_path}", i.e. the prefix is not a path, so rel becomes "no cpython source URL in header" and the message gets attributed to the CPYTHON_DIR fallback. Have verify_pair return (rel, message) tuples instead of pre-formatted strings and the guessing disappears.
  • .gitattributes double entry (lines 12 and 13) is a genuinely clever workaround for pr-sanity-check.sh:26 using sed (which can't expand **), and the comment explains why. Worth noting the sed -i '/pattern/d' is an unanchored regex match, so the bare-prefix line test/cpython/v3_13/ will also delete any other future path containing that substring from the LOC count. Harmless today, just not as narrow as it looks.
  • test_all_pairs_share_one_upstream_tag asserts len(tags) == 1 — good, no hardcoded tag. But note the earlier v3.13.12/v3.13.13 headers were rewritten down to v3.13.5 (commit 7805189), and test_enum.diff shows real content changes as a result (e.g. the sys.float_repr_style condition). That means the adapted files now claim a v3.13.5 provenance for content that was adapted from a later point release. The hashes are self-consistent so the checker is happy, but the claim about upstream is now the thing to double-check — this is exactly what the (currently absent) periodic network job would catch. Confirming those two blobs against python/cpython at v3.13.5 before merge would be worthwhile.

Suggested priority

  1. Matrix multiplication operator #1 — move the test so it actually runs, and check the box in the test plan.
  2. PEP8 #3 — GIT_CONFIG_GLOBAL/SYSTEM isolation; a two-line change that removes a whole class of works-on-my-machine failures.
  3. PEP8 #4 — skipIf no git.
  4. Checklist for Release #5/Remove dampening from SGD #6/ImportError: No module named _C #7 — latent, worth a follow-up or a comment rather than blocking.
· branch [`cpython-diff-sync`](https://github.com/pytorch/pytorch/tree/cpython-diff-sync)

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

Hi, addressed the corner-case review:

  • Moved the sync unit test to test/test_cpython_diff_sync.py so CI actually runs it (was excluded under test/cpython/)
  • Isolated all git subprocesses from user/system gitconfig (GIT_CONFIG_* + core.autocrlf / apply.whitespace)
  • skipIf when git is missing; stricter UTF-8 reads; BOM/CR normalize; split("\n"); drop --binary and reject binary patches
  • Exact --only matching; verify_* returns (rel, msg) tuples for the linter; comments that include_patterns are triggers only (whole-tree verify)
    python tools/regenerate_cpython_diffs.py --check passes on the tree.

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

I've approved this before but Claude caught one failure:

[AI-generated analysis]

regenerate_cpython_diffs.py can silently drop an adaptation and move the upstream anchor

regenerate() derives the pristine file by reverse-applying the stale .diff onto the new adapted file, then stamps that file's hash as the new index <before>. It never compares against the previous before, so a routine regeneration can redefine what "upstream" means — and verify_all() confirms the result forever after.

Repro on cbf7b14: add @unittest.skip("Dynamo: not supported yet") above test_hasattr in test_bool.py (line 210, outside every existing hunk — they sit at ~1-21, 23-29, 270-276, 437-440).

$ python tools/regenerate_cpython_diffs.py --check
cpython diff sync check FAILED:
  - test_bool.py: adapted file hash 789492ec... != diff index after hash eef64666...
    (stale .diff; regenerate with python tools/regenerate_cpython_diffs.py --only test_bool.py)

$ python tools/regenerate_cpython_diffs.py --only test_bool.py     # what the message instructs
REWRITE  test_bool.py  (v3.13.5)

before BEFORE = 34ecb45f161dfe41482b69384bc447209111c09f   <- real CPython v3.13.5 blob
before AFTER  = 6c361b98c987950ac7a5a92d573ecbf68f0d60b6   <- matches nothing upstream

$ python tools/regenerate_cpython_diffs.py --check
OK: 65 cpython .py/.diff pairs in sync

The skip is now in test_bool.py and has zero occurrences in test_bool.diff. The adaptation was absorbed into what the file claims is pristine upstream.

Review won't catch it: the regenerated diff has the same four hunks, and the only trace is an offset shift that reads as regeneration noise.

-@@ -252,6 +270,7 @@ class BoolTest(unittest.TestCase):
+@@ -253,6 +271,7 @@ class BoolTest(unittest.TestCase):

Root cause: git apply -R only needs the diff's + lines intact, so an edit outside the hunks reverses cleanly and survives into the derived pristine. The checks at lines 152-157 are tautologies — new_diff was built from pristine and adapted, so its index line always matches them. Behaviour depends on where the edit landed: outside the hunks it is silent; inside a hunk or its context git apply -R fails and you correctly get the --pristine hint.

Fix — make the anchor immovable unless a real pristine is supplied. In regenerate(), before make_unified_diff:

if pristine_path is None:
    try:
        old_before, _ = diff_sync.parse_index(
            diff_path.read_text(encoding="utf-8", errors="strict")
        )
    except ValueError:
        old_before = None  # no index line yet: nothing to preserve
    if old_before and diff_sync.git_hash_object(pristine) != old_before:
        raise RuntimeError(diff_sync.pristine_download_hint(tag, upstream))

--force needs the same guard, and lines 154-157 can then go. A regression test belongs in test/test_cpython_diff_sync.py: build a temp pair, edit the adapted file outside the hunks, regenerate, assert it refuses rather than rewriting before.

All 65 before hashes on this branch currently match the real python/cpython blobs at v3.13.5, so the anchor is valid today — the gap is that nothing stops the tool from moving it.

Comment thread .gitattributes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@PrabinDevkota
PrabinDevkota requested a review from albanD as a code owner August 19, 2026 15:18
@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase --onto refs/remotes/origin/viable/strict 4111829138f27e997b04d8fecb6390c9aa52b53d pull/191767/head returned non-zero exit code 1

Rebasing (1/11)
Rebasing (2/11)
Auto-merging .lintrunner.toml
CONFLICT (content): Merge conflict in .lintrunner.toml
error: could not apply 78051890b95... [dynamo] Address review feedback on cpython diff sync check
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply 78051890b95... # [dynamo] Address review feedback on cpython diff sync check

Raised by https://github.com/pytorch/pytorch/actions/runs/33186105661

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@PrabinDevkota can you rebase this PR with upstream/viable/strict?

@PrabinDevkota

Copy link
Copy Markdown
Contributor Author

@guilhermeleobas rebased onto viable/strict. The bot conflict was .lintrunner.toml (kept CODEOWNERS_TAXONOMY and CPYTHON_DIFF_SYNC).
Also refreshed test_operator.diff so it matches main's TEST_WITH_TORCHDYNAMO adaptations without moving the v3.13.5 index before hash. python tools/regenerate_cpython_diffs.py --check is green (65 pairs).

@guilhermeleobas guilhermeleobas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@guilhermeleobas

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 28, 2026
@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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
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]>
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/docker ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo open source skip-pr-sanity-checks topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a test that test/cpython/v3_13/*.diff files stay in sync with the adapted test files

6 participants