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/security-guidance/hooks | |
| 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/security-guidance/hooks')
| -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 |
3 files changed, 97 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): |
