Repository navigation
Hook: a resident helper on macOS and Linux dev mode, about 65 ms a call instead of 150-180 - #1235
Open
LoopGlitch26 wants to merge 21 commits into
Open
LoopGlitch26 wants to merge 21 commits into
LoopGlitch26 wants to merge 21 commits into
Conversation
…CEKIT_HOOK_HELPER=1 The client (python -S -E, _socket only) hands the call's stdin, argument, cwd, environment and umask to one helper per runtime dir, which forks a child of its warmed process to run the hook's own entry and sends back status, stdout and stderr. No helper, a stale one or a switch off runs today's hook itself. workspace builds git's environment per call instead of at import, so a forked call's environment is its own. Signed-off-by: LoopGlitch26 <53336715+LoopGlitch26@users.noreply.github.com>
The Claude Code hook `tracekit init --dev --v2` writes is now a thin client (python -S -E, _socket only) of a resident helper that forks per call and runs the hook's own entry. The client says "go" only after the helper has accepted a call, so a call runs once: with the helper or, on any failure before that (no helper, a stale one, a timeout, a runtime dir that isn't ours), as today's hook, with the reason written to hook-helper.fallback. The helper's output is streamed, so a held call's waiting line reaches the person while it waits. A stale helper (stamp of the package's folders, or a loaded file changed) is told so, ends and is replaced; a client that goes away ends its call. It ends after 10 minutes idle, `tracekit down` stops it, `tracekit doctor` reports it (D-HOOK-HELPER). TRACEKIT_HOOK_HELPER=0 turns it off. Windows, system mode, the plugin and the other agents' hooks are unchanged. Signed-off-by: LoopGlitch26 <53336715+LoopGlitch26@users.noreply.github.com>
The thin client checks the process at the other end of the socket before it sends a byte: the same user, and the pid in the helper's lock file while that lock is held (peer pid and uid from the kernel, LOCAL_PEERPID and LOCAL_PEERCRED on macOS, SO_PEERCRED on Linux). A program that took the socket's path is neither: the full hook runs, with a note. The helper binds its socket again when it is taken; `tracekit down` and `tracekit doctor` name a listener that isn't the helper and `down` removes its socket, and never signals a pid it can't tie to the lock. limits.md no longer says the helper adds no authority: it says what a same-user program can do in dev mode, what detects it (reconcile.hook_missing from the transcript tailer, tested) and that system mode closes it. Also: a stale notice from a child signals the helper only while it holds its lock, not whatever its parent is now; a working directory that is gone, in the client or the child, is a fallback before "go"; children close the lock fd; a client of another protocol version gets "S"; the lock file opens with O_NOFOLLOW; the switch off and every fallback before the payload is read exec the full hook, so the payload is read only once the helper has accepted the call; the helper ends on SIGTERM through a flag, not an exception that a signal landing in an accept could lose. Signed-off-by: LoopGlitch26 <53336715+LoopGlitch26@users.noreply.github.com>
… helper did not stop macOS reports a socket's peer as the last process to use it, so a client that checked a few ms after connecting saw the helper's forked child and refused the real helper. The child now waits in select() and reads only after the client has sent, which it does after checking who listens (the probe's 20 of 20 refusals at 5, 20 and 100 ms are 0). `tracekit down` raises Hung when the helper still holds its lock after SIGTERM, says so and exits 1, instead of printing "stopped". Doctor warns when the lock is held and nothing listens. The child that has said "A" waits for "go" for REQUEST_S, not forever. limits.md names issue #1233 for the check of the listener's program, not only its lock. Signed-off-by: LoopGlitch26 <53336715+LoopGlitch26@users.noreply.github.com>
Signed-off-by: LoopGlitch26 <53336715+LoopGlitch26@users.noreply.github.com>
# Conflicts: # docs/limits.md
…s has no fcntl The Windows quickstart and example jobs failed at `tracekit down` (ModuleNotFoundError: fcntl): down imported the helper before asking whether this platform has one, and doctor's D-HOOK-HELPER did the same. Both check install.HELPER_PLATFORM first; the helper's test module imports it only there, so its Command tests load on Windows.
…s its socket; Linux's reset is no answer too A loaded runner made the call after the helper had taken its socket back (within a second), so the call went through the helper and left no fallback note. The helper is stopped until the call is made, and a fake is ready once it answers on the socket, not once a socket file exists. Linux resets a peer that closes with its request unread, where macOS closes it: neither is an answer.
…k, nothing after it reruns, reads in linear time #1235's review: start_helper() raising (a directory at hook-helper.started), peer() raising ENOTCONN on macOS or stamp() racing a checkout escaped attempt(), so the client's traceback failed SessionStart and blocked every PreToolUse. Any exception before "go" is now a fallback with its reason in hook-helper.fallback; after "go" the client only relays, whatever happens. The payload is read before connecting, so the child's 2 s wait for "go" covers sending it, not the harness writing it (a late "go" ran the call through the full hook, or not at all), and the fallback execs the full hook on a pipe a child fills with it. Reads build a growing bytearray instead of bytes += (a 24 MB Write: 6.0 s through the helper, now about the full hook's 0.5-0.6 s), and a length the peer sends allocates nothing until its bytes come.
…a pid written in the lock file #1235's review: while the helper ran, a program of this user wrote its own pid into hook-helper.lock and took the socket's path. The client took it for the helper (10 of 10 held git push calls came back allowed), doctor named nothing, and tracekit down sent SIGTERM to it. The helper now holds a POSIX record lock (fcntl.lockf) and never opens the file again (closing any descriptor of it would drop the lock; a forked child holds none of it). The client, doctor and stop() ask the kernel who holds it (F_GETLK, struct flock built per platform: macOS's {start, len, pid, type, whence}, Linux's {type, whence, start, len, pid} padded to its C size), so the forged file is refused, named and never signalled. docs/limits.md says what a program of the user can still do: take the lock when no helper runs, after it kills the helper or after it replaces the lock file (#1233).
… helper gone before go #1235's review: two mutations survived. Removing serve()'s ours(conn) drop passed (only ours() itself was tested): a helper to which every peer is another user's must answer nothing, not the "A" a forked child gives. And a client that could not send "go" running nothing (status 1) passed: a helper that said "A" and went away must leave the call, with all of a 4 MB payload, to the full hook. (The client rerunning a call after "go" is killed by the previous commit's test_a_call_the_helper_has_is_never_run_again_by_the_client.)
…t it doesn't take #1235's review: the child replaces os.environ but glibc reads TZ only at tzset(), so on Linux the signer-down line ("isn't answering (since HH:MM)", time.strftime) showed the zone of the session that started the helper (14:36 for a call in JST-9 at 23:36). A held call's "expires" came out right only because datetime.strptime's first use in the child calls tzset() itself. The test runs both on macOS (whose libc rereads TZ) and in the sealed Linux container, where it fails without the fix. A lean: mark says the call's locale and rlimits stay the helper's.
…nd lean marks #1235's review: a runtime dir too long for the signer's socket gives way to a short dir of its own (autospawn._short; on macOS the default one to /tmp/tk-<uid>), where the helper, doctor and tracekit down work, but the client kept the long one, so every call ran the full hook. The client now finds the same dir, and a test pins it to autospawn's for a short dir, one where only the helper's socket is too long (87-91 bytes: the full hook runs, noted) and a long one. docs/limits.md's row: the measured times (about 65 ms from 150-175), what any error before the helper has a call does and that a call it has is never run again, the socket-path band, the TZ the child takes and the locale, rlimits and dependency upgrades it doesn't, and killing the helper as the same-user limit of #1233. lean: marks on stamp() and the child's locale and rlimits.
listen() bound the socket at its path and then called listen(): a client that found the path
in between was refused, and that call ran the full hook ("no helper answered"). In the sealed
Linux run at the previous commit, under load, two tests that connect as soon as the path
appears failed on it. The socket is now bound under a name of its own in the same dir (no
longer than the path's), made to listen, and moved over whatever is at the path (os.replace:
also no moment without a socket when the helper takes its path back).
#1235's re-review: a helper whose hook-helper.lock was removed or replaced kept its lock on a file no client could find. Clients refused it, each refusal started another helper, and the two traded the socket about once a second without idling out (the probe: 15 of 30 calls through the full hook, both helpers alive at the end). On each turn of its loop, calls coming or not, the helper now compares the file at the lock's path (lstat, no descriptor opened, so its own lock stays) with the one it locked, and ends when it is gone or another; after: 1 of 30 calls (the one that starts the next helper) through the full hook, one helper left. docs/limits.md says so.
… and the helper is let go first #1235's re-review: the fallback forks a child to write the payload into the full hook's stdin. Where fork fails (a process limit) its OSError escaped main() and the client exited 1, blocking a PreToolUse and leaving a PostToolUse unrecorded; the payload now goes in an unlinked 0600 file in the runtime dir, dup'd onto fd 0. And the writer child inherited the connection to the helper, so a helper's child that took the call waited on it while the full hook was slow to read: main() now makes the socket and closes it before any fallback (4.5 s held open before, under 2 s now).
…he next helper removes a socket left mid-move #1235's re-review, two nits. A client gone between its connect and the helper's accept (ConnectionAbortedError, as BSD reports it) ended the helper; it is now skipped. Any other accept error still ends the helper, logged: on EMFILE the connection stays queued, and going on would spin the loop. And a helper killed between binding its socket under .hh<pid> and moving it to its path left that socket behind; the next helper, once it holds the lock (only the holder binds one), removes any.
…s is a new one (mkstemp), never one already at the name
…the dev signer first CI on 281ed09, py3.9 shard 2: test_a_local_time_the_hook_prints_is_in_the_calls_time_zone found no session state after its SessionStart (FileNotFoundError), and ran 23 s. The test never checked the SessionStart's status, so it now does, with its stderr. A SessionStart hook waits at most 20 s (claude_code.deadline: 2 x autospawn.TIMEOUT_S) for a dev signer it starts itself; on a loaded runner the cold start can take longer, and the hook fails closed: "signer unreachable (the dev signer did not start ...); event not recorded", exit 1, no state. That is the class tests/factories.start_dev_signer() is for ("Tests of a hook's other behaviour start the signer first"), which waits up to autospawn's START_WAIT_S. With the SessionStart deadline cut to 0.1 s to stand in for that runner, 6 tests of this file failed besides this one, and the recorded-payloads one in one run of two; with start_dev_signer() first in those 8, all 54 pass twice. Nothing of 3.9 is involved: the test passes on Python 3.9.25 locally, and no API or syntax newer than 3.9 is in the PR's files.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Every agent tool call runs Tracekit's hook twice, PreToolUse and PostToolUse, and each was a fresh Python process: about 60-80 ms of start and imports for a decision that takes under 1 ms. On macOS and Linux in dev mode, the hook
tracekit init --dev --v2writes is now a thin client of a resident helper. The helper runs the same hook code in a child forked per call, with the call's own environment, working directory and time zone. It decides nothing itself: each call still goes to the signer.Measured
Pre and Post together, median of 20 interleaved runs, the real installed hook command, scratch dev signer, this Mac (load average about 11):
TRACEKIT_HOOK_HELPER=0)lsA 24 MB Write takes 0.30 s through the helper, against 0.27 s for the full hook.
How it stays safe
tracekit doctornames such a listener, andtracekit downsignals only the kernel's lock holder.hook-helper.fallback. That includes a missing, stale or refused helper, another version, a deleted working directory, and the client's own errors.reconcile.hook_missinggap when the run closes, from the transcript the run's tailer reads (tested).Evidence
D-HOOK-HELPER).