Skip to content

Hardening (retracted as a bug): bundled hook calls rtk rewrite without a deadline from PreToolUse — see correction, rtk was NOT the cause of our timeouts #3589

Closed

Description

@MoJuiceX

Summary

The Claude Code PreToolUse hook invokes rtk rewrite "$CMD" with no deadline. Because the hook blocks the tool call, a slow rewrite doesn't just cost latency — if it exceeds Claude Code's hook timeout, Claude Code cancels the tool call entirely, which is strictly worse than skipping the rewrite and passing the command through.

The failure is silent from the model's side: the command simply doesn't run.

Environment

  • rtk 0.34.3 (Homebrew), macOS
  • rtk-hook-version: 3, installed via rtk init -g --auto-patch
  • Claude Code, hook registered as PreToolUse / matcher Bash

The structural problem

In the installed hook:

# Delegate all rewrite + permission logic to the Rust binary.
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null)
EXIT_CODE=$?

Nothing bounds that call. The hook's contract already has a well-defined degradation path — exit 1 means "no RTK equivalent → pass through unchanged" — so a rewrite that is too slow has an obvious correct behaviour available (pass through), but no way to reach it.

Risk scales with parallelism: an agent fanning out many concurrent Bash calls multiplies both the chance of a slow rewrite and the cost of losing a tool call.

A secondary inefficiency in the same file: the version guard shells out to rtk --version on every Bash tool call, though the answer only changes when the binary is upgraded.

Proposed fix

Cap the rewrite and degrade to pass-through on timeout (timeout exits 124, which falls through to the existing catch-all), and cache the version probe. Patch against the 0.34.3 / hook-version-3 template:

--- a/rtk-rewrite.sh
+++ b/rtk-rewrite.sh
@@ -25,15 +25,24 @@
 
 # Version guard: rtk rewrite was added in 0.23.0.
 # Older binaries: warn once and exit cleanly (no silent failure).
-RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [ -n "$RTK_VERSION" ]; then
-  MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
-  MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
-  # Require >= 0.23.0
-  if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
-    echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
-    exit 0
+#
+# This hook fires on EVERY Bash tool call, so the version probe is cached and
+# re-run at most once a day. The answer only changes when the binary is upgraded.
+RTK_STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/rtk-hook"
+RTK_VERSION_STAMP="$RTK_STATE_DIR/version-ok"
+if [ ! -f "$RTK_VERSION_STAMP" ] || [ -n "$(find "$RTK_VERSION_STAMP" -mtime +1 2>/dev/null)" ]; then
+  RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
+  if [ -n "$RTK_VERSION" ]; then
+    MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
+    MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
+    # Require >= 0.23.0
+    if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
+      echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
+      exit 0
+    fi
   fi
+  mkdir -p "$RTK_STATE_DIR" 2>/dev/null && : > "$RTK_VERSION_STAMP" 2>/dev/null
 fi
 
 INPUT=$(cat)
@@ -44,7 +53,24 @@
 fi
 
 # Delegate all rewrite + permission logic to the Rust binary.
-REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null)
+#
+# Hard deadline: this is a PreToolUse hook, so every millisecond here blocks the
+# tool call. If `rtk rewrite` exceeds Claude Code's hook timeout the whole tool
+# call is cancelled — far worse than skipping the rewrite. Cap it at
+# RTK_HOOK_TIMEOUT seconds (default 2) and degrade to pass-through on timeout.
+# `timeout` exits 124 when it fires, which falls to the catch-all below and
+# passes the command through unchanged.
+RTK_HOOK_TIMEOUT="${RTK_HOOK_TIMEOUT:-2}"
+if command -v timeout &>/dev/null; then
+  RTK_TIMEOUT_CMD=(timeout "$RTK_HOOK_TIMEOUT")
+elif command -v gtimeout &>/dev/null; then
+  RTK_TIMEOUT_CMD=(gtimeout "$RTK_HOOK_TIMEOUT")
+else
+  RTK_TIMEOUT_CMD=()
+fi
+
+REWRITTEN=$("${RTK_TIMEOUT_CMD[@]}" rtk rewrite "$CMD" 2>/dev/null)
 EXIT_CODE=$?

The command -v timeout / gtimeout / empty-array fallback keeps it working on macOS without coreutils, where neither binary may exist.

Why this needs to be fixed upstream rather than locally

A user cannot hold this patch:

  1. Editing the installed hook makes rtk verify fail its integrity check, and rtk then refuses to run at all — so the patched user loses 100% of the savings.
  2. rtk init -g --auto-patch (the documented remedy) regenerates the hook from the bundled template, silently discarding the patch.

So the only stable states available to a user are "unpatched and working" or "patched and disabled". We hit exactly this loop: the hook was patched locally, rtk verify began failing, and re-running rtk init restored integrity while reverting both fixes.

Scope of what we verified

To be precise about evidence: the structural claim above is verifiable by reading the installed hook — there is no deadline on a blocking call. We did not produce a minimal reproduction of a rewrite exceeding the hook timeout; the local patch's own comments cite that as the motivating observation, and we're reporting it as such rather than as something we re-measured.

Happy to open a PR with the patch if that's easier.

Activity

  1. pszymkowiak commented on Aug 16, 2026

    @pszymkowiak
    Collaborator

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟠 Priority high
    🎯 Confidence 78%

    Summary

    PreToolUse hook calls rtk rewrite with no timeout, so a slow rewrite causes Claude Code to cancel the tool call instead of falling back to pass-through; add a timeout-wrapped call and cache the version probe per the provided patch.

    This looks like a simple fix that could be auto-resolved. Repo maintainers can use /wshm fix to attempt it.

    📁 Relevant files
    • rtk-rewrite.sh

    Triaged automatically by wshm · This is an automated analysis, not a human review.

  2. MoJuiceX commented on Aug 16, 2026

    @MoJuiceX
    Author

    Correction from the reporter — rtk is not implicated. Please don't spend triage time on this as a bug.

    Shortly after filing, we found the marker that let us attribute these timeouts properly, and it exonerates rtk completely. Posting the correction rather than quietly editing, because the original framing was wrong.

    What we can now measure

    Claude Code does not write a human-readable timeout string — it's a structured field in the transcript JSONL, which is why our first search found nothing. Match type == "attachment" + attachment.type == "hook_cancelled" + attachment.timedOut == true, dedup on the outer uuid (the same event is written into several files via sidechains/resumed sessions), and read attachment.command to see which hook died.

    Result across 1,818 transcripts, 176 distinct timed-out events:

    count command hookEvent timeoutMs
    94 headroom init hook ensure PreToolUse 15000
    82 …/headroom init hook ensure --profile … PreToolUse 15000
    0 rtk-rewrite.sh — —

    174 PreToolUse + 2 SessionStart, every one timeoutMs: 15000. Both rows are the same third-party plugin hook under two spellings. rtk-rewrite.sh appears zero times.

    Consequently, retracting these claims from the original report

    • "a slow rewrite can cancel the tool call" — not observed. Zero rtk timeouts on this machine, ever.
    • "Claude Code's default hook timeout is 15s" — wrong as stated. 15000 here is set explicitly by that plugin's own hooks.json, not a Claude Code default.
    • Our own rtk latency measurements (~40 ms flat from 100→60,000 chars; 55–99 ms replaying real commands; 24-way parallel ~300 ms; 64-way plus 12 concurrent DB writers peaking 887 ms) read as exonerating rtk, not indicting it. They were crude wall-clock timings on one Apple Silicon machine, n=20–64 — not a benchmark.
    • A hypothesis about history.db size contributing to contention was speculation and there is no longer any phenomenon for it to explain. Withdrawn.
    • We also want to explicitly retract a nearby claim we never published but that shaped our thinking: a large count of rtk grep "parse failures" are internal parser fallbacks, not broken commands — rtk grep -r logs one while still returning correct output. It would have been a false bug report.

    What, if anything, survives

    Only a hardening observation, and only if you think it's worth it: the bundled hook calls rtk rewrite "$CMD" with no deadline from a PreToolUse position, where exceeding the host's hook budget cancels the tool call outright. The 176 events above show that failure mode is real and reachable in practice — just from a different hook, not yours. rtk's exposure to it is structural rather than observed, and the hook already has a correct degradation path (exit 1 → pass through), so a bounded call could reach it.

    That's a robustness nicety, not a defect, and we have no evidence rtk needs it. Happy for this to be closed — we're leaving that to you rather than re-litigating it. Apologies for the noise; the attribution error was ours.

  3. changed the title [-]PreToolUse hook has no deadline on `rtk rewrite`; a slow rewrite can cancel the tool call instead of degrading to pass-through[/-] [+]Hardening (retracted as a bug): bundled hook calls `rtk rewrite` without a deadline from PreToolUse — see correction, rtk was NOT the cause of our timeouts[/+] on Aug 16, 2026
  4. MoJuiceX commented on Aug 16, 2026

    @MoJuiceX
    Author

    Closing this ourselves — the attribution in the original report was wrong and rtk is not implicated (0 of 176 observed hook timeouts were rtk; all were a third-party plugin hook). Retitled so nobody reads the original claim as standing. The hardening observation in the correction above is yours to take or leave; we're not asking for action on it and would rather withdraw cleanly than leave an unevidenced bug report open against the project.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions