Skip to content

NF01: rtk-rewrite.sh hook adds ~56ms overhead on Apple Silicon (vs documented <5ms) #1375

Open

Description

@ArtificialMonks

Summary

On Apple Silicon (M-series), rtk-rewrite.sh hook invocations measure ~56 ms average / ~84 ms p95 per call in production use, versus the documented "<5 ms overhead" target. A 100-invocation benchmark collected during a downstream project's enforcement phase identifies the root cause as a subprocess fork of rtk for command-prefix classification inside the hook.

The latency is imperceptible in interactive use (dwarfed by typical bash wall-time) but violates the documented NF01 budget and adds up across high-frequency sessions (~5,000 hook firings / day → ~4.7 min/day of classification overhead).

Environment

  • rtk version: 0.35.0
  • Platform: Apple Silicon (M-series), macOS 14+
  • Invocation: PreToolUse:Bash hook (Claude Code harness) piping stdin via rtk-rewrite.sh
  • Shell: zsh / bash — fresh subshell per invocation

Measurement

100-invocation benchmark:

avg:  56.14 ms
p50:  54.9  ms
p95:  ~84   ms (estimated)
p99:  ~120  ms

Harness forks a fresh bash per invocation. In-session runtime (no bash re-fork) is ~30–40 ms lower because shell startup amortizes, but the rtk-side cost remains ~30–40 ms per call.

Suspected root cause

rtk-rewrite.sh forks rtk as a subprocess to classify the incoming command prefix. On Apple Silicon, cold-start of the rtk binary accounts for the bulk of the 56 ms — process setup + dylib resolution + arg parse before any classification logic runs.

Proposed upstream mitigations (any one is sufficient)

  1. In-shell prefix parser — ship a small bash/sh function covering the top ~10 prefixes (git, grep, find, ls, cat, head, tail, wc, curl, docker) that short-circuits without forking rtk. Falls through to rtk subprocess for the long tail.
  2. Persistent classifier daemon — optional rtk-daemon binding to a unix socket; rtk-rewrite.sh uses nc -U for classification, falls back to subprocess fork if daemon is absent. Preserves zero-install default.
  3. Split classifier binary — ship rtk-classify as a focused, smaller binary without the full CLI surface.

Why this matters at scale

At ~5,000 hook firings / day, 56 ms/call × 5,000 = ~4.7 minutes/day of latency accrued purely from classification subprocess forks. Perceptible only on tight loops (shell-pipe-heavy scripts that trigger hooks repeatedly), but measurable.

Out of scope for this issue

  • Hook correctness and rewrite accuracy — functioning correctly, no regression.
  • rtk standalone invocation latency (rtk git status, etc.) — not measured here, may share root cause.

Downstream disposition

We've accepted the deviation internally by revising our target from p95 < 25 ms → p95 < 100 ms, and deferred a local prefix-parser optimization pending upstream response — we don't want to ship a divergent rtk-rewrite.sh that would later conflict with the upstream fix.

Happy to contribute a PR on any of the three mitigation paths if a maintainer signals preference.

Activity

  1. added
    effort-medium
    enhancement
    on Apr 18, 2026
  2. pszymkowiak commented on Apr 18, 2026

    @pszymkowiak
    Collaborator

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟡 Priority medium
    🎯 Confidence 76%

    Summary

    rtk-rewrite.sh subprocess fork costs ~56ms on Apple Silicon vs documented <5ms NF01 target; fix requires in-shell prefix parser, daemon, or split binary — contributor offers PR

    📁 Relevant files
    • rtk-rewrite.sh

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

  3. LucasSantana-Dev commented on May 3, 2026

    @LucasSantana-Dev

    Adding production data from a heavy daily user (Apple M-series, Claude Code 2.1.126, rtk 0.34.1):

    Hook overhead measured locally

    • Cold start: 44ms (single invocation)
    • Warm pass-through (true): ~28ms/call
    • Warm rewriteable (ls -la): ~48ms/call

    Consistent with the ~56ms reported here.

    Cumulative ROI

    Total commands:    10,363
    Tokens saved:       9.5M  (57.4%)
    Total exec time:    363m50s (avg 2.1s)
    

    Top earners:

    1. rtk read — 4.0M saved over 1,053 calls (~3.8K/call, 6ms avg)
    2. rtk gh pr diff — 1.6M saved over 22 calls (~73K/call)
    3. rtk lint eslint — 988K saved (3 calls, 100% reduction)

    Why daemon mode would be transformative at this scale
    At 10K+ commands, even a 30ms/call reduction equals 5+ minutes of cumulative interactive latency saved. More importantly, the per-call latency is the only thing that occasionally makes me reach for non-rtk-wrapped one-liners — eliminating it would push my hit-rate higher and unlock another lever of savings.

    A unix-socket daemon (rtkd) with a thin shell shim that does:

    exec socat - UNIX-CONNECT:/tmp/rtk.sock
    

    should plausibly drop the hook to <5ms, hitting the documented NF01 budget without any registry changes.

    Happy to beta-test a daemon-mode branch with real-world traffic if it would help validate the approach.

  4. added
    bug
    help wanted
    on May 27, 2026
  5. Yohjisakamoto commented on Jul 22, 2026

    @Yohjisakamoto

    This measured hook-overhead result reinforces why end-to-end agent outcomes matter more than compressed text alone: DeepSWE found Tura cuts coding-agent rounds by 89% and total token cost by 80%; would you evaluate the methodology? https://turaai.net/docs#benchmark-current-test-set-record

  6. HetCreep commented on Aug 4, 2026

    @HetCreep

    The 20 ms gap in @LucasSantana-Dev's numbers — 28 ms warm pass-through vs 48 ms warm rewriteable — is interesting, because both paths pay the same cold-start. Something in the rewrite path costs about 20 ms on top. I measured the same split on a different platform and traced it to regex compilation.

    Provenance: AI-assisted source audit, human-directed, at v0.44.2 (700bdde). Numbers measured on Windows 11, where the bare process-spawn floor is ~35 ms — so treat the deltas as meaningful and the absolute values as not comparable to Apple Silicon.

    The split

    invocation what it does measured
    rtk --version spawn only 40 ms
    rtk rewrite <no-match> spawn + REGEX_SET 52 ms
    rtk rewrite git status spawn + REGEX_SET + COMPILED 61 ms

    So on this box: ~12 ms for the RegexSet, then a further ~9 ms when a rule actually matches — about 21 ms of regex work per hook-rewritten call, against the documented <10 ms startup budget. The shape matches the 20 ms gap in this thread even though the absolute numbers differ.

    Where the second 9 ms goes

    src/discover/registry.rs builds two structures over the same 178 rules:

    • :51 — REGEX_SET, a RegexSet over all 178 patterns. This is the right structure and classify_command (:162) uses it as a single pass.
    • :54 — COMPILED, a Vec<Regex> that compiles all 178 patterns individually.

    COMPILED exists so that after REGEX_SET reports which rule matched, :167 can call COMPILED[idx].captures() to extract the capture groups. But it is a LazyLock, so the first access compiles all 178 — to use exactly one.

    That is the ~9 ms: it is paid only when a rule matches, which is exactly the pass-through vs rewriteable difference reported above.

    Possible directions (untested — no programmer has reviewed these)

    • Compile the matched rule's Regex on demand and cache it, instead of forcing all 178 up front — e.g. a OnceLock<Regex> per rule, or a small memo keyed by index. Most sessions touch a handful of distinct commands.
    • Or check whether the capture groups are needed at all for the common path; if the rewrite is a prefix substitution for most rules, RegexSet alone may be enough and COMPILED becomes a fallback.

    Neither addresses the cold-start component this issue opened on, which is likely still the larger share on Apple Silicon. This is the part that is in rtk's own control rather than the dynamic linker's.

    I have not profiled on Apple Silicon and cannot say what fraction of the 56 ms this represents there — someone with an M-series box could check by timing rtk rewrite on a matching vs non-matching command.

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

    area:clibugeffort-mediumenhancementhelp wantedplatform:macospriority:medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions