summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-15 14:32:20 -0700
committerGitHub <noreply@github.com>2026-10-15 21:32:20 +0000
commit59bb3e8b43a3dbab62933ae404a059bb1258c0ea (patch)
tree363497e32de81b25a9124a1e239ead304930a198
parent4c12e0797dafb29971a6f6e5db650e2cf4c5983c (diff)
security-guidance: stop re-reviewing untracked files past the snapshot cap (#6541)
* security-guidance: stop re-reviewing untracked files past the snapshot cap The untracked-file snapshot stops at 2,000 entries. Every pre-existing untracked file past the cap looked new on each turn, so the same files were reviewed again and again. Record when a capped snapshot was taken and treat unlisted files older than that as pre-existing. * security-guidance: test the metric that shows the capped-snapshot path preexisting_untracked_excluded stays at the 2,000 cap before this fix and rises above it after, which is how the fix can be confirmed from metrics. No new key.
-rw-r--r--plugins/security-guidance/hooks/diffstate.py28
-rw-r--r--plugins/security-guidance/tests/test_untracked_cap.py85
2 files changed, 110 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index be839212..74870c15 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -8,6 +8,7 @@ to work without retargeting.
"""
import os
import subprocess
+import time
from _base import debug_log, _PV
from gitutil import (
@@ -351,6 +352,12 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0):
# =====================================================================
UNTRACKED_BASELINE_CAP = 2000
+# Set in a snapshot that hit the cap, to the time the listing started. NUL
+# cannot occur in a path, so the key never collides with a file.
+UNTRACKED_CAPPED_AT_KEY = "\0capped_at_ns"
+# Coarse filesystem timestamps (1 s on ext3, 2 s on FAT) can stamp a file
+# created just after the snapshot as slightly older than it.
+_CAPPED_BASELINE_SLACK_NS = 2_000_000_000
def _list_untracked(cwd):
@@ -377,6 +384,7 @@ def _list_untracked(cwd):
the holdouts."""
try:
repo = _git_toplevel(cwd) or cwd
+ started_ns = time.time_ns()
# core.quotePath=false comes from GIT_CMD globally (see gitutil.py).
r = subprocess.run(
[*GIT_CMD, "ls-files", "--others", "--exclude-standard", "-z"],
@@ -397,6 +405,10 @@ def _list_untracked(cwd):
out[p] = 0
if len(out) >= UNTRACKED_BASELINE_CAP:
debug_log(f"_list_untracked: capped at {UNTRACKED_BASELINE_CAP}")
+ # The files past the cap are not recorded one by one. Record
+ # when the snapshot was taken so the Stop hook can still tell
+ # them from files created or edited during the turn.
+ out[UNTRACKED_CAPPED_AT_KEY] = started_ns
break
return out
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
@@ -442,14 +454,24 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
if tracked_dirty is None:
return [], "HEAD", repo, [], {"dirty_now_count": -1, "changed_since_count": -1, "review_set_count": 0}
+ capped_at_ns = untracked_at_baseline.get(UNTRACKED_CAPPED_AT_KEY)
+
def _unchanged_since_baseline(p):
base_mtime = untracked_at_baseline.get(p)
- if base_mtime is None:
- return False
try:
- return os.stat(os.path.join(repo, p)).st_mtime_ns == base_mtime
+ st = os.stat(os.path.join(repo, p))
except OSError:
return False
+ if base_mtime is not None:
+ return st.st_mtime_ns == base_mtime
+ if not capped_at_ns:
+ return False
+ # The snapshot stopped at the cap, so this file may simply be one it
+ # never reached. Without this, every pre-existing file past the cap
+ # looks new on every turn and the same files are reviewed again and
+ # again. A file created or edited during the turn has a later mtime
+ # or ctime than the snapshot; anything older was already there.
+ return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS
preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)}
new_untracked = untracked - preexisting_unchanged
diff --git a/plugins/security-guidance/tests/test_untracked_cap.py b/plugins/security-guidance/tests/test_untracked_cap.py
new file mode 100644
index 00000000..00fd4015
--- /dev/null
+++ b/plugins/security-guidance/tests/test_untracked_cap.py
@@ -0,0 +1,85 @@
+import os
+import time
+
+from conftest import make_repo, metrics_of, run_hook, stop_payload, ups_payload
+
+import diffstate
+
+SRC = "import os\nos.system(input())\n"
+
+
+def _review(repo, snapshot):
+ paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set(
+ str(repo), None, None, snapshot)
+ return sorted(os.path.relpath(p, root) for p in paths), metrics
+
+
+class TestCappedSnapshot:
+ def _repo(self, tmp_path, monkeypatch, n=30, cap=10):
+ monkeypatch.setattr(diffstate, "UNTRACKED_BASELINE_CAP", cap)
+ monkeypatch.setattr(diffstate, "_CAPPED_BASELINE_SLACK_NS", 20_000_000)
+ repo = make_repo(tmp_path / "repo")
+ for i in range(n):
+ (repo / f"old_{i:03d}.py").write_text(SRC)
+ time.sleep(0.1)
+ return repo
+
+ def test_snapshot_records_when_it_was_capped(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ before = time.time_ns()
+ snap = diffstate._list_untracked(str(repo))
+ assert before <= snap[diffstate.UNTRACKED_CAPPED_AT_KEY] <= time.time_ns()
+ assert len(snap) == 10 + 1
+
+ def test_uncapped_snapshot_has_no_marker(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch, n=5)
+ assert diffstate.UNTRACKED_CAPPED_AT_KEY not in diffstate._list_untracked(str(repo))
+
+ def test_files_past_the_cap_are_not_reviewed_when_untouched(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ review, metrics = _review(repo, snap)
+ assert review == []
+ assert metrics["preexisting_untracked_excluded"] == 30
+
+ def test_new_and_edited_files_past_the_cap_are_reviewed(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ time.sleep(0.1)
+ (repo / "zz_new.py").write_text(SRC)
+ (repo / "old_025.py").write_text(SRC + "eval(input())\n")
+ (repo / "old_003.py").write_text(SRC + "eval(input())\n") # inside the cap
+ review, _ = _review(repo, snap)
+ assert review == ["old_003.py", "old_025.py", "zz_new.py"]
+
+ def test_file_moved_in_with_an_old_mtime_is_reviewed(self, tmp_path, monkeypatch):
+ repo = self._repo(tmp_path, monkeypatch)
+ snap = diffstate._list_untracked(str(repo))
+ time.sleep(0.1)
+ new = repo / "zz_extracted.py"
+ new.write_text(SRC)
+ os.utime(new, (1_600_000_000, 1_600_000_000)) # as tar or cp -p would leave it
+ review, _ = _review(repo, snap)
+ assert review == ["zz_extracted.py"]
+
+
+def test_stop_hook_does_not_re_review_files_past_the_cap(tmp_path, hook_env, stub_api):
+ """More untracked files than the snapshot holds: the same old files must
+ not be sent for review turn after turn (#6407)."""
+ repo = make_repo(tmp_path / "repo")
+ n_files = diffstate.UNTRACKED_BASELINE_CAP + 60
+ for i in range(n_files):
+ (repo / f"old_{i:05d}.py").write_text(SRC)
+ time.sleep(2.2) # older than the snapshot by more than the timestamp slack
+
+ for _turn in range(2):
+ run_hook(ups_payload(repo), hook_env)
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ # Telemetry: a count above the cap is how this path shows up.
+ assert metrics_of(stdout)["preexisting_untracked_excluded"] == n_files
+ assert stub_api.calls == []
+
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "zz_new.py").write_text(SRC)
+ run_hook(stop_payload(repo), hook_env)
+ assert len([c for c in stub_api.calls if "messages" in c]) == 1