Skip to content

perf(guardrails): block-hook-bypass.sh (performance) averages 75.1s and timed out 105x - reduce process spawns #3513

Closed

Description

@kyle-sexton

Summary

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/**/*.jsonl hook_cancelled attachments with timedOut: true, across 236 sessions, 2026-08-23 to 2026-08-31.

Activity

  1. added
    agent-ready
    on Aug 31, 2026
  2. kyle-sexton commented on Aug 31, 2026

    @kyle-sexton
    MemberAuthor

    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:

    source-control  PreToolUse Bash                    timeout=15
    guardrails      PreToolUse Bash|PowerShell         timeout=60
    guardrails      PreToolUse Write|Edit|NotebookEdit timeout=60
    guardrails      PostToolUse Write|Edit             timeout=30
    context-guard   PreToolUse / PostToolBatch         timeout=60
    disk-hygiene    PreToolUse Bash|PowerShell         timeout=60 ; Stop timeout=20
    claude-ops      Stop timeout=10 ; StopFailure timeout=5
    autonomy        Stop timeout=15
    

    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.

  3. kyle-sexton commented on Sep 6, 2026

    @kyle-sexton
    MemberAuthor

    Verification: PARTLY FIXED

    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.
    source "$(dirname "${BASH_SOURCE[0]}")/hook-utils.sh" 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):

    tree execve process creations batch p50 (n=25)
    a5f5e799^ (pre-#3781) 16 (3 bash, 7 dirname, 3 git, 2 jq, 1 sed) 65 97 ms
    a5f5e799 (#3781) 8 (3 bash, 3 git, 2 jq) 54 78 ms
    5101f5a2 (#3788) 8 54 67 ms
    273c20fe (#3820) 3 (1 bash, 2 jq) 36 49 ms

    Measured counts for this guard

    On git status --short and on git commit -m "feat: thing", inside the dispatcher:

    • execve contributed: 0. The batch's 2 jq are the dispatcher's, paid once for all eight guards.
    • Process creations contributed: 7. This is the largest of any guard in the plugin.

    Attributed by a BASHPID-tracing DEBUG trap on the dispatcher's isolation subshell:

    line site
    block-hook-bypass.sh:112 INPUT=$(hook::buffer_stdin)
    block-hook-bypass.sh:159 SUBJECT=$(hook::extract_bash_subject "$TOOL_NAME" "$COMMAND"), file scope, unconditional
    block-hook-bypass.sh:478 EXECUTABLE=$(strip_literals "$COMMAND")
    block-hook-bypass.sh:474 done < <(printf '%s\n' "$cmd") in strip_literals
    block-hook-bypass.sh:1305 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:

    1. Line 159, unconditional SUBJECT. block-windows-drive-tmp.sh:186 already carries the fixed shape: SUBJECT is resolved lazily inside emit_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.
    2. 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.
    3. 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.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-ready

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions