summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-20 16:44:42 -0700
committerGitHub <noreply@github.com>2026-10-20 16:44:42 -0700
commit6cceb5096bf1e472bd3813ac64653df1c326f758 (patch)
tree846a4468bd47ea5ed63b00d975f26e8d5794b3a0 /plugins
parent6e50442cd64387efad73bab72a47f277b88d8662 (diff)
parent6d4e17c8c4d45de2eba6dce119e56fff18ae43b1 (diff)
Merge pull request #6629 from anthropics/mhegazy/sg-launcher-probe-timing
security-guidance: report how long the launcher waits for interpreter probes
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/_base.py20
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py6
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py7
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh51
-rw-r--r--plugins/security-guidance/tests/test_launcher_probe_timing.py196
5 files changed, 274 insertions, 6 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 59e8e569..e5959e68 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -330,6 +330,26 @@ def _log_usage(usage):
)
+def launcher_probe_metrics():
+ """How long sg-python.sh waited for interpreters to answer its probe.
+
+ Only when this launch's probes took a second or more together, so ordinary
+ rows carry no extra keys: `launcher_probe_ms` is all of them,
+ `launcher_probe_max_ms` the slowest one. Both are capped at an hour (the
+ launcher reads the wall clock, which can jump). Read once: the variables
+ are removed so child processes do not report this launch as their own.
+ """
+ try:
+ slowest = int(os.environ.pop("SG_LAUNCHER_PROBE_MAX_MS", ""))
+ total = int(os.environ.pop("SG_LAUNCHER_PROBE_MS", ""))
+ except ValueError:
+ return {}
+ if total < 1000 or slowest > total:
+ return {}
+ cap = 3_600_000
+ return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)}
+
+
def _usage_metrics():
"""Snapshot the accumulator as metric keys. Returns {} when no API calls
AND no HTTP errors were made so skip-path emits don't burn key budget.
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index fadeae00..d3aaf96b 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -27,7 +27,10 @@ from pathlib import Path
# → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased
# here to match the existing local name (state_dir was already a local var in
# main() and _maybe_emit_user_notice).
-from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
+from _base import (
+ launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir,
+ write_hook_output,
+)
from _base import llm_reviews_switched_off
@@ -973,6 +976,7 @@ if __name__ == "__main__":
# not read the plugin files.
if os.environ.get("SG_LAUNCHER_FALLBACK") == "1":
metrics["launcher_fallback"] = 1
+ metrics.update(launcher_probe_metrics())
response: dict[str, object] = {"metrics": metrics}
# One-time user-visible notice when the agentic reviewer is dead on
# arrival. Uses hookSpecificOutput.additionalContext (SessionStart's
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 99b00ce0..c72e3620 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -86,7 +86,7 @@ from _base import ( # noqa: E402,F401
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
_USAGE_CONTEXT, _log_usage,
- state_dir as _resolve_state_dir,
+ launcher_probe_metrics, state_dir as _resolve_state_dir,
write_hook_output as _write_hook_output,
llm_reviews_switched_off, agent_sdk_installed,
)
@@ -213,6 +213,9 @@ CONTINUATION_SUFFIX = (
# Extra keys emit_metrics appends to every row this invocation emits.
_TAIL_METRICS: Dict[str, Any] = {}
+# The launcher's slow interpreter probes, if any. After everything else.
+_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics()
+
# Reviewer context diagnostics from llm.agentic_review, most useful first.
_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls")
@@ -310,6 +313,7 @@ def emit_metrics(
# managed-mcp.json) and the review was started again without it.
tail["strict_mcp_off"] = 1
tail.update(_TAIL_METRICS)
+ tail.update(_LAUNCHER_METRICS)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
if rewake_summary:
@@ -2919,6 +2923,7 @@ def main():
"rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)),
"rule_mask": rule_names_to_mask(raw_names),
**({"pv": _PV} if _PV else {}),
+ **_LAUNCHER_METRICS,
}
if all_guidance:
output["hookSpecificOutput"] = {
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index a02c7d6c..e0c2730e 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -106,7 +106,7 @@ probe() {
exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null
}
-# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`.
+# Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below).
note_unreadable() {
[ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|"
return 0
@@ -119,6 +119,49 @@ on_path() {
command -v "$1" >/dev/null 2>&1
}
+# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms
+# metrics the hook reports. Measurement only: `ask` is `v=$(probe ...)` with a
+# clock around it, and changes neither which interpreter runs nor how long a
+# probe may take. EPOCHREALTIME needs bash 5; older bash (macOS /bin/bash) only
+# has whole seconds, where a difference of 1 can be a few milliseconds: there
+# a single probe counts from 2 s, and the total is first probe to last.
+unset SG_LAUNCHER_PROBE_MS SG_LAUNCHER_PROBE_MAX_MS
+sg_probe_ms=0
+sg_probe_max_ms=0
+sg_probe_first=""
+sg_coarse=""
+sg_clock() {
+ # Sets $sg_now (ms) without starting a process.
+ case "${EPOCHREALTIME:-}" in
+ [0-9]*[.,][0-9][0-9][0-9][0-9][0-9][0-9]) # the decimal point follows the locale
+ sg_now=${EPOCHREALTIME//[!0-9]/}
+ sg_now=$((10#$sg_now / 1000)) ;;
+ *)
+ sg_coarse=1
+ sg_now=$((SECONDS * 1000)) ;;
+ esac
+}
+ask() {
+ # Sets $v; same exit status as probe.
+ local rc=0 t0 ms
+ sg_clock; t0=$sg_now
+ [ -n "$sg_probe_first" ] || sg_probe_first=$t0
+ v=$(probe "$@") || rc=$?
+ sg_clock; ms=$((sg_now - t0))
+ if [ -n "$sg_coarse" ]; then
+ [ "$ms" -ge 2000 ] || ms=0
+ sg_probe_ms=$((sg_now - sg_probe_first))
+ [ "$sg_probe_ms" -ge 2000 ] || sg_probe_ms=0
+ elif [ "$ms" -gt 0 ]; then
+ sg_probe_ms=$((sg_probe_ms + ms))
+ fi
+ [ "$ms" -le "$sg_probe_max_ms" ] || sg_probe_max_ms=$ms
+ if [ "$sg_probe_ms" -gt 0 ]; then
+ export SG_LAUNCHER_PROBE_MS=$sg_probe_ms SG_LAUNCHER_PROBE_MAX_MS=$sg_probe_max_ms
+ fi
+ return $rc
+}
+
# True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires
# Python >= 3.10; below that, pip install fails ("No matching distribution")
# and the LLM-powered review (Stop / commit / push) silently no-ops while
@@ -139,7 +182,7 @@ is_sdk_compatible() {
# than this list are pass 2b.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
on_path "$cmd" || continue
- v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
@@ -154,7 +197,7 @@ for cmd in "python3" "python" "py -3"; do
# shellcheck disable=SC2086
on_path $cmd || continue
# shellcheck disable=SC2086
- v=$(probe $cmd) || { note_unreadable "$cmd"; continue; }
+ ask $cmd || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
@@ -229,7 +272,7 @@ sg_tried="|"
for cmd in "${sg_candidates[@]}"; do
case "$sg_tried" in *"|$cmd|"*) continue ;; esac
sg_tried="$sg_tried$cmd|"
- v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
diff --git a/plugins/security-guidance/tests/test_launcher_probe_timing.py b/plugins/security-guidance/tests/test_launcher_probe_timing.py
new file mode 100644
index 00000000..69b867a6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_probe_timing.py
@@ -0,0 +1,196 @@
+"""sg-python.sh times its interpreter probes and the hooks report slow ones.
+
+Measurement only: the launcher still waits for every probe and still picks
+the interpreter it picked before.
+
+The slow interpreter is a shell wrapper around the real one, so these tests
+need a POSIX shell.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR, edit_payload, metrics_of, run_hook, stop_payload
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+
+
+def _bash_major():
+ try:
+ return int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"],
+ capture_output=True, text=True, timeout=30).stdout)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return 0
+
+
+BASH5 = sys.platform != "win32" and _bash_major() >= 5
+
+# Prints what the launcher handed over, then its stdin.
+HOOK = (
+ "import os, sys\n"
+ "print('max=' + os.environ.get('SG_LAUNCHER_PROBE_MAX_MS', ''))\n"
+ "print('total=' + os.environ.get('SG_LAUNCHER_PROBE_MS', ''))\n"
+ "print('name=' + os.environ.get('SG_NAME', ''))\n"
+ "print('stdin=' + sys.stdin.read())\n"
+)
+
+WRAPPER = """#!{bash}
+# Answers the launcher's `-c` probe after DELAY seconds; RC != 0 fails it.
+if [ "${{1:-}}" = "-c" ]; then
+ sleep {delay}
+ [ {rc} -eq 0 ] || exit {rc}
+fi
+SG_NAME={name} exec '{real}' "$@"
+"""
+
+
+def _python(bindir, name, delay=0, rc=0):
+ bindir.mkdir(parents=True, exist_ok=True)
+ p = bindir / name
+ p.write_text(WRAPPER.format(bash=BASH, delay=delay, rc=rc, name=name, real=REAL))
+ p.chmod(0o755)
+
+
+def _run(bindir, script, extra_env=None, shim=SHIM):
+ env = {"PATH": f"{bindir}{os.pathsep}/usr/bin{os.pathsep}/bin", "HOME": os.environ.get("HOME", "/")}
+ env.update(extra_env or {})
+ r = subprocess.run([BASH, str(shim), str(script)], input="payload", capture_output=True,
+ text=True, timeout=60, env=env)
+ assert r.returncode == 0, r.stderr
+ return dict(line.split("=", 1) for line in r.stdout.splitlines())
+
+
+@pytest.fixture
+def script(tmp_path):
+ p = tmp_path / "hook.py"
+ p.write_text(HOOK)
+ return p
+
+
+@pytest.fixture
+def bindir(tmp_path):
+ """A PATH entry with only what the tests put there (plus sleep)."""
+ return tmp_path / "bin"
+
+
+def _only_these(bindir):
+ # Hide the system interpreters: PATH is bindir plus /usr/bin:/bin, so every
+ # name the launcher tries gets an entry here, failing unless a test set it.
+ for name in ("python3.13", "python3.12", "python3.11", "python3.10", "python3", "python", "py"):
+ if not (bindir / name).exists():
+ _python(bindir, name, rc=1)
+
+
+@pytest.mark.skipif(not BASH5, reason="millisecond clock needs bash 5")
+def test_fast_probes_are_timed_in_milliseconds(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 0 < int(out["max"]) <= int(out["total"])
+
+
+def test_slow_probe_is_waited_for_and_measured(bindir, script):
+ _python(bindir, "python3", delay=2.2)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ # Still the first name that answers, however long it took.
+ assert out["name"] == "python3" and out["stdin"] == "payload"
+ assert 2000 <= int(out["max"]) < 10000
+ assert int(out["total"]) >= int(out["max"])
+
+
+def test_slow_failing_probe_counts_towards_the_wait(bindir, script):
+ _python(bindir, "python3", delay=2.2, rc=49)
+ _python(bindir, "python")
+ _only_these(bindir)
+ out = _run(bindir, script)
+ assert out["name"] == "python"
+ assert int(out["max"]) >= 2000
+
+
+def test_inherited_values_are_not_reported_again(bindir, script):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, {"SG_LAUNCHER_PROBE_MAX_MS": "999999", "SG_LAUNCHER_PROBE_MS": "999999"})
+ assert out["max"] != "999999" and out["total"] != "999999"
+
+
+@pytest.fixture
+def whole_second_shim(tmp_path):
+ """The launcher as bash 3.2 runs it: no EPOCHREALTIME, only SECONDS."""
+ src = SHIM.read_text()
+ assert 'case "${EPOCHREALTIME:-}" in' in src
+ p = tmp_path / "sg-python-coarse.sh"
+ p.write_text(src.replace('case "${EPOCHREALTIME:-}" in', 'case "" in'))
+ return p
+
+
+def test_whole_second_clock_ignores_fast_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3")
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ # A probe of a few ms can straddle a second; that is not reported as 1 s.
+ assert out["max"] == "" and out["total"] == ""
+
+
+def test_whole_second_clock_measures_slow_probes(bindir, script, whole_second_shim):
+ _python(bindir, "python3", delay=2.2)
+ _only_these(bindir)
+ out = _run(bindir, script, shim=whole_second_shim)
+ assert out["name"] == "python3"
+ assert int(out["max"]) in (2000, 3000) and int(out["total"]) >= int(out["max"])
+
+
+@pytest.mark.parametrize("slowest,total,expected", [
+ ("4200", "4350", {"launcher_probe_ms": 4350, "launcher_probe_max_ms": 4200}),
+ ("900", "1500", {"launcher_probe_ms": 1500, "launcher_probe_max_ms": 900}),
+ ("999", "999", {}),
+ ("86400000", "86400000", {"launcher_probe_ms": 3600000, "launcher_probe_max_ms": 3600000}),
+ ("5000", "5", {}),
+ ("", "", {}),
+ ("junk", "5", {}),
+])
+def test_stop_hook_reports_only_slow_probes(hook_env, workspace, slowest, total, expected):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": slowest, "SG_LAUNCHER_PROBE_MS": total}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ m = metrics_of(out)
+ assert m is not None, err
+ assert {k: v for k, v in m.items() if k.startswith("launcher_probe")} == expected
+
+
+def test_launcher_keys_come_last(hook_env, workspace):
+ """Claude Code keeps the first 20 keys, so these never displace another."""
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ rc, out, err = run_hook(stop_payload(repo), env)
+ assert list(metrics_of(out))[-2:] == ["launcher_probe_ms", "launcher_probe_max_ms"]
+
+
+def test_edit_hook_reports_slow_probes_on_pattern_rows(hook_env, workspace):
+ _, repo = workspace
+ env = {**hook_env, "SG_LAUNCHER_PROBE_MAX_MS": "4200", "SG_LAUNCHER_PROBE_MS": "4350"}
+ payload = edit_payload(repo, repo / "app.py", new_string="import os\nos.system('ls ' + x)\n")
+ rc, out, err = run_hook(payload, env)
+ m = metrics_of(out)
+ assert m is not None and "rule_id" in m, (out, err)
+ assert m["launcher_probe_ms"] == 4350 and m["launcher_probe_max_ms"] == 4200
+
+
+def test_values_are_read_once(monkeypatch):
+ import _base
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MAX_MS", "7000")
+ monkeypatch.setenv("SG_LAUNCHER_PROBE_MS", "7100")
+ assert _base.launcher_probe_metrics() == {"launcher_probe_ms": 7100, "launcher_probe_max_ms": 7000}
+ assert "SG_LAUNCHER_PROBE_MS" not in os.environ and _base.launcher_probe_metrics() == {}