diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-22 17:11:25 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-22 17:11:25 +0000 |
| commit | 22aea1e9b9b4e4efa98237d4d52154f973b47fec (patch) | |
| tree | 47f7f055cec40bb8768f6f32c838ee8169f56217 /plugins | |
| parent | af59ee3a1051a29dda4a2e7a2af221aa457ae08b (diff) | |
security-guidance: report where a slow prompt's time goesmhegazy/sg-prompt-capture-time
Prompts that wait a second or more in the UserPromptSubmit hook send one
metrics row: total, baseline and untracked listing time, index size, and
whether the repository is on a Windows drive under WSL. Measures only;
capture is unchanged. See #6854.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 7 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 44 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 52 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_slow_prompt_metrics.py | 175 |
4 files changed, 272 insertions, 6 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 6532fb6c..063b0604 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -16,6 +16,7 @@ from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, + index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -322,6 +323,8 @@ def get_baseline_file_content(session_id, file_path, cwd): # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. last_baseline_fail = 0 +# Entries in the index the last capture copied, None if unknown. Telemetry only. +last_index_entries = None def capture_git_baseline(cwd): @@ -350,8 +353,9 @@ def capture_git_baseline(cwd): # with `Ávila_report.txt` triggers a quotePath/locale warning) would # trip the stderr reader thread on Windows cp1252. Decode both streams # leniently for symmetry with _list_untracked. See #2056. - global last_baseline_fail + global last_baseline_fail, last_index_entries last_baseline_fail = 0 + last_index_entries = None try: # Check if HEAD exists (i.e., repo has at least one commit) head_check = subprocess.run( @@ -369,6 +373,7 @@ def capture_git_baseline(cwd): # env is None when no usable index copy could be made: fall # back to HEAD. if env is not None: + last_index_entries = index_entry_count(env["GIT_INDEX_FILE"]) result = subprocess.run( [*GIT_CMD, "stash", "create"], cwd=cwd, capture_output=True, timeout=15, env=env diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 73d7c611..ab9a2d03 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -103,6 +103,50 @@ def apply_safe_git_env(): os.environ.update(SAFE_GIT_ENV) +def index_entry_count(path): + """The entry count in an index file's header (signature, version, count), + or None if it cannot be read. A split or sparse index holds fewer entries + than the repository has tracked files.""" + try: + with open(path, "rb") as f: + header = f.read(12) + except OSError: + return None + if header[:4] == b"DIRC" and len(header) == 12: + return int.from_bytes(header[8:12], "big") + return None + + +def windows_drive_mount(path, mountinfo): + """Whether `path` is on a Windows drive mounted into WSL, given the text + of /proc/self/mountinfo. Every file status there is a round trip to the + Windows host.""" + best, best_type = "", "" + for line in mountinfo.splitlines(): + # id parent dev root mountpoint options [tags] - fstype source options + before, _, after = line.partition(" - ") + fields, tail = before.split(), after.split() + if len(fields) < 5 or not tail: + continue + point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4]) + inside = path == point or path.startswith(point.rstrip("/") + "/") + if inside and len(point) >= len(best): + best, best_type = point, tail[0] + return best_type in ("9p", "drvfs", "virtiofs") + + +def on_windows_drive(path): + """windows_drive_mount for this machine. False anywhere but WSL.""" + try: + with open("/proc/sys/kernel/osrelease") as f: + if "microsoft" not in f.read().lower(): + return False + with open("/proc/self/mountinfo") as f: + return windows_drive_mount(os.path.realpath(path), f.read()) + except (OSError, ValueError): + return False + + def _git_rev_parse_head(cwd): """Return the current HEAD SHA, or None if not a git repo / no commits.""" try: diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 0cae917d..cb1b51d9 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -87,7 +87,7 @@ from _base import ( # noqa: E402,F401 _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _USAGE_CONTEXT, _log_usage, launcher_probe_metrics, state_dir as _resolve_state_dir, - write_hook_output as _write_hook_output, + write_hook_output as _write_hook_output, portable_output, llm_reviews_switched_off, agent_sdk_installed, ) import extensibility # noqa: E402 @@ -103,6 +103,7 @@ from session_state import ( # noqa: E402,F401 ) from gitutil import ( # noqa: E402,F401 GIT_CMD, apply_safe_git_env, remove_copies_on_termination, + on_windows_drive, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, _git_toplevel_and_head, _git_head_at, @@ -680,6 +681,31 @@ def _store_baseline_fail(state, fail): state.pop("baseline_fail", None) +# A prompt waits for this hook, so one this slow is worth a metrics row. Faster +# prompts send none: the row would be one more event per prompt for every user. +SLOW_PROMPT_MS = 1000 + + +def _slow_prompt_metrics(cwd, total, baseline, untracked, captured, baseline_fail): + """The metrics row for a slow prompt. Times are seconds, spent in + handle_user_prompt_submit (the launcher reports its own). Counts and flags + only, never a path. Telemetry only.""" + metrics = { + "ups_ms": int(total * 1000), + "ups_baseline_ms": int(baseline * 1000), + "ups_untracked_ms": int(untracked * 1000), + } + if diffstate.last_index_entries is not None: + metrics["ups_index_entries"] = diffstate.last_index_entries + if on_windows_drive(cwd): + metrics["ups_wsl_drive"] = 1 + if not captured: + metrics["ups_no_baseline"] = 1 + if baseline_fail: + metrics["ups_baseline_fail"] = baseline_fail + return metrics + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -692,6 +718,8 @@ def handle_user_prompt_submit(input_data): to be lost when the wipe landed before Stop's state read. """ + import time as _time + started = _time.monotonic() cwd = input_data.get("cwd", "") if not cwd: debug_log("UPS: no cwd, skipping baseline capture") @@ -704,17 +732,25 @@ def handle_user_prompt_submit(input_data): # nothing, so only the stash baseline (still read by the Write pattern # filter) is captured. snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + spent = {"baseline": 0.0, "untracked": 0.0} + + def _timed(key, fn, repo_cwd): + began = _time.monotonic() + try: + return fn(repo_cwd) + finally: + spent[key] += _time.monotonic() - began def _capture(repo_cwd): if not snapshot_untracked: - return capture_git_baseline(repo_cwd), None + return _timed("baseline", capture_git_baseline, repo_cwd), None # stash-create and ls-files both walk the worktree (~2-5s each in a # very large repo). Run them concurrently so UPS latency stays # ≈ max(both). import concurrent.futures as _cf with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, repo_cwd) - _f_ut = _ex.submit(_list_untracked, repo_cwd) + _f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd) # Taken whether or not the stash produced a SHA. `git stash # create` returns empty when there are no TRACKED changes, but # pre-existing untracked files still need to be excluded from the @@ -723,7 +759,6 @@ def handle_user_prompt_submit(input_data): # something tracked is dirtied. return _f_sha.result(), _f_ut.result() or {} - import time as _time captured_at = _time.time() sha, untracked_now = _capture(cwd) # No repo here and none remembered: the listing above failed, it did not @@ -813,6 +848,13 @@ def handle_user_prompt_submit(input_data): debug_log(f"Failed to capture git baseline (cwd={cwd!r}) — not a git repo, " f"or git invocation failed (check log entries above)") + total = _time.monotonic() - started + debug_log(f"UPS: took {total:.2f}s (baseline {spent['baseline']:.2f}s, " + f"untracked {spent['untracked']:.2f}s)") + if (total * 1000 >= SLOW_PROMPT_MS or _LAUNCHER_METRICS) and not portable_output(): + emit_metrics(_slow_prompt_metrics( + cwd, total, spent["baseline"], spent["untracked"], bool(sha), baseline_fail)) + sys.exit(0) def _resolve_amend_pre_sha(repo_root, expected_post_sha=None): diff --git a/plugins/security-guidance/tests/test_slow_prompt_metrics.py b/plugins/security-guidance/tests/test_slow_prompt_metrics.py new file mode 100644 index 00000000..fa947507 --- /dev/null +++ b/plugins/security-guidance/tests/test_slow_prompt_metrics.py @@ -0,0 +1,175 @@ +import json +import os +import re +import shutil +import subprocess + +import pytest + +import gitutil +from conftest import git, make_repo, metrics_of, run_hook, ups_payload + +SLOW = 1.2 +STASH = '*"stash create"*' +MOUNTS = ( + "25 30 8:32 / / rw,relatime - ext4 /dev/sdc rw\n" + "60 25 0:50 / /mnt/c rw,noatime - 9p C:\\134 rw,aname=drivers\n" + "61 25 0:51 / /mnt/my\\040disk rw,noatime - 9p D:\\134 rw\n" + "62 60 8:40 / /mnt/c/data rw - ext4 /dev/sdd rw\n" + "63 25 0:52 / /mnt/a\\134b rw - drvfs E:\\134 rw\n" +) + +# The stalling git is a shell script, and on Windows a clean prompt can itself +# take a second. +pytestmark = pytest.mark.skipif(os.name == "nt", reason="needs a shell-script git") + + +@pytest.fixture +def repo(tmp_path): + return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n", "lib.py": "x = 1\n"}) + + +def _slow(hook_env, tmp_path, match): + """hook_env with a `git` first on PATH that stalls on commands matching + `match` (a shell case pattern).""" + shim = tmp_path / "bin" + shim.mkdir(exist_ok=True) + (shim / "git").write_text( + f'#!/bin/sh\ncase "$*" in {match}) sleep {SLOW};; esac\n' + f'exec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + return {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + + +def test_slow_capture_reports_where_the_time_went(repo, hook_env, tmp_path): + rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + m = metrics_of(out) + assert rc == 0 + assert m["ups_ms"] >= SLOW * 1000 + assert m["ups_baseline_ms"] >= SLOW * 1000 + assert m["ups_untracked_ms"] < m["ups_baseline_ms"] + assert m["ups_index_entries"] == 2 + assert not {"ups_no_baseline", "ups_wsl_drive", "ups_baseline_fail"} & set(m) + + +def test_slow_untracked_listing_is_told_apart(repo, hook_env, tmp_path): + env = _slow(hook_env, tmp_path, '*"ls-files"*"--others"*') + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_untracked_ms"] >= SLOW * 1000 + assert m["ups_baseline_ms"] < m["ups_untracked_ms"] + + +def test_slow_prompt_with_stop_review_off_lists_nothing(repo, hook_env, tmp_path): + env = {**_slow(hook_env, tmp_path, STASH), "ENABLE_STOP_REVIEW": "0"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_baseline_ms"] >= SLOW * 1000 + assert m["ups_untracked_ms"] == 0 + + +def test_slow_prompt_without_a_baseline_says_so(hook_env, tmp_path): + empty = tmp_path / "empty" + empty.mkdir() + subprocess.run(["git", "init", "-q", str(empty)], check=True) + env = _slow(hook_env, tmp_path, '*"rev-parse HEAD"*') + m = metrics_of(run_hook(ups_payload(str(empty)), env)[1]) + assert m["ups_no_baseline"] == 1 and "ups_index_entries" not in m + + +def test_git_that_stalls_past_its_timeout_still_reports(repo, hook_env, tmp_path): + """A hung git reads as "not a repository"; the row must still go out.""" + shim = tmp_path / "bin" + shim.mkdir() + (shim / "git").write_text('#!/bin/sh\nexec sleep 6\n') + (shim / "git").chmod(0o755) + env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_no_baseline"] == 1 and m["ups_ms"] >= 5000 + + +def test_failed_snapshot_is_flagged(repo, hook_env, tmp_path): + shim = tmp_path / "bin" + shim.mkdir() + (shim / "git").write_text( + f'#!/bin/sh\ncase "$*" in {STASH}) sleep {SLOW}; exit 1;; esac\n' + f'exec "{shutil.which("git")}" "$@"\n') + (shim / "git").chmod(0o755) + env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["ups_baseline_fail"] == 1 + + +def test_fast_prompt_prints_nothing(repo, hook_env): + rc, out, _ = run_hook(ups_payload(str(repo)), hook_env) + assert rc == 0 and out.strip() == "" + + +def test_slow_launcher_is_reported_on_a_fast_prompt(repo, hook_env): + env = {**hook_env, "SG_LAUNCHER_PROBE_MS": "4350", "SG_LAUNCHER_PROBE_MAX_MS": "4000"} + m = metrics_of(run_hook(ups_payload(str(repo)), env)[1]) + assert m["launcher_probe_ms"] == 4350 and m["ups_ms"] < 1000 + + +def test_other_hosts_get_no_output(repo, hook_env, tmp_path): + env = {k: v for k, v in _slow(hook_env, tmp_path, STASH).items() + if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT")} + env["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1" + assert run_hook(ups_payload(str(repo)), env)[1].strip() == "" + + +def test_row_holds_no_path_and_valid_keys(repo, hook_env, tmp_path): + _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH)) + assert str(repo) not in out and str(tmp_path) not in out + metrics = json.loads(out)["metrics"] + assert all(re.fullmatch(r"[a-z][a-z0-9_]{0,39}", k) for k in metrics) + assert all(isinstance(v, (int, float)) for v in metrics.values()) + + +def test_slow_capture_saves_the_same_baseline(repo, hook_env, tmp_path): + (repo / "app.py").write_text("print('changed')\n") + (repo / "new.txt").write_text("untracked\n") + states = [] + for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, STASH))): + d = tmp_path / name + d.mkdir() + env = {k: v for k, v in env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"} + env["SECURITY_WARNINGS_STATE_DIR"] = str(d) + run_hook(ups_payload(str(repo)), env) + with open(d / "security_warnings_state_s1.json") as f: + states.append(json.load(f)) + fast, slow = states + assert git(repo, "rev-parse", fast["baseline_sha"] + "^{tree}") == \ + git(repo, "rev-parse", slow["baseline_sha"] + "^{tree}") + assert fast["baseline_sha"] != fast["head_at_capture"] + assert "new.txt" in fast["untracked_at_baseline"] + assert fast["untracked_at_baseline"] == slow["untracked_at_baseline"] + + +@pytest.mark.parametrize("path,expected", [ + ("/mnt/c/code/app", True), + ("/mnt/c", True), + ("/mnt/my disk/app", True), + ("/mnt/a\\b/app", True), + ("/mnt/cool/app", False), + ("/home/me/app", False), + ("/mnt/c/data/app", False), +]) +def test_windows_drive_mount(path, expected): + assert gitutil.windows_drive_mount(path, MOUNTS) is expected + + +@pytest.mark.parametrize("junk", ["junk\n", "1 2 - \n", "1 2 3 / /mnt/c rw - \n"]) +def test_windows_drive_mount_skips_malformed_lines(junk): + assert gitutil.windows_drive_mount("/mnt/c/x", junk + MOUNTS) is True + + +def test_wsl_drive_reaches_the_row(monkeypatch): + import security_reminder_hook as hook + monkeypatch.setattr(hook, "on_windows_drive", lambda cwd: True) + assert hook._slow_prompt_metrics("/x", 2.0, 1.5, 0.1, True, 0)["ups_wsl_drive"] == 1 + + +def test_index_entry_count(repo, tmp_path): + assert gitutil.index_entry_count(str(repo / ".git" / "index")) == 2 + assert gitutil.index_entry_count(str(tmp_path / "missing")) is None + (tmp_path / "bad").write_bytes(b"not an index") + assert gitutil.index_entry_count(str(tmp_path / "bad")) is None |
