The hook that taxed every prompt, and the race that could log out every agent
Superset is a desktop app for running many AI coding agents at once. Claude Code, Codex, Cursor, and others each get their own terminal and their own copy of the repo, side by side. "Many things at once" is the whole pitch. It is also the backdrop for both bugs in this post, because when a lot of things run at the same time, small costs multiply and shared things get fought over.
I shipped two fixes this week. One was someone else's report: a tiny shell script that was quietly adding seconds to every prompt for every user. The other I found by asking a question nobody had asked yet, and it turned out that about once a week, Superset could log out every agent on your machine at the same time. Then the project's two review bots found real holes in my fix, and the shipped version is better for it. I'll go through all three parts in order. (If you read my earlier Superset fixes, this is the same repo and the same habit of reading the other side before blaming your side.)
| Issue | Fix | Found by | In one line |
|---|---|---|---|
| #8245 | PR #8425 | a user | A status hook started 50 to 70 processes per event and ran on every tool call. Claude waited for it, sometimes past its 30-second limit. |
| #8426 | PR #8427 | me | Parallel commands refreshed the same login token at once. The server read that as theft and revoked everything. |
A quick vocabulary
A few words come up over and over, so here they are once.
A hook is a small program that a tool runs at certain moments. Claude Code has hooks for "the user just submitted a prompt," "a tool just finished," and so on. Superset installs one so it can show, in its sidebar, what each agent is doing. The important detail: Claude runs the hook and waits for it to finish before moving on.
A process launch is what happens every time a shell runs an external program like grep or sed. The operating system has to create a new process, load the program, set it up, and tear it down. It feels free. It is not, especially on a Mac with security software inspecting every launch.
An access token is the short-lived pass that proves you are logged in. When it is about to expire, the client trades a longer-lived refresh token for a new pair. Token rotation means every refresh also replaces the refresh token, so each one can be spent exactly once. A compare-and-set is a database update that only goes through if a field still has the value you expect, which guarantees that out of many simultaneous attempts, exactly one wins.
A lock file is the simplest way for separate programs on one machine to take turns: whoever manages to create the file goes first, and everyone else waits until it disappears.
Part 1: the hook that taxed every prompt
How I picked it
I filtered the open issues to ones nobody was assigned to, and then ranked them by a single question: how much user time does this bug burn? One stood out. A user reported that Superset's notification hook was adding multi-second delays to every prompt, and Claude kept logging this:
UserPromptSubmit hook timed out after 30s — output discarded.
Why this one wins on time: the hook is not an occasional code path. Superset registers it for ten Claude lifecycle events, including PostToolUse, which fires after every single tool call. Claude runs it and waits. So whatever this script costs, every user pays it dozens of times per prompt, on every prompt, in every terminal.
What the bug actually was
The hook is a bash script. It receives a blob of JSON from Claude, pulls a handful of fields out of it, and sends a status update to Superset's local service. The reporter did excellent work. They stubbed out the network entirely and measured that one run of the script still took 10 to 14 seconds on their machine. Their own patched version took about one second. So the cost was not the network. It was the script itself.
Here is the original function that pulled one field out of the JSON:
json_field() {
for KEY in "$@"; do
VALUE=$(echo "$INPUT" \
| grep -oE "\"$KEY\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" \
| head -n 1 | grep -oE '"[^"]*"$' | tr -d '"')
[ -n "$VALUE" ] && { printf '%s' "$VALUE"; return; }
done
}
Count the programs: echo, grep, head, grep, tr, plus the subshell that the $( ... ) creates. That is five or six process launches per key. The script looks up about eleven keys per event, each with fallback names that pay the whole pipeline again on a miss. Add the JSON escaping (one sed per field, five to eight fields), the preview extraction (another grep | head | sed per candidate), and the manifest file parsing (another pipeline per file), and one event starts roughly 50 to 70 short-lived processes before any network call happens.
Starting a process sounds free, and run once it nearly is. But on macOS, with endpoint security or antivirus software inspecting every launch, and with several agents firing hooks at the same moment so dozens of these scripts compete for the process table at once, the launches add up. That multiplication is what pushed runs past Claude's 30-second limit.
How I fixed it
The script already starts with #!/bin/bash, and bash can do everything those external programs were doing without starting a single process. Here is the same function, rewritten:
json_field() {
local KEY RE
for KEY in "$@"; do
RE="\"$KEY\"[[:space:]]*:[[:space:]]*\"([^\"]*)\""
if [[ $INPUT =~ $RE ]]; then
[ -n "${BASH_REMATCH[1]}" ] \
&& { printf '%s' "${BASH_REMATCH[1]}"; return; }
fi
done
}
The =~ operator is bash's built-in pattern matcher, and BASH_REMATCH holds whatever the parentheses captured. No pipe, no subshell, no programs. The same idea applied everywhere else:
- The preview extraction and the manifest read also became
[[ ... =~ ... ]]. The pattern lives in a variable on purpose: that is the form that behaves identically on the ancient bash 3.2 that macOS still ships at/bin/bash. - JSON escaping became parameter expansion,
${value//\\/\\\\}and${value//\"/\\\"}, instead of a pipe throughsed. - Reading the input became
read -d ''instead ofcat.
I kept the matching rules exactly the same on purpose: the first match wins, the first non-empty fallback name wins, and the preview keeps the raw JSON text with its escapes intact. A performance fix that changes what goes over the wire is two bugs wearing one diff.
How I proved it
Three layers of proof, which is the part I am happiest with.
1. A test that makes the bug loud. The new test runs the real script with a PATH that contains only bash and a link to curl. Nothing else exists. On the old script this fails spectacularly: about 70 lines of command not found from a single event. That is the bug, made visible as a test failure. On the new script, the full payload arrives at a fake host service, including a preview with escaped quotes and backslashes.
2. Golden tests that pin behavior. The package already had 54 tests that run the real script against a fake host service and check the exact payloads delivered. All of them pass unchanged against the rewrite, so nothing about the output moved.
3. A free before-and-after measurement. The hook's test suite runs the real script dozens of times, so its own wall time is a benchmark: 10.5 seconds before, 1.5 seconds after, on the same machine. I also ran the rewritten script by hand under /bin/bash 3.2.57 to prove the stock macOS shell handles it.
What I left out, and why
The issue's triage suggested two further changes: make the network send asynchronous, and add a short timeout to the hook registration. I left both out and said so in the PR. Sending in the background can reorder Start and Stop events as they arrive at the host, and a tight timeout can drop a lifecycle event entirely, which is exactly how terminals end up stuck showing the wrong status. Removing the measured cost was this PR's job. Those two deserve their own discussion. Saying what you did not change, and why, is half of what makes a PR easy to trust.
Part 2: the race that could log out every agent
How I found it
This one came from a hypothesis, not a report. Superset's whole point is parallelism: automations, orchestration, and hooks all shell out to the superset command-line tool, often many at once. So I asked one question. What state do all those parallel processes share, and is every access to it safe when two of them touch it at the same time?
The shared state is ~/.superset/config.json. It holds one access token and one refresh token for the whole machine.
My first suspect was the file write itself. If two processes write the config at once and the write is not atomic, you get a torn, half-written JSON file. I read the code, and the first suspect was innocent: writeConfig already writes to a temporary file and renames it into place, which is atomic. Dead end, reported honestly in the issue.
The second suspect was the refresh path, and that one was guilty. The logic in resolve-auth.ts was:
if the access token expires within 5 minutes:
call the token endpoint with the stored refresh token
write the new tokens to the config
No lock, no coordination, nothing. Every concurrent process that lands inside that five-minute window reads the same refresh token and spends it on its own.
What the server does with a spent token
Whether that matters depends entirely on the server. So instead of guessing, I read the installed server code. Superset's login uses the @better-auth/oauth-provider package, version 1.6.22, and the whole grant handler is right there in node_modules. Two findings settled it.
Refresh tokens rotate, atomically. On every refresh, the old token's database row is marked revoked with a compare-and-set (an update guarded by "revoked is still null"), and a new refresh token is issued. If two processes refresh with the same token at the same time, the database guarantees exactly one wins. The loser gets invalid_grant.
Reusing a rotated token is treated as theft. If a request arrives carrying a refresh token that is already marked revoked, the server calls invalidateRefreshFamily, which deletes every refresh token and every access token that user holds for this client. That is a standard, sensible defense against stolen tokens. It is also exactly what an innocent parallel process looks like when it read the config a moment before the winner wrote the new token.
The failure, in three beats
Put the client and the server together and the whole thing plays out in three beats.
- The access token is a week old. Several commands run at once, all inside the refresh window. All of them send the same refresh token.
- One wins the compare-and-set and writes fresh tokens to the config. The others get
invalid_grant, and the client turns that intoSession expired. Run: superset auth login, even though a perfectly good token now sits in the file right next to them. Random, confusing failures. - The dangerous beat. Any process that read the config before the winner wrote it sends the now-revoked token a moment later. The server sees reuse, assumes theft, and wipes the family. The winner's brand-new tokens die too. Every agent, every terminal, every automation on this login fails until a human logs in again.
The access token lives for seven days, so this window opens about once a week per login. Rare, which is exactly why nobody would ever connect the dots. "About once a week all my agents randomly log out," with nothing in any log to explain it. And because automations run unattended, the burst that triggers it usually happens when nobody is at the keyboard.
How I fixed it
The fix is client-side only, in a new module whose job is to make the whole machine behave like one login client instead of many.
- One refresh at a time, across processes. A lock file next to the config serializes the refresh. It is created exclusively (the create fails if the file already exists), carries the holder's process id, and is removed on release.
- Re-read before spending. After taking the lock, the process reads the config again. If another process already renewed while it waited, it uses that token and never touches the network. This is the line that prevents the family wipe, because the stale token is never sent twice.
- Re-read before giving up. If a refresh still fails, the process reads the config once more. If a fresh token appeared in the meantime, the race was lost harmlessly, and the command proceeds with the winner's token instead of telling the user their session expired.
- Crash safety without deadlock. A lock left behind by a dead process is detected by age and taken over with a rename, and a rename can only succeed for one waiter, so the takeover itself cannot race. A process that waits too long for the lock proceeds without it, which degrades to today's behavior rather than making login impossible, and step 3 still covers that path.
How I proved it
The module takes its clock, its sleep function, its config store, and its token endpoint as inputs, so the tests are fast and deterministic with no real waiting. (The repo's test rules forbid tests based on real time, for good reason.) Seven tests pin the contract:
- Three concurrent callers produce exactly one call to the token endpoint, and all three end up holding the winner's token.
- An already-renewed config short-circuits with zero network calls.
- A failed refresh falls back to a token another writer stored.
- A failed refresh with nothing fresh on disk still reports the session as expired.
- A stale lock from a dead process is taken over.
- The lock is released after a failure, so the next caller proceeds immediately.
Full CLI package after the change: 427 tests passing, typecheck and lint clean. I filed the issue first with the complete analysis, including exact file and line references on both the client and the server, and the reproduction steps, then opened the PR against it.
Part 3: the review rounds, where the robots found my bugs
Both PRs were reviewed within minutes by Superset's two review bots, CodeRabbit and Greptile. I want to spend real time on this part, because the findings were real, the fixes changed the design, and the exchange is what taking review seriously looks like. My rule for every comment: verify the claim against the code before agreeing, fix what survives verification, and push back with reasons on what does not.
Round one: three real holes in the lock
The lock PR collected the most serious findings, and both bots independently converged on the same root problem from different angles.
1. My staleness math was unsound. The lock treated any holder older than 30 seconds as a dead process and stole its lock. But the refresh network call had no timeout at all, so a live process on a slow connection could hold the lock for a minute while still working. My lock, built to stop token theft, could mug a living process. The fix went to the root: the refresh call is now bounded at 10 seconds, which makes the arithmetic honest. A holder is provably finished or dead well inside the 30-second threshold, so "stale" now really means "dead."
2. Release did not check ownership. Releasing the lock deleted it by filename. If my lock had been taken over while I was slow, I would delete the new holder's lock, and the failure could cascade. Now every acquisition writes a unique token into the lock file, release only removes a lock that still carries its own token, and a takeover re-reads the renamed file to confirm it took the lock it saw, handing it back if the owner changed in between.
3. One error path could spin forever. If the filesystem refused the takeover rename, my retry skipped both the deadline check and the sleep: a hot loop. The deadline check moved ahead of the takeover work, and every error path now falls through to the sleep.
Two new tests pin the ownership behavior and the degraded wait, bringing the module to nine. This is where the design visibly improved under fire. The shipped version is stronger than my first version, and the bots deserve the credit for two of the three insights.
Round one, smaller findings
The worktree delete learned to check what it deletes. An older PR of mine in the same repo (making workspace deletion fast by letting the app remove the files instead of git) got two findings in the same round, both valid. Handing the delete to the app had skipped the checks git used to do implicitly. A stored path that was itself a symlink could resolve into a neighboring workspace and pass the safety guard, and an unregistered folder inside the managed root would be deleted even though git would have refused. The fast delete now runs only when the stored path is not a symlink and the resolved path appears in the repository's own worktree list. Everything else falls through to git, which refuses it exactly as before. The one thing worth keeping from the slow path was its paranoia.
The hook's escaping gap, inherited at high speed. CodeRabbit noticed the hook's JSON escaping did not handle control characters: a newline or tab in an environment value would produce an invalid payload. True, and also pre-existing, because the old sed version had exactly the same blind spot. I had just inherited it at much higher speed. Since the fix costs nothing with the same parameter-expansion trick, the five control characters shells realistically carry now get their short JSON escapes, still with zero processes started, with a test that delivers a token containing a newline and a tab intact.
The help text that wrote checks the code could not cash. On an automations PR, Greptile caught my new help text promising that an empty workspace flag clears the pin, when for cloud automations the empty value slipped through every "is this falsy" check and did nothing. Two honest options: weaken the docs or strengthen the code. The server already accepted an explicit null for the cloud pin, so I made the code match the promise, with a test.
Round two: the best finding of the week
The next day both bots reviewed the fixes themselves, and three of the four new comments were real. Review is not a gate you pass once. It is a loop, and my round-one fixes had introduced one subtle problem of their own.
CodeRabbit noticed that the 10-second timeout I added to the refresh call, the fix that made the lock's staleness math honest, had quietly created a new hazard. A timeout aborts the client, but the server may have already rotated the token before the response was lost. The old refresh token then still sits in the config, the next process replays it, and the server's theft detection revokes the user's tokens on every machine. My fix for one family-wipe path had built a tidy little machine for producing another.
The answer is a pattern worth remembering: consume before spending. Inside the lock, the refresh token is deleted from the config before the network call goes out. Now an aborted, timed-out, or crashed refresh leaves nothing replayable on disk, and the worst case shrinks from "every machine logged out" to "one re-login on this machine." A failed refresh burns the token on purpose, which sounds aggressive until you compare the prices. A test pins the core of it: while the refresh request is in flight, the token is already gone from disk.
Two more, same day. The waiter that gave up after its 45-second budget used to fall back to refreshing with the same stored token, right beside a live holder doing the same thing. It now refuses, failing that one command with an honest "another command is renewing the login, retry in a few seconds" instead of the misleading re-login prompt. And the lock's give-back path, which returned a mistakenly stolen live lock by renaming it home, could flatten a lock a third process had created at that path in the meantime. It now uses a hard link, which cannot replace an existing file where a rename happily would.
The worktree delete, completed. The round-one symlink fix had bolted the front door and left git holding it open: skipping only the app-side delete still let git remove whatever the link resolved to, since git receives the resolved path too. A symlinked stored path is now refused outright before anything touches the disk, the delete blocks with a reason, and the workspace un-archives. The test proves the neighboring worktree survives with its files through both paths.
Round three: knowing when to say no
The last round was small, but it is about the other half of review discipline: declining well.
CodeRabbit came back once more on the hook PR, asking to escape the rarer control bytes too (ESC and friends), not just the five common ones. Three things made this a no instead of a yes. The same bot had already accepted leaving those bytes to their producers, in writing, in the thread it had just resolved. The gap predates the PR entirely. And the proposed fix needs a character-by-character bash loop, which would reintroduce per-byte work into a script whose whole reason to exist is being flat. The decline cited the reviewer's own acceptance as precedent and ended with an offer: if a real payload ever shows up with a stray control byte in the wild, that is a one-line producer fix with a test, and I will write it.
Saying yes to eleven findings is what earns the right for the nos to be taken seriously. A reviewer, human or bot, learns quickly whether your agreement means anything by watching whether your disagreement ever does.
The same sweep caught the worktree PR drifting into merge conflict again as the main branch moved. Open PRs rot quietly. Rebased, one import collision resolved, suites re-run, pushed, mergeable again. Keeping a PR green while it waits is part of the contribution.
On replying with jokes
Every reply led with one line of humor and followed with the substance: what was fixed, the commit hash, the test that pins it. "I built a lock to stop token theft and then taught it to mug living processes." "You caught the help text writing checks the cloud branch could not cash." Review threads are public record. Being light about your own bugs while being rigorous about fixing them reads a lot better than either defensiveness or silence.
The scorecard
What I'd take away
1. Rank bugs by time stolen, not by how loud they are. A hook that adds seconds to every prompt for every user outranks almost any crash that happens once.
2. Process starts are a real cost. A shell script that pipes through grep | head | sed | tr per field looks harmless and is fine when run once. Run it fifty times per event, on every event, under antivirus scanning and concurrency, and it becomes a product problem. The shell can usually do the job itself.
3. Write the test that makes the bug loud. The restricted-PATH test turns "this script launches too many processes" from a vague claim into 70 red lines in a failure message. Future regressions announce themselves.
4. Read the other side before blaming your side. The refresh race only becomes a real bug because of what the server verifiably does. The receipts came from reading the installed dependency's actual code in node_modules, with line numbers, not from assuming.
5. Hunt where the architecture concentrates risk. Superset's superpower is parallelism, so the right question was "what shared state do parallel processes fight over." The first suspect was innocent. Saying that in the issue builds trust in the part that was guilty.
6. Rare plus catastrophic beats frequent plus mild. A once-a-week window with a total-logout blast radius is a worse bug than a daily annoyance, precisely because nobody can reproduce it on demand or correlate it with anything.
7. Say what you did not change. Both PRs list the plausible extra changes that were left out and why. Reviewers trust a diff more when its edges are drawn on purpose.
8. Treat review bots like reviewers, not noise. Verify every claim against the code first. Of fifteen findings over three rounds, thirteen survived verification and made the designs better, and the two that did not got reasoned declines instead of blind fixes.
9. Your fix can be the next bug. The timeout that made the lock honest created the replay hazard. Review loops exist because second-order effects hide from the person who just solved the first-order problem.
10. Consume before you spend. When using a one-shot credential whose reuse is punished, remove it from storage before the network call, inside the lock. An ambiguous outcome then costs one local re-login instead of a fleet-wide revocation.
11. When docs and code disagree, consider fixing the code. The help text overpromised, the server already supported the promise, so the code grew into the docs instead of the docs shrinking to the code.
I'll end where the last post ended, because it keeps being true. I spend my days on infrastructure for agents that use computers, and the recurring lesson is that agents amplify whatever the tooling under them does. A hook that costs a second becomes a hook that costs a minute when ten agents fire it at once. A token refresh that is safe for one process becomes a fleet-wide logout when ten processes do it in the same five minutes. Nothing about either bug was exotic. They were ordinary scripts and ordinary auth code, multiplied.