Continuations and Cancellation
How several replicas keep one task to one turn at a time, what that costs, how it behaves when the network to the database fails, and how a cancel taken by one replica stops an executor running on another.
One turn of a task at a time, on whichever replica
Within one replica, a second SendMessage naming a task whose executor is
still running is refused, and a continuation of a task parked at
input-required waits for the turn that parked it to store its last events.
Both decisions read state the replica keeps in memory, so on their own they
did not cross replicas: before turn claims a continuation that reached replica B
while the task's turn ran on replica A was admitted, B started a second
executor, and B's save replaced what A stored after B read the task.
Turn claims close it. The PostgreSQL and SQLite stores (plain and
tenant-aware) keep a table, a2a_task_claims, in the same database as the
tasks, and the handler takes a row in it for each turn:
- A send claims its task once it knows which task that is, and then its
idempotency key if it carries one. The row names this replica (
HOSTNAME, the process id and a random suffix;with_replica_nameoverrides the first) and a random token for the turn. - A claim another turn holds is waited for, for up to
executor_drain_timeout(5 s by default), the same bound the in-process wait for a parked turn has. If it is still held then, the send is refused exactly as on the replica running the task:UnsupportedOperation, "task … is already being processed". A send takes its idempotency key only once it holds the turn, so a send that waits holds none, at any moment of the wait: a retry of it that reaches a third replica meanwhile is not answered "accepted" for a send that is then refused. The retry waits its own turn, and the first of the two to hold the turn takes the key and runs; the other reads the key before each attempt and is answered with the first one's task. A retry of a send that is running is answered at once: it finds the task claimed, reads who holds the key (a read that takes nothing, on every bundled store) and replays. The wait is not under the lock that serialises the sends of one context on this replica, so a send to another task of the same context goes on meanwhile. - A continuation reads the task again once it holds the claim, and starts from that read, so it keeps everything the last turn stored, wherever that turn ran.
- The claim is released when the turn's last write is done: the executor's future and its event consumer (the background processor, or a blocking send's collector) both hold it, and it is deleted when the last of them ends.
- Every write a turn makes carries its token, and the store refuses it,
in the same statement, unless the token still holds a claim. A replica that
stalled for longer than the claim's time to live (a long pause, a partition
from the database) and wakes up after another replica took the task over
is refused on its first write; its executor is then cancelled and it writes
nothing more (
ClaimLost). On PostgreSQL the check locks the claim row (FOR KEY SHARE). Without the lock, under READ COMMITTED, a write that started before a takeover and then waited on the task row was checked against the claim as it stood when the statement began, passed, and landed over the new turn's write (reproduced with twopsqlsessions). Renewals and cancel marks change no key column and never wait on the lock. - A replica renews the claims it holds every second, in one statement
naming each one, while it holds any. A claim it no longer tracks (a release
the database did not answer, a request dropped while its claim was being
written) is not renewed and expires. A replica that dies stops renewing;
after the time to live (15 s by default) the next send for one of its tasks
takes the claim over and continues the task, which is still
Workingin the store. That is the longest a task waits after its replica dies. - A replica that shuts down releases its claims (
shutdown,shutdown_with_timeout), so a rolling restart does not hold its tasks for the time to live. An executor still running then has its next write refused, as after a takeover.
with_turn_claim_timing(ttl, renewal) changes the two durations; build
refuses a time to live under 3 s, or a renewal interval that is not at most a
third of it. without_turn_claims() turns them off, for a store only one
replica uses: each turn then saves its two statements (the claim and its
release) and the renewal. A custom store several replicas share provides
claims by overriding TaskStore::turn_claims and fencing its writes with
store::claim::current_fence (Stores shared by replicas), or is
given them with with_turn_claims. build refuses with_turn_claims over a
store that has claims of its own, the bundled ones included: their writes are
fenced against their own table, so claims kept anywhere else would refuse
every write.
An approval toward a quorum (with_approval_gate, with_quorum) is counted
under the claim, so two approvals arriving at two replicas at once are
counted one after the other and the executor resumes once.
What it costs
tests/soak_multi_replica.rs: two replicas, one
PostgreSQL 17 database, eight clients each sending a new task to one replica
and reading it from the other, release build, one 4-vCPU Linux container,
2026-10-28. The database was reached directly, then through toxiproxy 2.12.0
adding latency each way; the round trip is what was measured on the link
(the smallest of 20 PostgreSQL SSL-request exchanges), not what was set.
Three 30 s runs per row, alternating (the first run of the 1 ms row with
claims overlapped a compile and was run again):
| Round trip to the database | With claims | Without | Median per pair, with / without |
|---|---|---|---|
| direct | 532 ± 11 pairs/s | — | 14.6 ms |
| 1.0 ms (proxy alone) | 390 ± 13 | 443 ± 13 | 19.8 / 17.4 ms |
| 2.8 ms | 166 ± 1 | 181 ± 8 | 48.5 / 43.7 ms |
| 11.2 ms | 54 ± 0 | 59 ± 0 | 148 / 134 ms |
The claim adds one to two round trips to a turn (2.4 ms at 1.0 ms, 4.8 ms at 2.8 ms, 13.4 ms at 11.2 ms): 8% to 12% fewer pairs. What dominates on a real network is the rest of the send path, so put the database close to the replicas. Counted at the wire (a proxy logging each time the client waited on the server), a send that starts a task and a read of it make 8 statements, a send that continues one and a read 11; each is followed by the ping sqlx makes as the connection returns to the pool, off the request's path, and a connection idle for a second or more is pinged before it is used. Both made 45 round trips before 2026-10-28, when the same soak measured 334 ± 31 pairs/s direct, 238 ± 3 at 1.2 ms, 67 ± 1 at 2.6 ms and 21 ± 1 at 11.1 ms, with claims. Every claim was released by the end of every run, and no run had a failed request or a task one replica could not read from the other.
What the stores do when the database drops a connection mid-turn is on Sharing the store.
When the network fails
Measured 2026-10-28, with two replicas as separate processes, each reaching PostgreSQL through its own toxiproxy link, default timing:
- Cut the running replica's link for 5 s, under the claim's 15 s time to live: a continuation sent to the other replica meanwhile was refused after its 5 s wait; when the link came back the turn went on writing (its artifact grew from 5 parts to 23 in the next 9 s, none lost), and a cancel sent to the other replica stopped its executor 0.71 s later.
- Cut it for 20 s, past the time to live (measured before the change described
below): the other replica ran a continuation 16.1 s after the cut, to
completed; the cut-off replica's executor, still running, had every write refused once its link was back (the artifact stayed at the 4 parts it had at the takeover), and was stopped on its first renewal, about 2.5 s after the link returned. So it ran for the whole cut, unfenced and unable to write. - Restart PostgreSQL mid-turn: the turn went on writing once the database was back (5 parts before, 15 five seconds after it was ready).
A replica that cannot renew stops its turns
A replica cut off from the store cannot tell that it lost its claim: its
renewals fail, nothing is reported, and the second bullet above is what that
used to cost. Since 2026-11-01 a holder stops acting on a claim it can no
longer prove it holds, and before anyone else can take it over. Each claim
records when the replica last had proof (the moment before it was taken, or
before the renewal the store last answered). A watchdog, which does not wait
for the renewal call (that can hang on a starved pool), stops every turn whose
proof is older than four fifths of the time to live: 12 s of the default 15 s.
The turn's executor is cancelled and the task ends failed, failure class
transient, never canceled, as at shutdown; its message says to send it
again as a new request, because a retry that reuses the first send's
idempotency key is answered with the failed task. The other replica's reaper
or next send then takes the task over at 15 s, with nothing of the first
executor still running. A blip shorter than the margin stops nothing.
Three things go with it. Renewals use a pool of their own (two connections), so traffic cannot starve them. A replica's own reaper skips the tasks it holds, so after a database outage it does not end a turn it is still running. And the reaper starts when the handler is built, not at its first request, so an idle survivor of a dead peer still ends the peer's orphans.
Verified in process, with a claim store whose renewals can be made to fail
(tests/claim_lapse.rs: a cut ends the turn transient, a 0.9 s blip stops
nothing), and against PostgreSQL for the pool (postgres_renews_while_the_task_pool_is_exhausted).
Repeated live through toxiproxy on 2026-11-14, two replicas on PostgreSQL 17 at
the default timing (scripts/live/partition_live.py, P2; the
Qualification Matrix): with the running
replica's link cut for 20 s, its watchdog stopped the turn 13.1 s after the cut,
the other replica's reaper ended the task failed, class transient, at 16.0 s,
a continuation sent to it was refused as terminal, and the cut-off replica wrote
nothing more, before or after its link came back. The 5 s cut and the database
restart behaved as in the 2026-10-28 run above.
A finished task whose owner died before it finished the ending
A turn that ends releases its claim. A claim that is still there behind a task in
a terminal state means the replica that held it stopped after the state
reached the store and before it finished what follows: the ending in the event
log, the webhooks, the audit record. The state can reach the store without the
owner. A CancelTask that lands on a replica not running the turn stores
canceled and leaves the ending to the owner's own event processor; an owner
killed in between left a task that GetTask reported canceled while its log
stopped short and its webhooks never heard (hostile campaign W2-hostile-3).
Every look of the reaper now also takes over such a claim, once it has been
expired for longer than the claim's time to live, and reads the log's last
event. If the log does not end with the task's terminal status, the reaper
appends it at the next position and sends it to the task's webhooks, once. If it
does, the owner got that far and nothing provable is missing, so the reaper only
releases the claim. A claim this replica holds itself, one that is live and one
that expired a moment ago (a slow owner, not a dead one) are left alone. The
finished outcome of the claim-events metric counts the endings completed.
Measured (PostgreSQL 16.15 on a 4-vCPU shared virtual machine, 2026-11-11, the
reaper's query run by hand with EXPLAIN ANALYZE): with 1,000,000 claims and 20
finished tasks among them, 0.45 ms and 121 buffers, the planner reading the task
table's state index and probing the claims by key; with 1,000,000 retained
finished tasks, 20,000 live claims and 20 stale ones, 3.7 ms and 288 buffers,
the planner reading the claims and probing the tasks by key. The cost follows the
smaller side, not the retained tasks, and the claims table gets no new index (an
index on expires_at would be written by every renewal, the hottest statement).
Run live (scripts/live/finish_live.py, two replicas on one PostgreSQL database,
the default 15 s claim time to live): a task held on replica A, CancelTask sent
to B, A killed with SIGKILL as the cancel returned. Before the change the stored
state was canceled, no event in the log carried the ending and the claim row
was still there 75 s later. After it, 44 s after the kill the log carries the
ending once and the claim is gone (the claim expires after 15 s, is stale after 15
more, and the survivor's reaper looks every 15 s); the same run with the owner in the
middle of a real model's answer (llama.cpp llama-server f3b407ca, Qwen3.5-2B
Q4_K_M, a slot processing when the cancel landed) took 42 s.
What this does not do: a replica without turn claims (a process-local store) has no claim to find, and the webhooks of a store with no event log are not sent an ending, because there is nothing to prove one missing by. A push the owner had queued and lost with it is the outbox's matter (ADR 0037), not this one's.
A known window: a killed owner and event positions
An event is numbered when it enters the owner's queue and is broadcast to the
subscribers attached to that replica at once; the background processor writes it
to the event log, under the same number, a moment later. A turn taken over after
its owner was killed (SIGKILL, out of memory, the node lost) numbers its
events from the end of the log, or from the position stored with the task if that
is later. So events the owner had broadcast but not yet logged, a window the
size of the persistence backlog at that moment, have positions the new turn
numbers again. A subscriber that saw them, or that resumes with Last-Event-ID
at one of them, can skip the new turn's first events as already delivered. The
stored task is not affected: GetTask always reads what was written.
This is a window, not a loop: it needs a kill during a store stall. The watchdog above removes the other way into it, an owner cut off from the store, because that owner stops at four fifths of the claim's life and writes a terminal event through its own queue before anyone can take over. The reaper, the close-out of a finished task and a continuation already number from the later of the log's end and the stored position.
It is accepted and documented, not fixed (audit F13, the maintainer's position
2026-11-03): closing it means the claim carrying the owner's broadcast
high-water mark in a schema change to two stores, or a takeover that jumps the
numbering and shows every client a hole after every takeover, and neither is
worth that for a window that needs a kill during a stall. It was read from the
code, not reproduced by a test. A client whose stream ends without a terminal
event should read the task with GetTask before it trusts a resumed stream, and
resubscribe from the state that returns.
Steering a task that runs elsewhere
With steering on (Steering a Running Task),
a message to a running task that reaches a replica other than the one holding
its claim is stored for that claim (TurnClaimStore::hand_steering, in the same
statement that checks the claim is live) and moved into the turn's inbox by the
replica that holds it, at its next look at the store (every renewal interval) or
when PostgreSQL announces it (SteeringConfig::with_notifications). A claim that
is gone refuses the message with 503; a full inbox delays it and a full store
refuses it. The table, a2a_task_steering, is created the first time steering is
used and costs a replica that holds a claim and takes steering one indexed read
per renewal interval.
Cancelling a task that runs elsewhere
CancelTask can arrive at any replica. On replica B, for a task whose
executor runs on replica A:
-
B finds no executor of its own to signal. It calls its own executor's
cancel(so an override that releases in-process resources releases B's, not A's), writesCanceled, and answers the clientCanceled. -
B marks A's claim on the task. A's next renewal, within about a second, reads the mark and fires the executor's cancellation token. With a halt store (
with_halt_store(PostgresHaltStore)) the cancel is also pushed to A at once (ADR 0024). -
Whatever A's executor writes after B's
Canceledis refused by the store, because the task is terminal in another state. From that refusal A cancels its executor's token (if the renewal has not already), adopts the stored task, and stops writing, pushing and logging the executor's events. A client streaming from A ends onCanceled, not on whatever A's executor emitted; a blockingSendMessagewaiting on A is answered with theCanceledtask; A deliversCanceledto the task's webhooks and appends it to the task's event log, which nothing else would, because B has no processor for the task.This does not depend on A's executor writing anything. One that simply returns when its token fires writes nothing, and until 2026-11-01 then nothing was delivered or logged, and a blocking
SendMessagewas answeredworking. Now, once A has stored the turn's events, a task that is terminal in the store without a terminal event having come through A is pushed once and logged at the next position, and the blocking call is answered with the stored task.
The client B answered is therefore never contradicted: before this was
enforced, all three stores let A overwrite Canceled with Completed, and
tests/cross_replica_cancel/ reproduced it on each.
What this does not give you:
- A clean stream on A. Non-terminal frames A's executor emitted between the cancel and its next write still reach a client streaming from A — though never the store. The terminal frame is held until the store has ruled on it, so the ending is right.
- An executor that honours the token. Cancellation is cooperative. An
executor that ignores
RequestContext::cancellation_tokenkeeps running on A until it returns, with its writes refused.