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-noncanonical-commit.sh averages 78.0s and timed out 91x - reduce process spawns #3514
Child of #3508 (Windows process-creation tax). This issue covers one hook: block-noncanonical-commit.sh in the guardrails plugin.
Measured
Plugin
guardrails
Hook
block-noncanonical-commit.sh
Event(s)
PreToolUse:Bash + PreToolUse:PowerShell
Timeouts in window
91
Average duration
78.0s
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
110 external call sites, second-highest in the set. Only relevant to git commit invocations.
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.
Static call-site counts do not reproduce — treat them as indicative only. An independent pass on shipped 0.29.24 using the stated pattern yields, for block-dangerous-git.sh, 184 with comments / 163 lines-with-match / 44 comment-stripped — none of which is the published 127. The ordering survives under every method (block-dangerous-git.sh is highest), so #3529's headline stands, but the absolute numbers should not be quoted without pinning the exact command and version. #3508's Method section needs that pin.
The spawn-count criterion is the one that matters and it is unaffected: it is measured directly by PATH shim on the executed path, not inferred from source greps.
Verification: PARTLY FIXED, and the credited commit is wrong
Read-and-report pass over plugins/guardrails/hooks/block-noncanonical-commit.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. Every guard 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. Verified on current main by reading the dispatcher and by measurement.
Counted with strace -f -e trace=clone,clone3,fork,vfork,execve, two separate counters: successful execve (PATH-visible program images, failed PATH probes discarded) and clone/fork (process creations including pure subshells, which is what an MSYS2 fork costs on the affected host). An xtrace command-position count is not used: #3520 showed it reads 2 where the kernel makes 8. The plugin's own budget test (run-guards.test.sh:168-215) uses PATH shims and its own comment concedes forks are invisible to them, so nothing in the suite pins the fork dimension.
Per-guard figures are deltas against a dispatcher run carrying a single no-op guard. HOOK_TELEMETRY_SINK unset. Linux, bash 5.2.21, jq present.
Per-guard delta for this file specifically: at 5101f5a2 it contributed 2 git execs and 8 process creations; at 273c20fe and on current main it contributes 0 execs and 3 process creations. So #3788 gets credit for the 78 -> 67 ms parse saving, and #3820 gets credit for the spawns.
What the issue claimed vs what main has
Named overhead
State on main
110 external call sites, "second-highest in the set"
Withdrawn by the maintainer addendum above; static counts do not reproduce. Runtime figures below.
<= 2 external process spawns on the common path
Met on execve (0 contributed; the batch's 2 jq are the dispatcher's, amortized across all eight guards). Missed on process creations (3).
grep/sed/cut/tr/basename/dirname on the hot path
Met. Zero on the common path.
Early exit before any spawn for non-matching invocations
Met.git status --short and a plain git commit -m "feat: thing" both cost 0 execs.
Behavioural tests still pass
Met.block-noncanonical-commit.test.sh PASS=216 FAIL=0. The multi-line -m block still fires (rc 2).
Under 2 s on a Windows host
Unverified. Measured on Linux.
Measured process creations, attributed
Traced with a BASHPID-logging DEBUG trap on the dispatcher's isolation subshell:
while IFS= read -rN1 c; …; done < <(printf '%s' "$cmd") in hook::bash_parse_segments
shared library
One git exec still appears on the block path (a multi-line -m message), from the alias/repo resolution. That is off the common path and is not what this issue asked about.
Residual the scout's read missed
Line 177 is a free win.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 (the fleet default). Line 177 pays the fork on every Bash tool call regardless of whether telemetry is on. block-hook-bypass.sh:159 and block-no-verify.sh:133 have the same defect.
The other two are shared, not this file's to fix:
hook::buffer_stdin_to <var> 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; INPUT=$(hook::buffer_stdin) copies it back out through a fork and a pipe. 1 fork per guard, 8 of the 36 process creations per Bash tool call. Largest remaining win in the plugin, and it deserves its own issue.
hook-utils.sh:2717, the per-character parse loop fed by a process substitution.
Also unaddressed by any of the three commits: the batch spends 2 jq, not the 1 this issue's criterion allows. The second is hook::json_complete's validity probe (hook-utils.sh:1386, called from buffer_stdin at 1600).
Recommendation
Close as fixed, with the residual re-filed. The overheads this issue actually names are gone and the guard contributes zero external process spawns on its common path. The one in-file residual (line 177) is a single-line change shared with #3513 and #3518; the rest is shared-library work. Suggest a successor issue covering the lazy-SUBJECT hoist in all three guards plus hook::buffer_stdin_to, rather than keeping this one open. Note for the record that the closing commit is 273c20fe (#3820), not #3788.
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 Aug 31, 2026
Addendum: hook file paths, matcher corrections, and two withdrawn comparative claims.
Several children named no script file, which left a pickup agent to hunt. Verified paths:
hooks/pr-body-linkage-gate.sh(+pr-linkage-mcp-gate.shon the^mcp__github__(create|update)_pull_request$matcher; sharedpr-linkage-validator.sh)hooks/worktree-add-containment-gate.sh(PostToolUse siblingworktree-add-claim-gate.sh)hooks/hook-failure-audit.shhooks/lane-stop-gate.shhooks/zone-crossing-inject.shMatcher corrections:
zone-crossing-inject.shalso fires onUserPromptSubmit, not onlyPostToolBatch. That changes its cost model: it is both a per-tool-batch and a per-turn cost, so it draws on the <= 500 ms per-turn ceiling as well.PreToolUse:Edit. The actual matcher isWrite|Edit|NotebookEditat timeout 60.block-windows-drive-tmp.shis registered onWrite|Edit|MultiEdit|NotebookEditin addition to the Bash/PowerShell matcher. The issue accounted for only the latter. See also block-windows-drive-tmp: non-Windows host gate leaves large payloads undrained on stdin #3504, which touches the same file (stdin drain).Two comparative claims withdrawn:
hook-utils.shat 113.Static call-site counts do not reproduce — treat them as indicative only. An independent pass on shipped 0.29.24 using the stated pattern yields, for
block-dangerous-git.sh, 184 with comments / 163 lines-with-match / 44 comment-stripped — none of which is the published 127. The ordering survives under every method (block-dangerous-git.shis highest), so #3529's headline stands, but the absolute numbers should not be quoted without pinning the exact command and version. #3508's Method section needs that pin.The spawn-count criterion is the one that matters and it is unaffected: it is measured directly by PATH shim on the executed path, not inferred from source greps.
kyle-sexton commentedon Sep 6, 2026
Verification: PARTLY FIXED, and the credited commit is wrong
Read-and-report pass over
plugins/guardrails/hooks/block-noncanonical-commit.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. Every guard 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. Verified on current main by reading the dispatcher and by measurement.Counted with
strace -f -e trace=clone,clone3,fork,vfork,execve, two separate counters: successful execve (PATH-visible program images, failed PATH probes discarded) and clone/fork (process creations including pure subshells, which is what an MSYS2 fork costs on the affected host). An xtrace command-position count is not used: #3520 showed it reads 2 where the kernel makes 8. The plugin's own budget test (run-guards.test.sh:168-215) uses PATH shims and its own comment concedes forks are invisible to them, so nothing in the suite pins the fork dimension.Per-guard figures are deltas against a dispatcher run carrying a single no-op guard.
HOOK_TELEMETRY_SINKunset. Linux, bash 5.2.21, jq present.Correction: #3788 is not what fixed this
The file was changed by three commits, and #3788 is the one that changed its spawn count least:
a5f5e799(#3781)source "$(dirname …)"replaced by${BASH_SOURCE[0]%/*}at lines 93-96dirnameexec5101f5a2(#3788)lib/powershell/ps-command.shsource into theif [[ "$TOOL_NAME" == "PowerShell" ]]branch (now lines 962-981)273c20fe(#3820)gitexecs and 5 process creations from this guard on a benign Bash callBatch-level history on
git status --short(whole matcher, all eight guards):a5f5e799^(pre-#3781)a5f5e799(#3781)5101f5a2(#3788)273c20fe(#3820)Per-guard delta for this file specifically: at
5101f5a2it contributed 2gitexecs and 8 process creations; at273c20feand on current main it contributes 0 execs and 3 process creations. So #3788 gets credit for the 78 -> 67 ms parse saving, and #3820 gets credit for the spawns.What the issue claimed vs what main has
<= 2 external process spawns on the common pathgit status --shortand a plaingit commit -m "feat: thing"both cost 0 execs.block-noncanonical-commit.test.shPASS=216 FAIL=0. The multi-line-mblock still fires (rc 2).Measured process creations, attributed
Traced with a
BASHPID-logging DEBUG trap on the dispatcher's isolation subshell:block-noncanonical-commit.sh:142INPUT=$(hook::buffer_stdin)block-noncanonical-commit.sh:177SUBJECT=$(hook::extract_bash_subject …), file scope, unconditionalhook-utils.sh:2717while IFS= read -rN1 c; …; done < <(printf '%s' "$cmd")inhook::bash_parse_segmentsOne
gitexec still appears on the block path (a multi-line-mmessage), from the alias/repo resolution. That is off the common path and is not what this issue asked about.Residual the scout's read missed
Line 177 is a free win.
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 (the fleet default). Line 177 pays the fork on every Bash tool call regardless of whether telemetry is on.block-hook-bypass.sh:159andblock-no-verify.sh:133have the same defect.The other two are shared, not this file's to fix:
hook::buffer_stdin_to <var>inlib/hook-utils.sh(synced to 17 copies viascripts/sync-hook-utils.sh). Under the dispatcher the payload is already inRUN_GUARDS_INPUT;INPUT=$(hook::buffer_stdin)copies it back out through a fork and a pipe. 1 fork per guard, 8 of the 36 process creations per Bash tool call. Largest remaining win in the plugin, and it deserves its own issue.hook-utils.sh:2717, the per-character parse loop fed by a process substitution.Also unaddressed by any of the three commits: the batch spends 2 jq, not the 1 this issue's criterion allows. The second is
hook::json_complete's validity probe (hook-utils.sh:1386, called frombuffer_stdinat 1600).Recommendation
Close as fixed, with the residual re-filed. The overheads this issue actually names are gone and the guard contributes zero external process spawns on its common path. The one in-file residual (line 177) is a single-line change shared with #3513 and #3518; the rest is shared-library work. Suggest a successor issue covering the lazy-SUBJECT hoist in all three guards plus
hook::buffer_stdin_to, rather than keeping this one open. Note for the record that the closing commit is273c20fe(#3820), not #3788.Generated by Claude Code
perf(guardrails): drop the forks that never exec in block-noncanonica…
perf(guardrails): drop the forks that never exec in block-noncanonica…