Skip to content

Prompt hook's graft ask child outlives its execFileSync timeout during an inline graph rebuild; SIGKILL leaves .sync.lock with a dead pid #635

Open

Description

@djbclark

Summary

On graft / Trail-Code 0.23.0 (macOS), the Claude Code UserPromptSubmit hook runs graft ask through execFileSync with a derived child timeout. When the working tree has drifted enough that ensureFreshGraph rebuilds inline, that rebuild is largely synchronous CPU work while holding graft/.cache/.sync.lock. The child continues running (and the hook blocks) for far longer than the intended ~4 s child budget. If the host then SIGKILLs the hook (Claude Code’s own hook timeout), the lock file is left behind naming a dead pid; later queries wait briefly and then answer from a stale graph.

This compounds the units issue in #283: a settings value of "timeout": 60 (seconds in Claude Code) is read as 60 ms of budget before overhead, then floored to 4000 ms for the child.

Environment

  • Package: @nanonets/graft / Trail-Code 0.23.0
  • OS: macOS 27.0.1 (Darwin arm64)
  • Node: v26.8.1
  • Hook entry: ~/.claude/helpers/graft-hooks.cjs prompt
  • Isolated CLAUDE_CONFIG_DIR with "timeout": 60 on the graft UserPromptSubmit command hook

Observed (minimal repro)

  1. Cold graft build of ~3500 Python files: ~28 s, peak RSS ~1.1 GiB.
  2. promptAskTimeout(dir) with installed timeout 60 → 4000.
  3. Wipe extract cache + modify 500 files; run the prompt hook as Claude Code does.
    • Hook wall: ~43 s (expected child budget 4 s).
    • graft ask child remained in runnable state and held .sync.lock until ~39 s.
    • Hook produced no additionalContext (child timed out / null JSON).
  4. Same setup under gtimeout -s KILL 10:
    • .sync.lock survived with a dead pid.
    • Next graft ask printed: a graph rebuild is already in flight — answering from the current graph (~3.8 s), lock still present.
  5. Control: GRAFT_NO_REFRESH=1 on the same hook → ~2.3 s with a normal retrieval pack.
Repro script (synthetic 3500-file repo, isolated CLAUDE_CONFIG_DIR; does not touch ~/.claude)
# 0) Preconditions
node -e "console.log(require(require('os').homedir()+'/.local/lib/node_modules/@nanonets/graft/package.json').version)"
# expect 0.23.0
uptime   # wait until 1-min load <= 20
BASE=$(mktemp -d /tmp/graft-repro-XXXX)
R=$BASE/repo
CFG=$BASE/claude-config
mkdir -p "$R" "$CFG" "$BASE/trail-home"
git -C "$R" init -q

# 1) Synthetic tree (~3500 Python files; adjust N if build time not 20–60s)
N=3500
i=0
while [ "$i" -lt "$N" ]; do
  d=$((i / 100)); mkdir -p "$R/src/mod_$d"
  cat > "$R/src/mod_$d/file_$i.py" <<EOF
class ParseError(Exception): pass
def tokenize(s): return s.split()
def parse_expr(tokens, pos=0):
    if pos >= len(tokens): raise ParseError("eof")
    return tokens[pos], pos+1
def handle_errors(src):
    try: return parse_expr(tokenize(src))[0]
    except ParseError as e: return {"error": str(e), "mod": $i}
EOF
  i=$((i + 1))
done
git -C "$R" add -A
git -C "$R" -c user.email=repro@local -c user.name=repro commit -q -m 'repro tree'

# 2) Cold build + RSS
cd "$R"
/usr/bin/time -l graft build .
# record real time + "maximum resident set size"

# 3) Confirm timeout math (isolated settings; does not touch ~/.claude)
cat > "$CFG/settings.json" <<'EOF'
{
  "hooks": {
    "UserPromptSubmit": [{
      "hooks": [{
        "type": "command",
        "command": "node ~/.claude/helpers/graft-hooks.cjs prompt",
        "timeout": 60
      }]
    }]
  }
}
EOF
CLAUDE_CONFIG_DIR=$CFG node --input-type=module -e "
import { promptAskTimeout } from 'file://'+process.env.HOME+'/.local/lib/node_modules/@nanonets/graft/dist/claude/hooks.js';
console.log('promptAskTimeoutMs', promptAskTimeout(process.argv[1]));
" "$R"
# expect 4000

# 4) Force long inline rebuild (drift + wipe extract cache)
rm -f "$R"/graft/.cache/extract.*.json
i=0; while [ "$i" -lt 500 ]; do
  f="$R/src/mod_$((i/100))/file_$i.py"
  [ -f "$f" ] && printf '\n# drift %s\n' "$i" >> "$f"
  i=$((i+1))
done

# 5) Run hook exactly as Claude Code (isolated config)
export CLAUDE_CONFIG_DIR=$CFG CLAUDE_PROJECT_DIR=$R TRAIL_HOME=$BASE/trail-home
# In another terminal while this runs: ps -ax -o pid,ppid,etime,state,command | grep 'cli.js ask'
printf '%s' '{"prompt":"how does the parser handle errors","session_id":"repro","hook_event_name":"UserPromptSubmit"}' \
  | /usr/bin/time -p node ~/.claude/helpers/graft-hooks.cjs prompt
# expect wall >> 4s; often empty stdout

# 6) SIGKILL simulation + stale lock
rm -f "$R"/graft/.cache/extract.*.json
i=0; while [ "$i" -lt 500 ]; do
  f="$R/src/mod_$((i/100))/file_$i.py"
  [ -f "$f" ] && printf '\n# drift2 %s\n' "$i" >> "$f"
  i=$((i+1))
done
printf '%s' '{"prompt":"how does the parser handle errors","session_id":"repro-kill","hook_event_name":"UserPromptSubmit"}' \
  | gtimeout -s KILL 10 /usr/bin/time -p node ~/.claude/helpers/graft-hooks.cjs prompt || true
cat "$R/graft/.cache/.sync.lock"
# expect JSON with dead pid; kill -0 <pid> fails
/usr/bin/time -p graft ask "how does the parser handle errors" "$R" --json -n 1
# stderr note: rebuild already in flight; answers from current graph

# 7) Control
rm -f "$R/graft/.cache/.sync.lock"   # optional cleanup before control
export GRAFT_NO_REFRESH=1
printf '%s' '{"prompt":"how does the parser handle errors","session_id":"repro-control","hook_event_name":"UserPromptSubmit"}' \
  | /usr/bin/time -p node ~/.claude/helpers/graft-hooks.cjs prompt
# expect ~1–3s and non-empty hookSpecificOutput

# 8) Cleanup
rm -rf "$BASE"

Likely mechanism

  • dist/claude/hooks.js: graftJson → execFileSync(..., { timeout: promptAskTimeout(dir) }).
  • promptAskTimeout subtracts 2000 from the installed number and floors at 4000, without converting Claude Code seconds → ms (settings-merge: hook timeouts written in ms (Claude Code reads seconds) and footerLinksRegexes written to project settings where it is ignored #283).
  • dist/graph/refresh.js: ensureFreshGraph takes .sync.lock, installs releaseOnSignal, then await buildGraph(...). Synchronous parse/build work can delay handling of SIGTERM until the rebuild finishes, so the child (and parent hook) overrun the timeout. releaseOnSignal never runs if the process is SIGKILL’d.
  • dist/util/state.js: acquireLockIn treats an existing lock as free only after LOCK_STALE_MS (300000 ms); it does not check whether pid is alive.

Expected

  • Child timeout should track Claude Code’s seconds budget (or settings should store ms consistently) so a 60 s hook allows a proportionate ask/rebuild window — or rebuild should not run synchronously under the prompt hook’s short child budget.
  • SIGTERM during rebuild should abort promptly and always release .sync.lock.
  • A lock whose pid is dead should be reclaimable immediately (or within seconds), not up to five minutes of “rebuild in flight” stale answers.

Related

Workaround

GRAFT_NO_REFRESH=1 in front of the prompt hook command (it then answers from the current graph; the Stop hook's background sync still refreshes it). graft init rewrites the hook command, so this has to be re-applied after every init.

Activity

  1. hr1juldey commented on Nov 18, 2026

    @hr1juldey

    Picked up the stale-lock half of this. On current main the lock's pid-liveness check only ran after the 5-minute age floor, so the SIGKILLed hook's fresh dead-pid lock kept every query waiting and answering from the stale graph for up to five minutes — the repro's step 4. Draft: #861 makes a dead owner lose the lock immediately while keeping the age rules for live owners (and lockHeldByOther moves with it, so the next caller rebuilds instead of waiting). The child-budget half (timeout units, compounding #283) is a separate surface and deliberately untouched.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions