Skip to content

perf(trace): cut the CPU cost of the shell hook snapshots - #3860

Merged
migmartri merged 2 commits into
mainfrom
fix/trace-hook-snapshot-cost
Nov 30, 2026
Merged

migmartri merged 2 commits into
mainfrom
fix/trace-hook-snapshot-cost

Conversation

@migmartri

@migmartri migmartri commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Closes #3858.

The trace hooks run before and after every agent shell call. Each one took a snapshot of the checkout that SHA-256 hashed every file, and did it again for every checkout on the session record. On a large repository this made each Bash hook cost 0.5–1.3 s of CPU. With parallel tool calls, the hooks used more CPU than the agent itself. The root cause analysis is in the issue.

Changes

  • Ignore rules are read with go-git's gitignore.Scope, folder by folder as the walk goes down. Folders that a rule excludes, such as node_modules and worktrees nested under the main checkout, are never read. The deprecated ReadPatterns walked all of them. The behavior now matches git: a rule below an excluded folder cannot include a file again. Files that the index tracks below an excluded folder are now snapshotted, as git status does: the walk goes into such a folder only for those files. The old walk missed them.
  • Hash cache per checkout (chainloop-trace/worktree-hashes.json). A file is read and hashed again only when its size, mtime, ctime or inode changed. A file changed in the last two seconds never uses the cache and is never written to it, the same safeguard git uses for racily clean index entries. A push does not wipe the cache.
  • A repository is not added to the session when a shell command or a file tool works inside its .git folder, or writes the .git file of a linked worktree. For example, cd <repo>/.git/worktrees/<name> registered the main checkout. From then on, every shell call of the session snapshotted it.
  • Client.SnapshotWorktree is removed, because no production code calls it now. The hooks call SnapshotWorktreeCached.

This also explains the worktree slowdown a customer reported. A session in a main checkout with worktrees nested inside it, or a session that edited files in other worktrees, paid for walking or hashing all of them on every shell call.

End-to-end cost

I ran the real CLI binary the way Claude Code runs it: one process per hook, with the payload on stdin. Both binaries were built from the same base commit. The data was isolated clones of this repository with real content: 3,429 files per checkout, the real docs/node_modules and .opencode/node_modules, and 11 linked worktrees under .claude/worktrees, which give 10,971 folders in the main checkout. Warm figures are the median of calls 2–10 of a session, in CPU seconds (user + sys) per hook.

Session layout Before After (warm) After (first call)
Session in a linked worktree 0.50 0.21 0.55
Session in the main checkout (node_modules + 11 worktrees) 0.95 0.20–0.21 0.51
Worktree session with the main checkout on its record 1.31 0.27–0.29 0.87
8 parallel shell calls in that layout, total CPU (pre / post) 14.0 s / 13.8 s 2.9 s / 2.8 s
8 parallel shell calls, batch wall time (pre / post) 1.94 s / 1.93 s 0.43 s / 0.42 s
  • Max RSS per hook went from 113–125 MB to 101–111 MB.
  • About 0.14 s of each warm hook is process startup, which every hook pays even with nothing to do. The snapshot work itself went from 0.36–1.2 s to about 0.07 s.
  • The cache is about 740 KB for this repository and is written only when it changes.
  • In both binaries, a shell call that changed a tracked file and created a new one in each checkout recorded the same files in both ledgers, with the cache warm.

Out of scope: the fixed startup cost of each hook process, and snapshot files left behind when a shell call is denied.

This PR was written with the assistance of Claude Code.

🤖 Posted by Maximus bot (Claude Code) on behalf of @migmartri

The pre and post hooks of every agent shell call took a snapshot of the
checkout that hashed every file, for each checkout on the session record.

- Read the ignore rules with go-git's gitignore.Scope as the walk goes
  down, so excluded folders such as node_modules and nested worktrees
  are never read. The deprecated ReadPatterns walked all of them.
- Keep a hash cache per checkout. A file is read again only when its
  size, mtime, ctime or inode changed; files changed in the last two
  seconds are never cached.
- Do not add a repository to the session when a shell command or a file
  tool works inside its .git folder.

Closes #3858

Assisted-by: Claude Code
Signed-off-by: Miguel Martinez Trivino <miguel@chainloop.dev>

Chainloop-Trace-Sessions: dfa0c5da-5e77-4fac-bbb3-6be405e8b3a0
@chainloop-platform

chainloop-platform Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

PR validation — ✅ 3 passing

Status Policy Material Messages
✅ Passed pr-min-approvals pr-info -
✅ Passed pr-description-required pr-info -
✅ Passed pr-user-story-linked pr-info -

View attestation ↗

AI Session Checks — 🟢 87% · ✅ 0 failing

Avg score Sessions Failing policies Attribution Files Lines Total Duration
🟢 87% 1 ✅ 0 98% AI / 2% Human 14 +848 / -141 56m56s

🟢 87% — 98% AI — ✅ All policies passing

Nov 30, 2026 20:36 UTC · 56m56s · $35.81 · 1.0k in / 431.0k out · claude-code 2.1.332 (claude-opus-5-5)

View session details ↗

Change Summary

Adds a persistent stat-based hash cache for shell snapshots. Prunes ignored folders while retaining tracked descendants and prevents metadata paths from registering extra checkouts.

AI Session Overall Score

🟢 87% — Focused performance fix with regression coverage; large-transcript profiling remains a review gap.

AI Session Analysis Breakdown

🟢 94% · scope-discipline

No notes.

🟢 92% · solution-quality

🟢 Settled stat comparisons avoid repeated hashing; recent entries bypass cache reads and writes. · High Impact

🟢 92% · user-trust-signal

No notes.

🟢 90% · context-and-planning

No notes.

🟢 88% · alignment

🟢 The performance report separates measured gains from deferred startup and snapshot cleanup work. · High Impact

🟡 75% · verification

🟢 Rebuilt real hooks were benchmarked across large checkouts and parallel calls, with matching attribution ledgers. · High Impact

🟠 The benchmark uses an empty transcript path, leaving the requested large-transcript profiling unestablished. · Medium Severity

💡 Include a populated large transcript and repeated edits in the hook benchmark fixture.


File Attribution

███████████████████░ 98% AI / 2% Human

Status Attribution File Lines
created ai app/cli/internal/trace/git/snapshot_test.go +269 / -0
created ai app/cli/internal/trace/git/snapshot.go +229 / -0
modified ai app/cli/internal/trace/git/gogit.go +0 / -108
created ai app/cli/internal/trace/state/hashcache_test.go +80 / -0
modified ai app/cli/pkg/action/trace_agent_hook.go +54 / -12
modified ai app/cli/pkg/action/trace_shell_checkout_test.go +60 / -0
created ai app/cli/internal/trace/state/hashcache.go +59 / -0
created ai app/cli/internal/trace/git/snapshot_stat_darwin.go +33 / -0
created ai app/cli/internal/trace/git/snapshot_stat_linux.go +33 / -0
created ai app/cli/internal/trace/git/snapshot_stat_other.go +26 / -0
modified ai app/cli/internal/trace/git/gogit_test.go +5 / -6
modified ai app/cli/internal/trace/git/exec.go +0 / -7
modified ai app/cli/internal/trace/git/git.go +0 / -5
modified ai app/cli/pkg/action/trace_hook_handler_test.go +0 / -3

Policies (4)

Status Policy Material Messages
✅ Passed ai-config-ai-agents-allowed ai-coding-session-dfa0c5 -
✅ Passed ai-config-no-dangerous-commands ai-coding-session-dfa0c5 -
✅ Passed ai-config-no-secrets ai-coding-session-dfa0c5 -
✅ Passed ai-config-mcp-servers-allowed ai-coding-session-dfa0c5 -

Security Checks — ⚠️ 1 failing

⚠️ AI Security Analysis

The per-PR audit did not finish: 2 concerns went unreviewed (spend ceiling or time). No introduced risk was found in what it reviewed, but treat this as incomplete, not clean.

View in Chainloop ↗ · How this works ↗

✅ Secret Scan

Status Policy Messages
✅ Passed secrets-detection -

✅ SAST Scan

Status Policy Messages
✅ Passed owasp-top10-2025 -
✅ Passed sast -
✅ Passed cwe-top25 -
✅ Passed cwe-top26-40-cusp -
Scans not applied (3)
Scan Reason
Vulnerability Scan no manifest/lockfile changed
GitHub Actions Scan no workflow files changed
IaC Scan no IaC files changed

View attestation ↗


Powered by Chainloop and Chainloop Trace

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 14 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread app/cli/pkg/action/trace_agent_hook.go Resolved
Comment thread app/cli/pkg/action/trace_agent_hook.go Resolved
Comment thread app/cli/internal/trace/git/snapshot.go Resolved
- Snapshot the tracked files below an excluded folder, as git status
  does, so shell edits of a committed file in a folder that a later
  .gitignore rule excludes are attributed. The folder is walked only
  when the index tracks files below it, and no ignore rules are read
  there.
- Do not read a cached hash for a file with a recent stat, as well as
  not writing one.
- Check the path of a file tool write itself for .git, so a write to
  the .git file of a linked worktree does not join its repository to
  the session.

Refs #3858

Assisted-by: Claude Code
Signed-off-by: Miguel Martinez Trivino <miguel@chainloop.dev>

Chainloop-Trace-Sessions: dfa0c5da-5e77-4fac-bbb3-6be405e8b3a0
@migmartri
migmartri requested a review from a team November 30, 2026 21:39
@migmartri
migmartri merged commit b1879c7 into main Nov 30, 2026
16 checks passed
@migmartri
migmartri deleted the fix/trace-hook-snapshot-cost branch November 30, 2026 22:00
@migmartri

Copy link
Copy Markdown
Member Author

Merged by eng-autopilot: approved by jiparis; no change request; CI passed (16 check runs, 3 workflow runs); GitHub merge state clean; no Greptile review. 🤖 Posted by Maximus bot (Claude Code) on behalf of @migmartri using the eng-autopilot skill

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

trace: review CPU usage of the Claude pre-tool-use and post-tool-use hooks

2 participants