Your Agent's Stop Button Stops the Agent. It Doesn't Stop the Side Effects.

In a seeded model, a stop flag in the agent loop let a mean of 39 side effects through after STOP, and 589 in the worst run. Revoking at the gateway let 0.


Every agent platform has a stop button somewhere. Usually it sets a flag, and the agent’s main loop checks the flag before each step. Press it and the agent stops planning, stops calling tools, and reports that it’s been halted.

That’s true for the loop that reads the flag. It isn’t true for the work that loop already started: the subagent it spawned, the retry it scheduled, the job it put on a queue, the tool call that’s on the wire. Those keep going, and from the outside, an agent that’s “stopped” while its side effects keep landing is still running.

The question for a kill switch isn’t “did the agent stop?”. It’s “did the side effects stop?”, and the answer depends on where the stop is enforced.

The model

I built a small discrete-event model of one agent run to count side effects after STOP. The agent is invented and the timing is illustrative. The numbers describe how the three designs behave, not how any real framework does. The script is at the end.

  • The parent agent alternates between thinking (1–6 seconds) and tool calls (0.5–4 seconds to land).
  • Each step has a 15% chance of spawning a subagent, which runs 3–8 steps of its own and can spawn more.
  • Each tool call has a 10% chance of failing and scheduling a retry 5–30 seconds later.
  • The operator presses STOP at 60 seconds, and I watch for 10 more minutes.

Three places to put the stop:

  1. Loop flag. The parent checks a flag before each step. Subagents and the retry scheduler don’t read it.
  2. Cancel the tree. STOP cancels the parent and every subagent it spawned. Retries live in a separate scheduler and still fire.
  3. Revoke at the gateway. STOP suspends the agent’s credential at the tool gateway. Every call sent after STOP is refused, whoever sends it.

Results

Side effects sent after STOP, across 200 seeded runs:

Stop designMeanMedianp95Worst run
Loop flag39.17178589
Cancel the tree1.3147
Revoke at the gateway0.0000

Plus, in every design: a mean of 1.4 tool calls (up to 8) were already in flight at the moment of STOP and landed anyway.

The loop flag is the worst kind of control: it works in the median case. Seven side effects after STOP sounds like a race condition you could live with. The tail is where it breaks. A subagent spawned just before STOP keeps running, spawns its own subagents, schedules its own retries, and none of them read the parent’s flag. In the worst run, 589 side effects landed in the ten minutes after the operator believed the agent was halted. That’s the run you get during an incident, because an agent that’s misbehaving badly enough to stop is usually also one that’s been busy.

Cancelling the tree fixes most of it, if you can actually enumerate the tree. What it misses is everything the agent handed off to infrastructure it doesn’t own: here, retries in a scheduler. In a real system add queued jobs, workflow engines, webhooks registered for later, cron entries the agent created. Each of those is a place the agent’s intent survives the agent.

Revoking at the gateway is the only design where “stopped” means stopped, because it doesn’t depend on knowing what the agent started. It doesn’t matter which process sends the next call, or when. The authority behind it is gone.

In-flight calls are a fact, not a bug

No design caught the 1.4 calls already on the wire. A request that has passed the gateway will land, and nothing on the agent’s side can recall it. A kill switch has to plan for these rather than pretend they don’t exist:

  • Record them. At STOP, the gateway knows exactly which calls are in flight. Write that list into the incident record, so the responder checks those systems first.
  • Make side-effecting tools idempotent and reversible where possible. An idempotency key means an in-flight call that gets retried by something else doesn’t happen twice. A compensating action means the one that did land can be undone.
  • Prefer short-lived, narrowly scoped credentials. A credential that expires in minutes bounds the damage even if revocation is slow. Delegated tokens issued per task make revocation precise: you can stop one agent run without stopping the platform.

A kill switch checklist

  1. Enforce at the authority layer. The tool gateway, the API proxy, the credential issuer. Not the agent’s loop, and not the agent’s prompt.
  2. Stop the agent’s identity, not the process. Every subagent, job and retry the agent creates should act under an identity that the stop revokes. If a subagent runs under its own unrelated credential, your kill switch has a hole the size of that subagent.
  3. Sweep what the agent left behind. After revocation, list the queued jobs, schedules and registrations the agent created during the run, and cancel or quarantine them. Revocation stops them from acting; it doesn’t remove them.
  4. Measure stop latency in drills. Press the button in staging on a busy agent and count side effects that land after it, the way you’d test a backup by restoring it. A stop you’ve never measured is a hypothesis.
  5. Make STOP cheap to press. If halting an agent needs a ticket, people will hesitate during an incident. One action, scoped to one agent run, reversible by re-granting.

The script

Standard library only. Seeded, so you get exactly the numbers above. Save as kill_switch.py and run it with python3.

"""Where should an agent's stop button live? Counting side effects after STOP.
Synthetic, seeded, stdlib only. A discrete-event model of one parent agent that
spawns subagents and schedules retries; the agent is invented, the timing is illustrative.
"""
import heapq
import random

SEED = 5
STOP_AT = 60.0          # seconds into the run the operator presses STOP
HORIZON = 600.0         # how long we keep watching after that
TOOL_LAT = (0.5, 4.0)   # tool call latency range (s)
THINK = (1.0, 6.0)      # model "thinking" time between tool calls (s)
SPAWN_P = 0.15          # chance a step spawns a subagent
RETRY_P = 0.10          # chance a tool call fails and schedules a retry
RETRY_DELAY = (5.0, 30.0)
SUBAGENT_STEPS = (3, 8)


def run(design, seed=SEED):
    """design:
    'loop-flag'   parent checks a stop flag before each step; subagents and retry
                  timers don't share the flag.
    'cancel-tree' stop cancels the parent and every task it spawned; queued
                  retries live in a separate scheduler and still fire.
    'gateway'     stop revokes the agent's credential at the tool gateway; every
                  side effect after STOP is refused there, whoever sends it.
    """
    rng = random.Random(seed)
    q, seq = [], 0
    def push(t, kind, owner, steps=None):
        nonlocal seq
        heapq.heappush(q, (t, seq, kind, owner, steps)); seq += 1
    push(0.0, "step", "parent", None)
    landed_after_stop = 0
    in_flight_at_stop = 0
    n_sub = 0
    while q:
        t, _, kind, owner, steps = heapq.heappop(q)
        if t > STOP_AT + HORIZON:
            break
        stopped = t >= STOP_AT
        if kind == "step":
            if stopped:
                if design == "loop-flag" and owner == "parent":
                    continue
                if design == "cancel-tree":
                    continue
            if steps is not None:
                if steps == 0:
                    continue
                steps -= 1
            # issue a tool call; it lands (has its side effect) after latency
            land = t + rng.uniform(*TOOL_LAT)
            push(land, "land", owner, (steps, t))
            if rng.random() < SPAWN_P:
                n_sub += 1
                push(t + 0.1, "step", f"sub{n_sub}", rng.randint(*SUBAGENT_STEPS))
        elif kind in ("land", "retry"):
            sent = steps[1] if kind == "land" else t
            if t >= STOP_AT:
                if sent < STOP_AT:
                    in_flight_at_stop += 1      # already past the gateway: nobody can recall it
                elif design == "gateway":
                    continue                    # sent after STOP: refused at the gateway
                else:
                    landed_after_stop += 1
            if kind == "land" and rng.random() < RETRY_P:
                push(t + rng.uniform(*RETRY_DELAY), "retry", owner, None)
            if kind == "land":
                push(t + rng.uniform(*THINK), "step", owner, steps[0])
    return landed_after_stop, in_flight_at_stop


if __name__ == "__main__":
    print("side effects sent AFTER stop (200 seeds), plus calls already in flight at stop")
    for d in ("loop-flag", "cancel-tree", "gateway"):
        rs = [run(d, s) for s in range(200)]
        new = sorted(r[0] for r in rs)
        fl = [r[1] for r in rs]
        print(f"  {d:12s} mean {sum(new)/200:5.1f}  median {new[100]:3d}  p95 {new[190]:4d}  max {new[-1]:4d}"
              f"   | in flight at stop: mean {sum(fl)/200:.1f}, max {max(fl)}")

Full output:

side effects sent AFTER stop (200 seeds), plus calls already in flight at stop
  loop-flag    mean  39.1  median   7  p95  178  max  589   | in flight at stop: mean 1.4, max 8
  cancel-tree  mean   1.3  median   1  p95    4  max    7   | in flight at stop: mean 1.4, max 8
  gateway      mean   0.0  median   0  p95    0  max    0   | in flight at stop: mean 1.4, max 8

Limits

  • One agent, idealized. Real agents have queues, workflow engines and webhooks that this model folds into “retries”. Each of those is another path the tree-cancel design misses.
  • Revocation is modeled as instant. In practice, credential caches and token lifetimes add delay. A cached token valid for 15 minutes means the gateway design isn’t zero until the cache expires, unless the gateway checks a revocation list on every call.
  • The spawn and retry rates are invented. The tail of the loop-flag design is driven by subagent spawning. Agents that don’t spawn subagents will see a much smaller gap, until someone adds that feature.
  • Stopping isn’t recovering. A kill switch ends the damage; it doesn’t undo it. The evidence of what the agent did before STOP is what lets you reconstruct and reverse it.

A stop button is a promise that the agent can no longer change anything. Put it where that promise can be kept.

Frequently asked questions

How should you implement a kill switch for an AI agent?

Enforce it where the agent's authority is checked, not inside the agent's own loop. The most reliable stop revokes or suspends the agent's credential at the tool or API gateway, so every side effect sent after the stop is refused no matter which process sends it: the parent agent, a subagent, a retry timer, or a queued background job. A flag in the agent loop only stops the loop that reads it.

Why doesn't cancelling an AI agent process stop everything it was doing?

Because the agent's work outlives its process. Subagents run as separate tasks, retries sit in schedulers, background jobs sit in queues, and tool calls already sent can't be recalled. In a seeded discrete-event model, a stop flag checked by the parent loop let a mean of 39.1 side effects land after STOP across 200 runs, with a worst case of 589. Cancelling the whole task tree cut that to 1.3, all of them queued retries.

Can a kill switch stop tool calls that were already in flight?

No. A request that has already passed the gateway will land, and nothing on the agent's side can recall it. In the model, about 1.4 calls were in flight at the moment of STOP on average, and up to 8. Plan for them: make side-effecting tools idempotent and reversible where you can, and record in-flight calls at stop time so the incident responder knows what to check.

Comments