You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(guardrails): block-hook-bypass.sh (performance) averages 75.1s and timed out 105x - reduce process spawns #3513
Child of #3508 (Windows process-creation tax). This issue covers one hook: block-hook-bypass.sh (performance) in the guardrails plugin.
Measured
Plugin
guardrails
Hook
block-hook-bypass.sh (performance)
Event(s)
PreToolUse:Bash + PreToolUse:PowerShell
Timeouts in window
105
Average duration
75.1s
Worst observed
134.1s
Configured timeout
15 s
Every recorded run exceeded the 15 s timeout, so this guard is killed before it renders a verdict. It currently costs wall-clock without providing protection on this platform.
Context from the parent
Process creation on the affected host costs 0.3-0.9 s per spawn (bash -c true = 661 ms, jq -n 1 = 908 ms, cmd.exe /c exit = 872 ms, against ~3-5 ms on a healthy host). User CPU time is ~1% of wall-clock, so the fix is reducing the number of process spawns, not optimizing script logic. See #3508 for the full measurement and environment detail.
Specific guidance
52 external call sites. Correctness bug tracked separately in #3507 (fails CLOSED on a Windows stdin stall) - fix that first, then the spawn count.
Acceptance criteria
This hook makes no more than 2 external process spawns on its common path (its own shell plus at most one jq).
Subprocess calls to grep/sed/cut/tr/basename/dirname on the hot path are replaced with bash builtins.
Where the guard only applies to a subset of commands, the matcher or an early guard clause exits before any spawn for non-matching invocations.
Existing behavioural tests still pass; the guard still blocks what it blocked before.
Measured on a Windows host, a single run of this hook completes in under 2 s.
Method
Counts from ~/.claude/projects/**/*.jsonlhook_cancelled attachments with timedOut: true, across 236 sessions, 2026-08-23 to 2026-08-31.
Shared correction (applies to every child of #3508)
1. The "15 s" timeout in the table above is wrong for most of these hooks. Timeouts are declared per hook in each plugin hooks/hooks.json, and they vary widely. Verified against the installed manifests and cross-checked against the timeoutMs field the harness records in transcripts:
Observed timeoutMs distribution across the transcript corpus confirms it: 1,365 PreToolUse:Bash timeouts at 15,000 ms (source-control), 246 at 60,000 ms and 384 PreToolUse:PowerShell at 60,000 ms (guardrails), Stop at 10,000 / 15,000 / 20,000 ms.
This makes the guardrails hooks worse than reported, not better — each one burns a full 60 seconds before being killed, not 15.
2. The acceptance criteria should cite the repo's existing budget, not the ad-hoc ones I wrote.docs/conventions/hook-budget/README.md (adopted in #1809, surfaced by .claude/rules/hook-budget.md on plugins/*/hooks/**) already defines the binding ceiling:
Surface
Budget
Per tool call (PreToolUse + PostToolUse for one matcher)
<= 1 s typical, <= 2 s worst-case
Per turn (Stop / notification-shaped)
<= 500 ms
Measured as parallel wall time, not the sum. Rule 1 of that doc requires a plugin adding or widening an always-on hook to state its measured share in its README; Rule 2 states the budget never relaxes to absorb an overage. Use those numbers as the bar. My "under 2 s on a Windows host" was an accidental near-restatement of the per-tool-call worst case; the per-turn 500 ms figure I did not have at all, and it binds every Stop-event child.
3. Prior art exists and should not be re-derived.#1403 (closed, needs-human) captures the spawn-reduction work from the unmerged PR #1385, including:
hook::jq_fields batched field extraction in lib/hook-utils.sh, replacing per-field jq calls across eight guards
a strip_quoted_spans shell-builtin replacement for a printf | sed | sed pipeline
a deferred git rev-parse --is-inside-work-tree probe in hardcoded-path-check.sh
a census of 65 process spawns per Bash tool call, and a measured 437 ms per-spawn unit price
It also records why #1385 did not merge: a fresh-context verification found four contract-test regressions, two of which failed open. Any revival must clear those first.
4. hook-utils.sh is synced, not per-plugin. It exists in 17 copies across plugins/*/hooks/hook-utils.sh, delivered by scripts/sync-hook-utils.sh. A change there must go through that script with all copies verified identical — editing one plugin's copy will be reverted or will diverge the fleet.
5. Validate with scripts/affected-tests.sh --run (add --explain to see suite selection), per the repo AGENTS.md. A changed file mapping to zero suites is an error, not "nothing to run".
6. Reference baseline for the host. The budget doc's reference measurements (2026-07-31, Windows 11 + Git Bash) are bash -c : ~ 80 ms and python3 -c pass ~ 160 ms, with the per-Bash-call always-on set at **~ 5.9 s parallel wall**. The host in #3508 measures a bimodal no-op spawn at 180-2,841 ms (median 1,108 ms) at 501 concurrent processes — 2-35x worse than that reference. Report the spawn baseline alongside any timing so a result on a healthy box is not mistaken for a pass on a contended one.
Read-and-report pass over plugins/guardrails/hooks/block-hook-bypass.sh at origin/main (a34a96bc). This lane does not close issues; the recommendation below is for the triage lane.
Method
Guards no longer run as standalone hooks. Since #1403's dispatcher work, every guard named in the Bash|PowerShell matcher is sourced in-process by run-guards.sh, which calls hook::buffer_stdin once for the whole batch and primes the jq field cache once. I confirmed that on current main by reading run-guards.sh (stdin at lines 138-150, jq priming at 152-200) and by measurement, not by inference.
Counting was done with strace -f -e trace=clone,clone3,fork,vfork,execve on the real invocation path, with two separate counters:
execve (successful only, failed PATH probes discarded): PATH-visible program images.
clone/fork: process creations including pure subshells. A $(...) or < <(...) that never execs still costs a Win32 process under MSYS2 fork emulation, and perf(context-guard): PostToolBatch: context-zone crossing averages 73.0s and timed out 10x - reduce process spawns #3520 showed an xtrace command-position count reads 2 where the kernel makes 8. The plugin's own budget test (run-guards.test.sh:168-215) counts with PATH shims and its own comment concedes "function forks are invisible to them", so nothing in the suite pins this dimension today.
Per-guard figures are deltas against a dispatcher run carrying a single no-op guard. HOOK_TELEMETRY_SINK unset (fleet default). Linux, bash 5.2.21, jq present.
What the issue claimed vs what main has
Named overhead
State on main
52 external call sites
Not reproducible as a runtime figure; see the maintainer addendum on #3514. Measured runtime spawns below.
Gone. Lines 62-65 are now _HOOK_SELF="${BASH_SOURCE[0]%/*}" with the bare-filename fallback.
<= 2 external process spawns on the common path
Met on execve, missed on process creations.
grep/sed/cut/tr/basename/dirname on the hot path
Met. Zero on the common path. One tr appears on the block path only, from hook::json_escape (hook-utils.sh:73).
Behavioural tests still pass
Met.block-hook-bypass.test.sh PASS=602 FAIL=0.
Under 2 s on a Windows host
Unverified. Measured on Linux; no Windows host in this lane.
Which commit changed it
a5f5e799 (#3781, "drop dirname and sed execs from the always-on path"), not #3788. #3788 (5101f5a2) does not touch this file — confirmed against its file list.
Batch-level history on git status --short (whole Bash|PowerShell matcher, all eight guards):
done < <(printf '%s\n' "$NORMALIZED_SEGMENTS") in staged_write_move_bypass
block-hook-bypass.sh:1330
same, cat_redirect_bypass
block-hook-bypass.sh:1403
same, producer_redirect_bypass
Residual the scout's read missed
Five of the seven are in this file and specific to it:
Line 159, unconditional SUBJECT.block-windows-drive-tmp.sh:186 already carries the fixed shape: SUBJECT is resolved lazily insideemit_tel, behind hook::telemetry_enabled, so it costs nothing when no sink is wired. Lines 159 pays that fork on every Bash tool call regardless. Same fix applies verbatim.
Lines 474, 1305, 1330, 1403. Four done < <(printf '%s\n' …) process substitutions over strings the script already holds in a variable. The comments correctly rule out a here-string (a >=64 KiB here-string deadlocks), but a fork-free split is available: peel lines with line="${rest%%$'\n'*}"; rest="${rest#*$'\n'}" in a while [[ -n "$rest" ]] loop. That removes four process creations without touching any matcher.
Line 478's $(strip_literals …) could take the _to <var> convention hook-utils already uses for its path helpers.
Two are shared, not this file's to fix: hook::buffer_stdin's $( ) capture (see the fleet item below) and the dispatcher's own per-guard isolation fork (run-guards.sh:211, already tracked as #3685).
Fleet item worth its own issue: a hook::buffer_stdin_to <var> form in lib/hook-utils.sh (synced to 17 copies via scripts/sync-hook-utils.sh). Under the dispatcher the payload is already in RUN_GUARDS_INPUT, and INPUT=$(hook::buffer_stdin) copies it back out through a fork and a pipe. That is 1 fork per guard, 8 of the 36 process creations on every Bash tool call, and the single largest remaining win in this plugin.
Recommendation
Keep open, re-scoped to the fork count. The named defect (the dirname exec) is gone and the execve criterion is met, but 7 process creations on the common path is materially above the issue's own "<= 2 spawns" bar on the host this campaign is about, and 5 of those 7 are in-file and independently fixable. Retiring this one now would drop a real, localized, measured win. If triage prefers, close this and open a successor naming lines 159, 474, 1305, 1330 and 1403.
Activity
kyle-sexton commentedon Aug 31, 2026
Shared correction (applies to every child of #3508)
1. The "15 s" timeout in the table above is wrong for most of these hooks. Timeouts are declared per hook in each plugin
hooks/hooks.json, and they vary widely. Verified against the installed manifests and cross-checked against thetimeoutMsfield the harness records in transcripts:Observed
timeoutMsdistribution across the transcript corpus confirms it: 1,365PreToolUse:Bashtimeouts at 15,000 ms (source-control), 246 at 60,000 ms and 384PreToolUse:PowerShellat 60,000 ms (guardrails), Stop at 10,000 / 15,000 / 20,000 ms.This makes the guardrails hooks worse than reported, not better — each one burns a full 60 seconds before being killed, not 15.
2. The acceptance criteria should cite the repo's existing budget, not the ad-hoc ones I wrote.
docs/conventions/hook-budget/README.md(adopted in #1809, surfaced by.claude/rules/hook-budget.mdonplugins/*/hooks/**) already defines the binding ceiling:PreToolUse+PostToolUsefor one matcher)Stop/ notification-shaped)Measured as parallel wall time, not the sum. Rule 1 of that doc requires a plugin adding or widening an always-on hook to state its measured share in its README; Rule 2 states the budget never relaxes to absorb an overage. Use those numbers as the bar. My "under 2 s on a Windows host" was an accidental near-restatement of the per-tool-call worst case; the per-turn 500 ms figure I did not have at all, and it binds every Stop-event child.
3. Prior art exists and should not be re-derived. #1403 (closed,
needs-human) captures the spawn-reduction work from the unmerged PR #1385, including:hook::jq_fieldsbatched field extraction inlib/hook-utils.sh, replacing per-fieldjqcalls across eight guardsstrip_quoted_spansshell-builtin replacement for aprintf | sed | sedpipelinegit rev-parse --is-inside-work-treeprobe inhardcoded-path-check.shIt also records why #1385 did not merge: a fresh-context verification found four contract-test regressions, two of which failed open. Any revival must clear those first.
4.
hook-utils.shis synced, not per-plugin. It exists in 17 copies acrossplugins/*/hooks/hook-utils.sh, delivered byscripts/sync-hook-utils.sh. A change there must go through that script with all copies verified identical — editing one plugin's copy will be reverted or will diverge the fleet.5. Validate with
scripts/affected-tests.sh --run(add--explainto see suite selection), per the repo AGENTS.md. A changed file mapping to zero suites is an error, not "nothing to run".6. Reference baseline for the host. The budget doc's reference measurements (2026-07-31, Windows 11 + Git Bash) are
bash -c :~ 80 ms andpython3 -c pass~ 160 ms, with the per-Bash-call always-on set at **~ 5.9 s parallel wall**. The host in #3508 measures a bimodal no-op spawn at 180-2,841 ms (median 1,108 ms) at 501 concurrent processes — 2-35x worse than that reference. Report the spawn baseline alongside any timing so a result on a healthy box is not mistaken for a pass on a contended one.kyle-sexton commentedon Sep 6, 2026
Verification: PARTLY FIXED
Read-and-report pass over
plugins/guardrails/hooks/block-hook-bypass.shatorigin/main(a34a96bc). This lane does not close issues; the recommendation below is for the triage lane.Method
Guards no longer run as standalone hooks. Since #1403's dispatcher work, every guard named in the
Bash|PowerShellmatcher issourced in-process byrun-guards.sh, which callshook::buffer_stdinonce for the whole batch and primes the jq field cache once. I confirmed that on current main by readingrun-guards.sh(stdin at lines 138-150, jq priming at 152-200) and by measurement, not by inference.Counting was done with
strace -f -e trace=clone,clone3,fork,vfork,execveon the real invocation path, with two separate counters:$(...)or< <(...)that never execs still costs a Win32 process under MSYS2 fork emulation, and perf(context-guard): PostToolBatch: context-zone crossing averages 73.0s and timed out 10x - reduce process spawns #3520 showed an xtrace command-position count reads 2 where the kernel makes 8. The plugin's own budget test (run-guards.test.sh:168-215) counts with PATH shims and its own comment concedes "function forks are invisible to them", so nothing in the suite pins this dimension today.Per-guard figures are deltas against a dispatcher run carrying a single no-op guard.
HOOK_TELEMETRY_SINKunset (fleet default). Linux, bash 5.2.21, jq present.What the issue claimed vs what main has
source "$(dirname "${BASH_SOURCE[0]}")/hook-utils.sh"_HOOK_SELF="${BASH_SOURCE[0]%/*}"with the bare-filename fallback.<= 2 external process spawns on the common pathtrappears on the block path only, fromhook::json_escape(hook-utils.sh:73).block-hook-bypass.test.shPASS=602 FAIL=0.Which commit changed it
a5f5e799(#3781, "drop dirname and sed execs from the always-on path"), not #3788. #3788 (5101f5a2) does not touch this file — confirmed against its file list.Batch-level history on
git status --short(wholeBash|PowerShellmatcher, all eight guards):a5f5e799^(pre-#3781)a5f5e799(#3781)5101f5a2(#3788)273c20fe(#3820)Measured counts for this guard
On
git status --shortand ongit commit -m "feat: thing", inside the dispatcher:Attributed by a
BASHPID-tracing DEBUG trap on the dispatcher's isolation subshell:block-hook-bypass.sh:112INPUT=$(hook::buffer_stdin)block-hook-bypass.sh:159SUBJECT=$(hook::extract_bash_subject "$TOOL_NAME" "$COMMAND"), file scope, unconditionalblock-hook-bypass.sh:478EXECUTABLE=$(strip_literals "$COMMAND")block-hook-bypass.sh:474done < <(printf '%s\n' "$cmd")instrip_literalsblock-hook-bypass.sh:1305done < <(printf '%s\n' "$NORMALIZED_SEGMENTS")instaged_write_move_bypassblock-hook-bypass.sh:1330cat_redirect_bypassblock-hook-bypass.sh:1403producer_redirect_bypassResidual the scout's read missed
Five of the seven are in this file and specific to it:
block-windows-drive-tmp.sh:186already carries the fixed shape: SUBJECT is resolved lazily insideemit_tel, behindhook::telemetry_enabled, so it costs nothing when no sink is wired. Lines 159 pays that fork on every Bash tool call regardless. Same fix applies verbatim.done < <(printf '%s\n' …)process substitutions over strings the script already holds in a variable. The comments correctly rule out a here-string (a >=64 KiB here-string deadlocks), but a fork-free split is available: peel lines withline="${rest%%$'\n'*}"; rest="${rest#*$'\n'}"in awhile [[ -n "$rest" ]]loop. That removes four process creations without touching any matcher.$(strip_literals …)could take the_to <var>convention hook-utils already uses for its path helpers.Two are shared, not this file's to fix:
hook::buffer_stdin's$( )capture (see the fleet item below) and the dispatcher's own per-guard isolation fork (run-guards.sh:211, already tracked as #3685).Fleet item worth its own issue: a
hook::buffer_stdin_to <var>form inlib/hook-utils.sh(synced to 17 copies viascripts/sync-hook-utils.sh). Under the dispatcher the payload is already inRUN_GUARDS_INPUT, andINPUT=$(hook::buffer_stdin)copies it back out through a fork and a pipe. That is 1 fork per guard, 8 of the 36 process creations on every Bash tool call, and the single largest remaining win in this plugin.Recommendation
Keep open, re-scoped to the fork count. The named defect (the
dirnameexec) is gone and the execve criterion is met, but 7 process creations on the common path is materially above the issue's own "<= 2 spawns" bar on the host this campaign is about, and 5 of those 7 are in-file and independently fixable. Retiring this one now would drop a real, localized, measured win. If triage prefers, close this and open a successor naming lines 159, 474, 1305, 1330 and 1403.Generated by Claude Code
perf(guardrails): block-hook-bypass drops six forks that never exec (#…
perf(guardrails): block-hook-bypass drops six forks that never exec (#…
perf(guardrails): block-hook-bypass drops six forks that never exec (#…