summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-19 16:57:46 +0000
committerClaude <noreply@anthropic.com>2026-10-19 16:57:46 +0000
commit6d375ed2062b0c34e8a18885439cd992ad2d834a (patch)
tree98a2462abaa1412abaf42640e867cb2c4652dee0 /plugins
parentaf95e28036dec718066ef0c3b684dccb4f23cd39 (diff)
security-guidance: keep added lines past the cut, hold the diff timeout
A reviewable file past the per-file cap now keeps as much again of its added lines, so a rewritten large file still shows what is new, and its diff ends with a line saying it was cut. The read runs on a thread so the 30 s limit holds while a process git started keeps the pipe open; a read that breaks is an error instead of a short diff. SG_MAX_FILE_DIFF_BYTES of zero or less means the default. The parser and the reader share one test for which files are reviewed.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py239
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py12
-rw-r--r--plugins/security-guidance/tests/test_stop_diff_memory.py157
3 files changed, 299 insertions, 109 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index cf606337..0e7fcf95 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -20,6 +20,7 @@ import re
import subprocess
import tempfile
import threading
+import time
from _base import debug_log
@@ -768,26 +769,37 @@ def _is_ancestor(cwd, maybe_ancestor, descendant):
return False
+_DEFAULT_FILE_DIFF_BYTES = 4 * 1024 * 1024
+_LATE_FILE_DIFF_BYTES = 256 * 1024
+_LAST_FILE_DIFF_BYTES = 96 * 1024
+
def _file_diff_cap():
+ """SG_MAX_FILE_DIFF_BYTES, or the default when it is unset, not a number
+ or not positive. Never below what a late file keeps, which is well above
+ what the review prompt takes of one file."""
try:
n = int(os.environ.get("SG_MAX_FILE_DIFF_BYTES", ""))
except ValueError:
- return 4 * 1024 * 1024
+ return _DEFAULT_FILE_DIFF_BYTES
+ if n <= 0:
+ return _DEFAULT_FILE_DIFF_BYTES
return max(n, _LATE_FILE_DIFF_BYTES)
-_LATE_FILE_DIFF_BYTES = 64 * 1024
# How much of one file's diff the Stop review keeps while it reads git's
-# output. The review prompt takes far less of a file (DIFF_PER_FILE_BYTES);
-# the rest is room for filter_preexisting_from_diff, which needs the removed
-# and the added side of a rewritten file, so a rewrite keeps both sides for
-# files up to about half of this.
+# output: this much from the start of the file's section, and as much again
+# of the added lines after that. The review prompt takes far less of a file
+# (DIFF_PER_FILE_BYTES); the rest is for filter_preexisting_from_diff, which
+# needs the removed and the added side of a rewritten file.
MAX_FILE_DIFF_BYTES = _file_diff_cap()
-# Past this much kept in total, each further file keeps only its start.
+# Past this much kept in total, a further file keeps _LATE_FILE_DIFF_BYTES
+# the same two ways; past four times as much, _LAST_FILE_DIFF_BYTES from its
+# start, which is still more than the review prompt takes of one file.
MAX_KEPT_DIFF_BYTES = 4 * MAX_FILE_DIFF_BYTES
_SECTION_MARK = b"\ndiff --git "
_MAX_HEADER_BYTES = 64 * 1024
+_CUT_MARK = b"\\ [cut by security-guidance: the rest of this file's diff was not read]\n"
# What the last get_git_diff read, for the Stop hook's metrics: bytes of git
# output, reviewable files whose diff was cut and the bytes cut from them,
@@ -797,9 +809,9 @@ _diff_read = {"bytes": 0, "cut_files": 0, "cut_bytes": 0, "timeouts": 0}
class _DiffKeeper:
"""Takes `git diff` output as it arrives and keeps only what the review
- can use: the header line of every file, and up to MAX_FILE_DIFF_BYTES of
- each file parse_diff_into_files would keep. A turn that wrote large data
- files no longer puts their whole diff in memory."""
+ can use: the header line of every file, and a bounded part of each file
+ parse_diff_into_files would keep. A turn that wrote large data files no
+ longer puts their whole diff in memory."""
def __init__(self):
self.parts = []
@@ -811,10 +823,14 @@ class _DiffKeeper:
# at the very start of the output is found like any other.
self._pending = b"\n"
self._at_start = True
- self._room = MAX_FILE_DIFF_BYTES
self._reviewable = True
+ self._room = self._added_room = MAX_FILE_DIFF_BYTES
self._cut = False
self._ends_nl = True
+ # Past the cut: whether the next byte starts a line, and whether the
+ # line being read is an added one.
+ self._bol = True
+ self._in_added = False
def feed(self, data):
buf = self._pending + data
@@ -824,66 +840,116 @@ class _DiffKeeper:
if i < 0:
# Hold back a tail that could be the start of a header.
end = max(pos, len(buf) - len(_SECTION_MARK) + 1)
- self._keep(buf[pos:end])
+ self._keep(buf, pos, end)
self._pending = buf[end:]
return
j = buf.find(b"\n", i + 1)
if j < 0 and len(buf) - i <= _MAX_HEADER_BYTES:
# The header line is not complete yet.
- self._keep(buf[pos:i])
+ self._keep(buf, pos, i)
self._pending = buf[i:]
return
- self._keep(buf[pos:i + 1])
+ self._keep(buf, pos, i + 1)
if j >= 0:
self._begin(buf[i + 1:j])
pos = i + 1
def _begin(self, header):
"""A new file's section starts with this `diff --git ` line."""
+ self._end_section()
text = header[len(_SECTION_MARK) - 1:].decode("utf-8", errors="replace")
paths = _parse_diff_header(text)
- # Same test as parse_diff_into_files. An unparsed header is passed on
- # so the parser still counts it.
- self._reviewable = not paths or _is_reviewable_source(paths[1] or paths[0])
+ # A section the parser drops, or whose header it cannot read and only
+ # counts, keeps its header line.
+ self._reviewable = bool(paths) and _section_is_reviewable(
+ paths[1] or paths[0], paths[0])
if not self._reviewable:
- self._room = len(header) + 1
+ self._room, self._added_room = len(header) + 1, 0
+ elif self.kept > 4 * MAX_KEPT_DIFF_BYTES:
+ self._room, self._added_room = max(len(header) + 1, _LAST_FILE_DIFF_BYTES), 0
elif self.kept > MAX_KEPT_DIFF_BYTES:
- self._room = max(len(header) + 1, _LATE_FILE_DIFF_BYTES)
+ self._room = self._added_room = max(len(header) + 1, _LATE_FILE_DIFF_BYTES)
else:
- self._room = MAX_FILE_DIFF_BYTES
+ self._room = self._added_room = MAX_FILE_DIFF_BYTES
self._cut = False
- if not self._ends_nl:
- # The previous file was cut inside a line.
- self.parts.append(b"\n")
- self._ends_nl = True
- def _keep(self, data):
- if self._at_start and data:
+ def _end_section(self):
+ if not self._ends_nl:
+ # Cut inside a line: end it, so what follows starts a line.
+ self._append(b"\n")
+ if self._cut:
+ self._append(_CUT_MARK)
+
+ def _append(self, piece):
+ self.parts.append(piece)
+ self.kept += len(piece)
+ self._ends_nl = piece.endswith(b"\n")
+
+ def _keep(self, buf, start, end):
+ if self._at_start and end > start:
self._at_start = False
- data = data[1:]
- if not data:
+ start += 1
+ n = end - start
+ if n <= 0:
return
- self.seen += len(data)
- take = data[:self._room]
+ self.seen += n
+ take = min(n, self._room)
if take:
- self.parts.append(take)
- self.kept += len(take)
- self._room -= len(take)
- self._ends_nl = take.endswith(b"\n")
- if len(take) < len(data) and self._reviewable:
- self.cut_bytes += len(data) - len(take)
- if not self._cut:
- self._cut = True
- self.cut_files += 1
+ self._append(buf[start:start + take])
+ self._room -= take
+ if take == n or not self._reviewable:
+ return
+ if not self._cut:
+ self._cut = True
+ self.cut_files += 1
+ self._bol = self._ends_nl
+ self._in_added = False
+ self.cut_bytes += n - take - self._keep_added(buf, start + take, end)
+
+ def _keep_added(self, buf, pos, end):
+ """Past a file's cut, keep its added lines only, up to as much again.
+ A rewritten file lists every removed line before the first added one,
+ and the review is about the added ones. Returns the bytes kept."""
+ kept = 0
+ run = -1 # where a run of added lines not yet appended starts
+ while pos < end and self._added_room > 0:
+ if self._bol:
+ self._bol = False
+ self._in_added = buf.startswith(b"+", pos)
+ if self._in_added and run < 0 and not self._ends_nl:
+ self._append(b"\n")
+ if not self._in_added:
+ if run >= 0:
+ self._append(buf[run:pos])
+ run = -1
+ nxt = buf.find(b"\n+", pos, end)
+ if nxt < 0:
+ self._bol = buf.endswith(b"\n", pos, end)
+ break
+ pos = nxt + 1
+ self._bol = True
+ continue
+ nl = buf.find(b"\n", pos, end)
+ stop = end if nl < 0 else nl + 1
+ take = min(stop - pos, self._added_room)
+ if run < 0:
+ run = pos
+ self._added_room -= take
+ kept += take
+ self._bol = nl >= 0
+ if pos + take < stop:
+ self._append(buf[run:pos + take])
+ run = -1
+ pos = stop
+ if run >= 0:
+ self._append(buf[run:pos])
+ return kept
def result(self):
- self._keep(self._pending)
+ self._keep(self._pending, 0, len(self._pending))
self._pending = b""
- if not self._ends_nl:
- # Cut inside a line: end it, so anything joined after this
- # output starts on a line of its own.
- self.parts.append(b"\n")
- self._ends_nl = True
+ self._end_section()
+ self._cut = False
return b"".join(self.parts)
@@ -892,6 +958,7 @@ def _run_diff_bounded(cmd, timeout, **kwargs):
`git diff`, except that stdout goes through _DiffKeeper instead of being
held whole."""
keeper = _DiffKeeper()
+ deadline = time.monotonic() + timeout
try:
err = tempfile.TemporaryFile()
except OSError:
@@ -900,40 +967,57 @@ def _run_diff_bounded(cmd, timeout, **kwargs):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=err if err is not None else subprocess.DEVNULL,
**kwargs)
- expired = threading.Event()
-
- def _expire():
- expired.set()
- p.kill()
+ failed = []
+ given_up = []
- timer = threading.Timer(timeout, _expire)
- timer.daemon = True
+ def _read():
+ try:
+ while not given_up:
+ chunk = p.stdout.read1(65536)
+ if not chunk or given_up:
+ break
+ keeper.feed(chunk)
+ except BaseException as e:
+ failed.append(e)
+
+ # Read on a thread, so the timeout holds even while something git
+ # started still has the pipe open after git itself is gone.
+ reader = threading.Thread(target=_read, daemon=True)
+ timed_out = False
try:
try:
- timer.start()
+ reader.start()
except RuntimeError as e:
- raise OSError(f"no thread for the diff timeout: {e}")
- while True:
- chunk = p.stdout.read1(1024 * 1024)
- if not chunk:
- break
- keeper.feed(chunk)
- returncode = p.wait()
- except BaseException:
- p.kill()
- p.wait()
- raise
+ failed.append(e)
+ else:
+ reader.join(timeout)
+ timed_out = reader.is_alive()
+ if timed_out or failed:
+ p.kill()
+ try:
+ returncode = p.wait(max(deadline - time.monotonic(), 0.1))
+ except subprocess.TimeoutExpired:
+ timed_out = True
finally:
- timer.cancel()
- p.stdout.close()
- stdout = keeper.result()
+ if timed_out or failed or p.returncode is None:
+ # The reader may be left waiting on a pipe something else
+ # holds: it keeps nothing more, and the pipe stays its.
+ given_up.append(True)
+ p.kill()
+ p.wait()
+ if reader.ident is not None:
+ reader.join(1)
+ if not reader.is_alive():
+ p.stdout.close()
_diff_read["bytes"] += keeper.seen
- _diff_read["cut_files"] += keeper.cut_files
- _diff_read["cut_bytes"] += keeper.cut_bytes
- # A diff that finished as the timer fired is still a finished diff.
- if expired.is_set() and returncode != 0:
+ if timed_out:
_diff_read["timeouts"] += 1
raise subprocess.TimeoutExpired(cmd, timeout)
+ if failed:
+ raise OSError(f"reading the diff failed: {failed[0]!r}")
+ stdout = keeper.result()
+ _diff_read["cut_files"] += keeper.cut_files
+ _diff_read["cut_bytes"] += keeper.cut_bytes
stderr = b""
if err is not None:
err.seek(0)
@@ -960,7 +1044,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
can add only those files instead of scanning the whole worktree.
The output is read through _DiffKeeper: files the review would drop come
back as their header line only, and a file's diff past
- MAX_FILE_DIFF_BYTES is cut.
+ MAX_FILE_DIFF_BYTES is cut down to its added lines.
"""
pathspec = _diff_pathspec(cwd, paths)
if paths and not pathspec:
@@ -1297,6 +1381,13 @@ def _parse_diff_header(header):
_unparsed_diff_headers = set()
+def _section_is_reviewable(file_path, old_path):
+ """Whether a diff section is sent for review: a source file, and not one
+ renamed away from a secret-shaped name, which still carries the secret's
+ content."""
+ return _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path)
+
+
def _iter_diff_sections(diff_output):
"""Yield (new_path, old_path, lines after the header line) per file section."""
for section in _DIFF_SECTION_RE.split(diff_output)[1:]:
@@ -1318,7 +1409,7 @@ def extract_file_paths_from_diff(diff_output):
return [
file_path for file_path, old_path, _ in _iter_diff_sections(diff_output)
- if _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path)
+ if _section_is_reviewable(file_path, old_path)
]
@@ -1334,7 +1425,7 @@ def parse_diff_into_files(diff_output):
for file_path, old_path, lines in _iter_diff_sections(diff_output):
# Filter to source code files only. A rename away from a secret-shaped
# name still carries the secret's content, so the old name counts too.
- if not _is_reviewable_source(file_path) or _skip_secret_shaped(old_path):
+ if not _section_is_reviewable(file_path, old_path):
continue
# Extract the diff content (from first @@ onwards)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 72edf794..9ff43529 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -2138,8 +2138,10 @@ def handle_push_sweep_posttooluse(input_data):
def _stop_diff_truncated():
"""Bytes of reviewable diff the Stop review did not send: cut while
- reading git's output, plus what the prompt caps dropped after that."""
- return llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"]
+ reading git's output, plus what the prompt caps dropped after that.
+ As the metric to emit, or nothing when there were none."""
+ n = llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"]
+ return {"diff_truncated": n} if n else {}
def handle_stop_hook(input_data):
@@ -2432,8 +2434,7 @@ def handle_stop_hook(input_data):
"touched_paths_count": len(touched_paths),
"review_ms": review_ms,
"fire_index": fire_index,
- **({"diff_truncated": _stop_diff_truncated()}
- if _stop_diff_truncated() else {}),
+ **_stop_diff_truncated(),
**({"repo_resolution": repo_res} if res_metrics else {}),
**sweep_trimmed,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
@@ -2470,8 +2471,7 @@ def handle_stop_hook(input_data):
"review_ms": review_ms,
"fire_index": fire_index,
**({"api_error": llm._last_call_claude_http_error} if llm._last_call_claude_http_error is not None else {}),
- **({"diff_truncated": _stop_diff_truncated()}
- if _stop_diff_truncated() else {}),
+ **_stop_diff_truncated(),
**v2_metrics,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
if gitutil._unparsed_diff_headers else {}),
diff --git a/plugins/security-guidance/tests/test_stop_diff_memory.py b/plugins/security-guidance/tests/test_stop_diff_memory.py
index e95d94ec..31a524f9 100644
--- a/plugins/security-guidance/tests/test_stop_diff_memory.py
+++ b/plugins/security-guidance/tests/test_stop_diff_memory.py
@@ -4,6 +4,7 @@ import random
import subprocess
import sys
import tempfile
+import time
import tracemalloc
import pytest
@@ -16,6 +17,22 @@ from conftest import (
import gitutil
+@pytest.fixture(autouse=True)
+def _fresh_read_state():
+ yield
+ gitutil._unparsed_diff_headers.clear()
+ gitutil._diff_read.update(bytes=0, cut_files=0, cut_bytes=0, timeouts=0)
+
+
+def _rewrite(path, removed, added):
+ return (f"diff --git a/{path} b/{path}\n"
+ "index 1111111..2222222 100644\n"
+ f"--- a/{path}\n+++ b/{path}\n"
+ f"@@ -1,{len(removed)} +1,{len(added)} @@\n"
+ + "".join(f"-{ln}\n" for ln in removed)
+ + "".join(f"+{ln}\n" for ln in added))
+
+
@pytest.fixture
def git_env(tmp_path, monkeypatch):
d = tmp_path / "tmproot"
@@ -96,34 +113,77 @@ class TestDiffKeeper:
files = dict(gitutil.parse_diff_into_files(kept.decode()))
assert set(files) == {"big.json", "after.py"}
assert files["after.py"] == dict(gitutil.parse_diff_into_files(raw.decode()))["after.py"]
- assert files["big.json"] and len(files["big.json"]) < 300
+ # The start of the section, then as much again of its added lines.
+ assert 300 < len(files["big.json"]) <= 2 * 300 + len(gitutil._CUT_MARK) + 2
+ assert keeper.cut_files == 1
+ assert keeper.cut_bytes == len(big) - 2 * 300
+
+ def test_cut_file_says_so_on_its_last_line(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ raw = (_section("big.json", ["k" * 37] * 100) + _section("after.py", ["x"])).encode()
+ _, kept = _keep(raw, _sizes(64))
+ files = dict(gitutil.parse_diff_into_files(kept.decode()))
+ assert files["big.json"].endswith(gitutil._CUT_MARK.decode())
+ assert "cut by security-guidance" not in files["after.py"]
+ assert kept.count(gitutil._CUT_MARK) == 1
+
+ @pytest.mark.parametrize("chunk", [1, 23, 4096])
+ def test_rewrite_past_the_cap_keeps_its_added_lines(self, monkeypatch, chunk):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 400)
+ raw = (_rewrite("views.py", ["old line %03d" % i for i in range(200)],
+ ["os.system(cmd)"] + ["new line %03d" % i for i in range(200)])
+ + _section("after.py", ["x"])).encode()
+ keeper, kept = _keep(raw, _sizes(chunk))
+ body = dict(gitutil.parse_diff_into_files(kept.decode()))["views.py"]
+ assert "+os.system(cmd)\n" in body
+ assert "-old line 199" not in body
+ past = body[400:]
+ assert all(ln.startswith(("+", "\\")) for ln in past.splitlines()[1:])
+ assert len(body) <= 2 * 400 + len(gitutil._CUT_MARK) + 2
assert keeper.cut_files == 1
- assert keeper.kept <= 300 + len(_section("after.py", ["import os"])) + 1
def test_dropped_large_file_is_not_counted_as_cut(self, monkeypatch):
monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
raw = (_section("big.log", ["k" * 37] * 100) + _section("after.py", ["x"])).encode()
keeper, kept = _keep(raw, _sizes(64))
- assert keeper.cut_files == 0
+ assert keeper.cut_files == 0 and keeper.cut_bytes == 0
assert [p for p, _ in gitutil.parse_diff_into_files(kept.decode())] == ["after.py"]
- def test_past_the_total_each_file_keeps_only_its_start(self, monkeypatch):
+ def test_renamed_from_a_secret_shaped_name_keeps_its_header_only(self):
+ raw = (_section("config.py", ["TOKEN = 'abc'"], old=".env")
+ + _section("after.py", ["x"])).encode()
+ want = gitutil.parse_diff_into_files(raw.decode())
+ _, kept = _keep(raw, _sizes(64))
+ assert gitutil.parse_diff_into_files(kept.decode()) == want
+ assert [p for p, _ in want] == ["after.py"]
+ assert b"TOKEN" not in kept
+
+ def test_past_the_total_later_files_keep_less_and_less(self, monkeypatch):
monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 2000)
monkeypatch.setattr(gitutil, "MAX_KEPT_DIFF_BYTES", 3000)
monkeypatch.setattr(gitutil, "_LATE_FILE_DIFF_BYTES", 200)
- raw = "".join(_section(f"f{i}.py", ["v" * 30] * 60) for i in range(6)).encode()
+ monkeypatch.setattr(gitutil, "_LAST_FILE_DIFF_BYTES", 120)
+ raw = "".join(_section(f"f{i}.py", ["v" * 30] * 400) for i in range(40)).encode()
keeper, kept = _keep(raw, _sizes(333))
files = gitutil.parse_diff_into_files(kept.decode())
- assert [p for p, _ in files] == [f"f{i}.py" for i in range(6)]
- assert len(kept) <= 2 * 2000 + 4 * 200 + 6
- assert keeper.cut_files == 6
+ assert [p for p, _ in files] == [f"f{i}.py" for i in range(40)]
+ sizes = [len(body) for _, body in files]
+ mark = len(gitutil._CUT_MARK) + 2
+ assert sizes[0] > 2000 and sizes[0] <= 4000 + mark
+ assert 200 < sizes[5] <= 400 + mark
+ assert sizes[-1] <= 120 + mark
+ assert sizes[0] > sizes[5] > sizes[-1]
+ assert keeper.cut_files == 40
+ # Everything not kept is counted; a cut may add a newline or two.
+ from_git = len(kept) - 40 * len(gitutil._CUT_MARK)
+ assert from_git - 80 <= len(raw) - keeper.cut_bytes <= from_git
def test_output_cut_inside_a_line_ends_with_a_newline(self, monkeypatch):
monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
- raw = _section("big.json", ["k" * 37] * 100).encode()
+ raw = _rewrite("big.json", ["k" * 37] * 100, []).encode()
keeper, kept = _keep(raw, _sizes(64))
- assert kept.endswith(b"\n") and not raw.startswith(kept)
- assert keeper.cut_bytes == len(raw) - (len(kept) - 1)
+ assert kept == raw[:300] + b"\n" + gitutil._CUT_MARK
+ assert keeper.cut_bytes == len(raw) - 300
both = kept + _section("next.py", ["x"]).encode()
assert [p for p, _ in gitutil.parse_diff_into_files(both.decode())] == ["big.json", "next.py"]
@@ -134,7 +194,8 @@ class TestDiffKeeper:
class TestRunDiffBounded:
def test_returns_what_run_would(self):
- code = "import sys; sys.stdout.write('diff --git a/a.py b/a.py\\n@@ -1 +1 @@\\n+x\\n'); sys.stderr.write('warn'); sys.exit(3)"
+ code = ("import sys; sys.stdout.buffer.write(b'diff --git a/a.py b/a.py\\n@@ -1 +1 @@\\n+x\\n'); "
+ "sys.stderr.write('warn'); sys.exit(3)")
r = gitutil._run_diff_bounded([sys.executable, "-c", code], 30)
assert r.returncode == 3
assert r.stdout == b"diff --git a/a.py b/a.py\n@@ -1 +1 @@\n+x\n"
@@ -147,18 +208,41 @@ class TestRunDiffBounded:
gitutil._run_diff_bounded([sys.executable, "-c", code], 0.5)
assert gitutil._diff_read["timeouts"] == before + 1
- def test_finished_as_the_timer_fired_is_not_a_timeout(self, monkeypatch):
- class Fired:
- def __init__(self, timeout, fn):
- self.fn = fn
- daemon = False
- def start(self):
- pass
- def cancel(self):
- self.fn()
- monkeypatch.setattr(gitutil.threading, "Timer", Fired)
- r = gitutil._run_diff_bounded([sys.executable, "-c", "print('ok')"], 30)
- assert r.returncode == 0 and r.stdout.strip() == b"ok"
+ def test_timeout_holds_while_another_process_keeps_the_pipe_open(self):
+ # What a `git diff` that started a fetch looks like: the program is
+ # gone, something it started still holds its stdout.
+ code = ("import subprocess, sys; "
+ "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(8)']); "
+ "sys.stdout.write('x'); sys.stdout.flush()")
+ before = gitutil._diff_read["timeouts"]
+ t0 = time.monotonic()
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 1)
+ assert time.monotonic() - t0 < 5
+ assert gitutil._diff_read["timeouts"] == before + 1
+
+ def test_a_timed_out_read_still_reports_its_size(self):
+ code = "import sys, time; sys.stdout.write('x' * 300000); sys.stdout.flush(); time.sleep(60)"
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 1)
+ assert gitutil._diff_read["bytes"] >= 200000
+
+ def test_a_read_that_breaks_is_an_error_not_a_short_diff(self, monkeypatch):
+ def broken(self, data):
+ raise MemoryError("no room")
+ monkeypatch.setattr(gitutil._DiffKeeper, "feed", broken)
+ code = "import sys; sys.stdout.write('diff --git a/a.py b/a.py\\n' * 50000)"
+ t0 = time.monotonic()
+ with pytest.raises(OSError):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 30)
+ assert time.monotonic() - t0 < 10
+
+ def test_no_thread_to_read_with_is_an_error(self, monkeypatch):
+ def refuse(self):
+ raise RuntimeError("can't start new thread")
+ monkeypatch.setattr(gitutil.threading.Thread, "start", refuse)
+ with pytest.raises(OSError):
+ gitutil._run_diff_bounded([sys.executable, "-c", "print('x')"], 30)
def test_missing_program_raises_like_run(self):
with pytest.raises(FileNotFoundError):
@@ -196,8 +280,8 @@ class TestGetGitDiff:
untracked_paths=[]) is None
@pytest.mark.parametrize("value, want", [
- ("", 4 * 1024 * 1024), ("junk", 4 * 1024 * 1024), ("0", 64 * 1024),
- ("-5", 64 * 1024), ("100000", 100000)])
+ ("", 4 * 1024 * 1024), ("junk", 4 * 1024 * 1024), ("0", 4 * 1024 * 1024),
+ ("-5", 4 * 1024 * 1024), ("1000", 256 * 1024), ("1000000", 1000000)])
def test_cap_setting_cannot_break_the_read(self, monkeypatch, value, want):
monkeypatch.setenv("SG_MAX_FILE_DIFF_BYTES", value)
assert gitutil._file_diff_cap() == want
@@ -217,6 +301,19 @@ class TestGetGitDiff:
gitutil.parse_diff_into_files(diff), str(repo), "HEAD")
assert "+os.system(request.GET['cmd'])" in files[0][1][:2000]
+ def test_rewrite_past_the_cap_still_shows_what_is_new(self, tmp_path, git_env, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 200000)
+ body = "".join(f"def handler_{i}(request):\n return render(request, 'page_{i}.html')\n"
+ for i in range(18000))
+ repo = make_repo(tmp_path / "repo", {"views.py": body.replace("\n", "\r\n")})
+ (repo / "views.py").write_bytes(("import os\nos.system(request.GET['cmd'])\n" + body).encode())
+ diff = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "views.py")], untracked_paths=[])
+ assert gitutil._diff_read["cut_files"] == 1
+ assert len(diff) < 2 * 200000 + 1000
+ files = gitutil.filter_preexisting_from_diff(
+ gitutil.parse_diff_into_files(diff), str(repo), "HEAD")
+ assert "+os.system(request.GET['cmd'])" in files[0][1][:2000]
+
def test_failed_diff_is_still_none(self, tmp_path, git_env):
repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
assert gitutil.get_git_diff(str(repo), "0" * 40, paths=[str(repo / "app.py")],
@@ -229,15 +326,17 @@ class TestStopHook:
run_hook(ups_payload(repo), hook_env)
(repo / "app.py").write_text(VULN_PY)
(repo / "gen.txt").write_text("some generated text\n" * 150000)
- (repo / "big.json").write_text('"k": "some generated value",\n' * 9000)
- env = {**hook_env, "SG_MAX_FILE_DIFF_BYTES": "100000"}
+ (repo / "big.json").write_text('"k": "some generated value",\n' * 20000)
+ env = {**hook_env, "SG_MAX_FILE_DIFF_BYTES": "1000"}
rc, so, se = run_hook(stop_payload(repo), env)
m = metrics_of(so)
assert not m.get("skipped"), m
assert m["files_reviewed"] == 2
assert m["diff_mb"] == 3
assert m["diff_cut_files"] == 1
- assert m["diff_truncated"] > 9000 * 29 - 80000 - 1000
+ # 256 KiB from the start and as much again of added lines were read;
+ # the prompt took 80,000 bytes of that.
+ assert m["diff_truncated"] > 20000 * 29 - 80000 - 1000
assert "diff_timeout" not in m
assert stub_api.calls