diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-13 20:57:12 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-13 20:57:12 +0000 |
| commit | 84f3cd05382d6c190fc0b09ca2cd2f4d5432e7f6 (patch) | |
| tree | e39966a885fbb544eff5191f6bf351e8fff32837 /plugins/security-guidance/tests | |
| parent | f359d43b406057f1a8cdbc4ea93b827642c162e6 (diff) | |
security-guidance: keep the Stop review working when the changed paths do not fit one command
The Stop review passed every changed path to `git diff` as arguments. With enough of them (an unignored cache, a repo at $HOME) the OS refused to start git, the diff failed twice, and the turn's real edits were never reviewed.
When the OS refuses the argument list, keep only the paths the review can use (reviewable source files) and send them in a few commands under the same time limit. A path list that fits one command is handled exactly as before. Skip review sets of more than 100,000 paths before any diff.
Fixes #4824
Diffstat (limited to 'plugins/security-guidance/tests')
| -rw-r--r-- | plugins/security-guidance/tests/test_stop_review_paths.py | 193 |
1 files changed, 193 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_stop_review_paths.py b/plugins/security-guidance/tests/test_stop_review_paths.py new file mode 100644 index 00000000..85c612af --- /dev/null +++ b/plugins/security-guidance/tests/test_stop_review_paths.py @@ -0,0 +1,193 @@ +"""The Stop review still runs when the changed paths of a turn do not fit in +one git command.""" +import errno +import os +import subprocess +import tempfile +import types + +import pytest + +from conftest import ( + GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, + ups_payload, +) + +import diffstate +import gitutil + +GIT_CMD_CHARS = sum(len(a) + 1 for a in gitutil.GIT_CMD) + + +@pytest.fixture +def git_env(tmp_path, monkeypatch): + """Git identity for in-process calls, and a temp dir of our own for the + index copies.""" + d = tmp_path / "tmproot" + d.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(d)) + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + + +def _more_than_one_command_holds(repo, exts): + """3,000 untracked files, cycling through `exts`, whose names add up to + more than a single command can carry on any platform (the largest limit + is about 2 MB, on Linux).""" + deep = repo / ("d" * 180) / ("e" * 180) / ("f" * 180) / ("g" * 180) + deep.mkdir(parents=True) + for i in range(3000): + (deep / f"file_{i:05d}{exts[i % len(exts)]}").write_text("x\n") + + +long_paths = pytest.mark.skipif( + os.name == "nt", reason="needs paths longer than Windows allows by default") + + +def _refuse_long_commands(monkeypatch, limit, error): + """Make subprocess.run fail like the OS does for a command whose + arguments exceed `limit` characters. Returns the list of commands run.""" + real_run = subprocess.run + ran = [] + + def run(cmd, *args, **kwargs): + if sum(len(a) + 1 for a in cmd) > limit: + raise error + ran.append(cmd) + return real_run(cmd, *args, **kwargs) + + monkeypatch.setattr(subprocess, "run", run) + return ran + + +class TestPathBatches: + def test_every_path_once_and_each_batch_bounded(self): + paths = [f"dir/file_{i}.py" for i in range(100000)] + batches = list(gitutil._path_batches(paths)) + assert [p for b in batches for p in b] == paths + assert len(batches) > 1 + assert all(sum(len(p) for p in b) <= gitutil._MAX_PATH_ARGS_BYTES + for b in batches) + + def test_budget_is_in_bytes(self, monkeypatch): + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 100) + assert len(list(gitutil._path_batches(["\u6f22" * 20 + ".py"] * 3))) == 3 + + def test_one_overlong_path_still_goes_out(self): + long = "x" * (gitutil._MAX_PATH_ARGS_BYTES + 10) + assert list(gitutil._path_batches(["a", long, "b"])) == [["a"], [long], ["b"]] + + def test_no_paths_no_batches(self): + assert list(gitutil._path_batches([])) == [] + + +class TestGetGitDiff: + def _review_set(self, tmp_path): + repo = make_repo(tmp_path / "repo", {f"t{i}.py": "x = 1\n" for i in range(6)}) + for i in range(6): + (repo / f"t{i}.py").write_text("x = 2\n") + (repo / f"new{i}.py").write_text("y = 1\n") + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + assert len(paths) == 12 and len(untracked) == 6 + return root, base, paths, untracked + + def test_one_command_when_the_paths_fit(self, tmp_path, git_env, monkeypatch): + root, base, paths, untracked = self._review_set(tmp_path) + ran = _refuse_long_commands(monkeypatch, 10**9, OSError(errno.E2BIG, "too long")) + diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert len(gitutil.parse_diff_into_files(diff)) == 12 + assert len([c for c in ran if "diff" in c]) == 1 + assert len([c for c in ran if "add" in c]) == 1 + + @pytest.mark.parametrize("error", [ + OSError(errno.E2BIG, "Argument list too long"), + # What Python raises on Windows for ERROR_FILENAME_EXCED_RANGE. + type("WinTooLong", (FileNotFoundError,), {"winerror": 206})(errno.ENOENT, "too long"), + ], ids=["posix", "windows"]) + def test_batches_when_one_command_is_refused(self, tmp_path, git_env, monkeypatch, error): + root, base, paths, untracked = self._review_set(tmp_path) + whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60) + limit = GIT_CMD_CHARS + 100 # the six-path add fits, the twelve-path diff does not + ran = _refuse_long_commands(monkeypatch, limit, error) + batched = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert sorted(gitutil.parse_diff_into_files(batched)) == \ + sorted(gitutil.parse_diff_into_files(whole)) + assert len([c for c in ran if "diff" in c]) > 1 + + def test_only_reviewable_paths_after_a_refusal(self, tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert whole.count("diff --git ") == 21 + _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long")) + cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert cut.count("diff --git ") == 1 + assert gitutil.parse_diff_into_files(cut) == gitutil.parse_diff_into_files(whole) + + def test_gives_up_past_the_batch_limit(self, tmp_path, git_env, monkeypatch): + root, base, paths, untracked = self._review_set(tmp_path) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60) + monkeypatch.setattr(gitutil, "_MAX_PATH_BATCHES", 2) + ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long")) + assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None + assert [c for c in ran if "diff" in c] == [] + + def test_other_start_failures_are_not_retried(self, tmp_path, git_env, monkeypatch): + root, base, paths, untracked = self._review_set(tmp_path) + ran = _refuse_long_commands(monkeypatch, 0, FileNotFoundError(errno.ENOENT, "git")) + assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=[]) is None + assert ran == [] + + def test_batches_share_one_time_limit(self, tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo") + clock = iter([0, 0, 31]) + monkeypatch.setattr(gitutil, "time", types.SimpleNamespace(monotonic=lambda: next(clock))) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 30) + ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 60, OSError(errno.E2BIG, "too long")) + with pytest.raises(subprocess.TimeoutExpired): + gitutil._run_git_on_review_paths( + ["status"], ["a" * 40, "b" * 40, "c" * 40], timeout=30, cwd=str(repo)) + assert len(ran) == 1 + + @long_paths + def test_more_paths_than_one_command_holds(self, tmp_path, git_env): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + _more_than_one_command_holds(repo, [".py", ".txt"]) + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + assert sum(len(p) for p in untracked) > 2 * 1024 * 1024 + diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert diff is not None + # app.py and the 1,500 .py files, from more than one command. + assert len(gitutil.parse_diff_into_files(diff)) == 1501 + assert diff.count("diff --git ") == 1501 + + +class TestWholeHook: + @long_paths + def test_edit_reviewed_beside_more_paths_than_one_command_holds(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + _more_than_one_command_holds(repo, [".txt"]) + rc, so, se = run_hook(stop_payload(repo), hook_env) + m = metrics_of(so) + assert m.get("skip_reason") is None, m + assert m.get("review_set_count") == 3001 + assert stub_api.calls + + def test_review_set_past_the_cap_skips_without_a_diff(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + (repo / "new.py").write_text(VULN_PY) + rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"}) + m = metrics_of(so) + assert m.get("skip_reason") == 8, m + # The skip taken after a diff reports how many files the diff held. + assert "diff_files_count" not in m + assert not stub_api.calls |
