Skip to content

perf(guardrails): block-noncanonical-commit.sh averages 78.0s and timed out 91x - reduce process spawns #3514

Closed

Description

@kyle-sexton

Summary

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/**/*.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 Aug 31, 2026

    @kyle-sexton
    MemberAuthor

    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:

    Issue Plugin Hook file(s)
    #3509 source-control hooks/pr-body-linkage-gate.sh (+ pr-linkage-mcp-gate.sh on the ^mcp__github__(create|update)_pull_request$ matcher; shared pr-linkage-validator.sh)
    #3510 source-control hooks/worktree-add-containment-gate.sh (PostToolUse sibling worktree-add-claim-gate.sh)
    #3512 claude-ops hooks/hook-failure-audit.sh
    #3515 autonomy hooks/lane-stop-gate.sh
    #3520 context-guard hooks/zone-crossing-inject.sh

    Matcher corrections:

    Two comparative claims withdrawn:

    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.

  4. kyle-sexton commented on Sep 6, 2026

    @kyle-sexton
    MemberAuthor

    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.

    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:

    commit what it did to this file measured effect
    a5f5e799 (#3781) source "$(dirname …)" replaced by ${BASH_SOURCE[0]%/*} at lines 93-96 removed 1 dirname exec
    5101f5a2 (#3788) deferred the 41 KB lib/powershell/ps-command.sh source into the if [[ "$TOOL_NAME" == "PowerShell" ]] branch (now lines 962-981) zero change to exec or fork counts. Batch counts are byte-identical before and after: 8 execve, 54 process creations. Its win is a parse, not a spawn.
    273c20fe (#3820) dropped the leftover git probes removed 2 git execs and 5 process creations from this guard on a benign Bash call

    Batch-level history on git status --short (whole 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

    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:

    line site ownership
    block-noncanonical-commit.sh:142 INPUT=$(hook::buffer_stdin) shared pattern, all eight guards
    block-noncanonical-commit.sh:177 SUBJECT=$(hook::extract_bash_subject …), file scope, unconditional in-file
    hook-utils.sh:2717 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 inside emit_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.


    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