Repository navigation
fix(control-plane): stop claimKey stepping over a live idempotency claim mid-create - #1043
Conversation
An idempotency claim is written a round trip before the record it names (`claimIdempotencyKey` writes the key, `turns.create` the record), so a holder stalled between the two was indistinguishable from one whose record had expired. `claimKey` read both as "stale", released a LIVE claim and created a second turn for one key -- the duplicate fan-out §4.3 exists to prevent. On a gate key both resumes carry the same decision, and the second leaf finds the gate already decided and re-derives the same continuation, so one human approval ran twice: double spend, double side effects. A human decision and the deadline sweep race on that key by design (rossoctl#393 §3), which made this a regular path rather than a client-retry oddity. An unreadable holder is now treated as live for CLAIM_GRACE_MS (10 s) and stepped over after it -- option 1 of the issue, and the upgrade the `shortcut:` note in `claimKey` already prescribed. The age comes from `TurnStore.claimedAtOr`, one HSETNX plus a read on the claim hash the key already is. Treating an unreadable holder as live WITHOUT the age was never an option: the default key is the session id, so a crash between a claim and its create would wedge every later turn of that session with no self-heal. The READER stamps the age, not the claimant, so `claimIdempotencyKey` keeps its single round trip on the path every submission takes; the cost is that an orphaned claim frees a grace after the first duplicate attempt rather than a grace after the crash. The stamp is a field per holder, because a claim can change hands without the hash being deleted in between -- a holder that releases its key between a caller's read of its record and the stamp leaves a holderless hash the next claim adopts, and one shared `claimedAt` would then age the new holder from the old one's stamp and re-admit the very stepover this fixes. Visible change on the decision route: a second decision racing a winner that is still being created now answers `409 gate_not_pending` instead of 202 with a duplicate resume. The control plane cannot see which decision won, so a 202 could report an approval as accepted when an abort is what runs; the retry replays normally once the winner's record lands. Documented in openapi.yaml and in the fan-out design §4.3, which also now states the 10 s grace and that a deduplicated 202 inside it can name a turn whose GET 404s briefly. shortcut: a claimant that stalls between its claim and its create for longer than the grace is still stepped over. Telling that apart from a crash needs lease renewal, which §5.1's no-Lua/WATCH/MULTI rule forbids today. Closes rossoctl#989 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Self-review of the grace added in e667445. `claimGate`'s ZREM is the lock, so the deadline-index member is the only pointer that brings a later sweep pass back to a gate -- and the hand-back that re-adds it lived ONLY in the catch block around `submitResume`. The grace introduced a path that returns `created: false` without throwing: an unreadable holder of the gate key is now answered with its own turn id instead of being stepped over. The member was therefore dropped with nothing answering the gate, so a claimant that really died between its claim and its create left the gate permanently unanswered and `onTimeout: 'abort'` silently never fired. Before the grace the sweep stepped the ghost over and the gate was answered, so this was a regression the grace introduced, not a pre-existing hole. The reader-stamps design makes it worse: the sweep's first look is what starts the grace clock, so the pass that burns the last pointer to the gate is always the one that sees age 0, and the 10 s self-heal never gets a pass to run in. The catch block's hand-back condition already distinguishes the two cases exactly -- `findPausedBySession` builds `resumed` from records, so a ghost holder reads UNRESUMED (hand back) and a human decision whose record landed reads `resumed` (leave the member out, or a later pass would build a second resume for one decision). Lifted into `handBackIfUnanswered` and called from both paths; the catch block keeps its behaviour unchanged. Also from the review: the two past-grace tests derive their stale age from `CLAIM_GRACE_MS` instead of a magic `600_000`, which is what earns that constant its `export`; and `claimedAtOr` records the leak it can cause -- a holder releasing the key during the call leaves a stamp-only hash that nothing deletes. The new sweep test was re-run with the hand-back disabled and it is the only test that fails, so it is not vacuous. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Self-review turned up one real defect in the first commit, now fixed in 7898d17. The gate sweep could lose a deadline. Reader-stamping makes it sharper: the sweep's first look is what starts the grace clock, so the pass The Two smaller items from the same pass: the past-grace tests now derive their stale age from Verification: control-plane 2254 passed / 4 skipped, EXIT 0; Assisted-By: Claude Code |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Clean, well-argued fix that closes the #989 window at all three call sites (submitTurn, submitResume via /decision, and the deadline sweep), with the adjudicated trade-offs spelled out. I traced the grace through each caller: the fresh and non-terminal-holder branches return before it, terminal holders still step over immediately, and a holderless hash never reaches it because claimIdempotencyKey answers with the caller's own id. The /decision 409 is right for both same- and different-decision losers, and the retry converges via the found.resumed branch once the winner's record lands. The self-review fix in 7898d178 is the right predicate: findPausedBySession skips failed resumes, so an ordinary enqueue failure still hands the gate back, while a landed human resume reports resumed and the member stays out; the catch path is behaviourally unchanged. The new tests drive the age from CLAIM_GRACE_MS through the injected clock rather than a magic number, and the sweep test pins both the hand-back and the later firing.
Two non-blocking notes below: a narrow race in the new age stamp can answer a duplicate with a turn id that never materialises (suggestion), and one comment states a guarantee that only holds per process clock (nit).
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: control-plane TypeScript (turn-handlers, turn-store, gate-sweep), tests (contract, handlers, gate decision, sweep), docs (openapi, fan-out design)
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: 18/18 pass at 7898d178
Not run locally (no node_modules in this checkout); the suite result cited is the PR's own and CI is green at this head.
| // The holder finished (or its record is gone -- see the window in the doc above): the key is | ||
| // stale, so release THAT holder and take it. The second claim re-reads the holder, so losing the | ||
| // compare and losing the claim converge. | ||
| if (!existing && now - (await turns.claimedAtOr(owner, key, held, now)) < CLAIM_GRACE_MS) { |
There was a problem hiding this comment.
suggestion — a stepover that loses the race can 202 a turn id that will never exist.
Take a key held by a ghost H (crashed before create, so no claimedAt:H yet) and two submissions S and U racing on it. Both read claimIdempotencyKey → H and get(H) → null. U wins the stepover: its releaseIdempotencyKeyIf(key, H) deletes the hash, its second claim creates {turnId: U}, and its record follows. S's claimedAtOr(owner, key, H, now) then runs against U's hash — the del took claimedAt:H with it, so hSetNX succeeds, the stamp is now, the age is 0, and S returns {turnId: H, fresh: false}. submitTurn answers 202 with H (and correctly gives the quota slot back), but H's record never lands, so GET /v1/sessions/{id}/turns/H 404s forever — not "until the record lands" as the store doc and design §4.3 promise.
Before this PR, S fell through to releaseIdempotencyKeyIf (a no-op against U) plus a second claim and returned U's id. The window is one round trip on each side, but two retries of an old crashed claim is exactly when it opens.
Minimal fix: have claimedAtOr return the holder it read — the hGetAll path already has turnId in hand — and take the grace branch only while that holder is still held; otherwise fall through to the stepover, whose compare-and-reclaim already converges on U's id. That costs one extra read only on the stamping path.
There was a problem hiding this comment.
Confirmed and fixed in fae7ce4 — the race is real, and worse than "a 202 that may not have materialised": releaseIdempotencyKeyIf does a full del (turn-store.ts:241), so the winner's stepover takes claimedAt:H with it and S stamps a brand-new field on U's hash. Age zero, holder gone for good, GET 404s forever. That contradicts the promise the store doc and design §4.3 both make, and it is a regression against the pre-grace behaviour you describe.
Took your fix. claimedAtOr now returns { at, heldBy } and the grace branch reads:
const claim = await turns.claimedAtOr(owner, key, held, now);
if (claim.heldBy === held && now - claim.at < CLAIM_GRACE_MS)
return { turnId: held, fresh: false };A mismatch falls through to the stepover, whose compare-and-reclaim converges on U's id — exactly as before the grace. The extra hGetAll is on the stamping path only, and only on the unreadable-holder branch.
One thing it closes for free: the stamp-only hash I had recorded as a shortcut: leak is no longer a leak. heldBy reads null, the caller steps over, and releaseIdempotencyKeyIf treats a hash with no turnId as already released and deletes it. The note is gone and the docblock says why instead.
Test: the two-submission race driven through submitTurn with the same deterministic turns.get interleave the terminal-holder race test uses, asserting the loser gets the winner's id and that no record names the ghost. Re-run with the holder check removed, it is the only failing test. The store contract also pins heldBy for an unchanged holder, a stepped-over one and an unheld key — and the Redis half of the contract ran here this time, not just the fake.
| * (#989), so `claimIdempotencyKey` keeps its single round trip on the path every submission takes. | ||
| * The cost is that a claim orphaned by a crash starts its clock when the next submission first | ||
| * looks at it rather than when it was made, so the key frees a grace after the first duplicate | ||
| * attempt instead of a grace after the crash. It still frees, and it never frees EARLY, which is |
There was a problem hiding this comment.
nit — "it still frees, and it never frees EARLY" holds per process clock, not across replicas.
The stamp is written by whichever replica first reads the claim, and a later reader compares it against its own now (claimKey passes deps.now()), so a replica whose clock is more than CLAIM_GRACE_MS ahead of the stamping replica's steps over a live claim — the duplicate fan-out this PR closes. This is the same wall-clock assumption dueGates/gateDeadlineS already make, so documentation rather than code, but the guarantee as written is stronger than the design can make. Worth a clause naming the assumption.
There was a problem hiding this comment.
Fair — the guarantee as written claimed more than the design can deliver. Documented in fae7ce4:
It still frees, and it never frees EARLY, which is the side that would hand a live turn's key to a second submission -- within one replica's clock. ACROSS replicas it is the usual wall-clock assumption: whichever replica reads the claim first writes the stamp, and a later reader compares it against its own
now, so a replica running more than the grace ahead of the stamping one does step over a live claim. The same assumptiongateDeadlineSanddueGatesalready make, and skew that large breaks token validation first.
Docs only, as you say — naming the assumption rather than defending against it, since a replica that far out of sync fails on grant exp/nbf before it reaches a claim.
…anged Review of rossoctl#1043. `claimedAtOr` reported an age without saying whose claim it measured, and `releaseIdempotencyKeyIf` deletes the WHOLE hash -- stamp included. So two submissions racing past one orphaned claim diverge: the winner steps the ghost over, deletes the hash, re-claims and writes its record, while the loser's `claimedAtOr` then writes a fresh `claimedAt:<ghost>` onto the WINNER's hash, reads an age of zero and answers 202 with the ghost's turn id. That turn never existed and never will, so its GET 404s forever rather than "until the record lands", which is what the store doc and the fan-out design §4.3 promise. Before the grace the loser fell through to the stepover and returned the winner's id. `claimedAtOr` now returns `{ at, heldBy }` and the grace branch is taken only while `heldBy` is still the holder the caller read. A mismatch falls through to the stepover, whose compare-and-reclaim already converges on the winner's id. The extra `hGetAll` is on the stamping path only, and only on the unreadable-holder branch. Two things follow. A stamp-only hash is no longer a leak worth a `shortcut:`: `heldBy` reads as null, the caller steps over, and `releaseIdempotencyKeyIf` treats a hash with no `turnId` as already released and deletes it -- so the note is gone and the docblock says why. And the "never frees EARLY" guarantee is now stated as what it is: true within one replica's clock, while across replicas it rests on the same wall-clock assumption `gateDeadlineS` and `dueGates` already make. Tests: the two-submission race is driven through `submitTurn` with the same deterministic `turns.get` interleave the terminal-holder race uses, and the store contract pins `heldBy` for an unchanged holder, a stepped-over one and an unheld key. Re-run without the holder check, the race test is the only one that fails. The Redis half of the contract ran here, not just the fake. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
claimKeytreated "I cannot read the holder's record" as "the holder is finished". A claim iswritten a round trip before the record it names —
claimIdempotencyKeywrites the key hash,turns.createwrites the record — so a holder stalled between the two was indistinguishable fromone whose record had expired. The stepover then released a live claim, the second claim won, and
both submissions created and enqueued a turn for one idempotency key.
On an ordinary key that is two runs of the same envelope. On a gate key it is two resumes carrying
the same decision, and the second leaf finds the gate already decided and re-derives the same
continuation (
decideSeed's no-pending-gate branch), so one human approval ran twice — doublespend, double side effects. A human decision and the deadline sweep race on that key by design
(#393 §3), which made this a regular path rather than a client-retry oddity.
The fix
Option 1 from the issue, which is also the upgrade
claimKey's ownshortcut:note prescribed: anunreadable holder is treated as live for
CLAIM_GRACE_MS(10 s) and stepped over after it. Thegrace covers the only window that is actually narrow — the round trip between a claim and its create
— so a holder mid-create reads as live and no second turn is created for its key, while a holder
that crashed in that window, or whose record expired, still frees the key.
Treating an unreadable holder as live without an age was never an option: the default key is the
session id, so a crash between a claim and its create would wedge every later turn of that session
with no self-heal. That is acceptance item 2, and it has its own test.
The age comes from one new store method,
TurnStore.claimedAtOr(owner, key, held, now)— an HSETNXplus a read on the hash the claim already is, so no schema migration. Two deliberate choices:
claimIdempotencyKeykeeps its single round trip on thepath every submission takes, and
claimedAtOris called only on the unreadable-holder branch. Thecost is that an orphaned claim frees a grace after the first duplicate attempt rather than a
grace after the crash. It still frees, and it never frees early — the side that would hand a live
turn's key to a second submission.
claimedAt:<turnId>). Reading my own diff turned up thehazard: a holder that releases its key between the caller's read of its record and the stamp
leaves a holderless hash that the next claim adopts, and one shared
claimedAtwould then age thenew holder from the old one's stamp — a reader past the grace would step over a claim made moments
ago, re-admitting the exact bug this fixes. A per-holder field cannot be misattributed; a stale one
is a few dead bytes until the key's release.
Not done: the TTL (option 2) and record-before-claim (option 3), for the reasons the issue gives. No
env knob for the grace — its only visible effect is how long a duplicate submission is answered with
an id that may not have materialised yet. No change to
releaseIdempotencyKeyIf's compare or to the§4.3 protocol.
Visible behaviour change
On
POST /v1/sessions/{id}/decision, a second decision racing a winner that is still being creatednow answers
409 gate_not_pendinginstead of 202 with a duplicate resume. The control plane cannotsee which decision won, so a 202 there could report an approval as accepted when an abort is what
runs; the retry replays normally once the winner's record lands. Stated in
docs/api/openapi.yamland in the fan-out design §4.3, which also now records the 10 s grace and that a deduplicated 202
inside it can name a turn whose
GET404s briefly.Tests
The issue's three acceptance items, driven through the routes rather than by calling
claimKey:submitTurn: a key held by a turn with no record creates nothing inside the grace — the holder'sid is returned, no record, nothing enqueued, and the reserved quota slot goes back.
submitTurn: the same state past the grace is stepped over and a new turn is created (the orphanself-heal, so the default session key cannot wedge).
decideGate: a gate key held by a turn still being created fans out no second resume.decideGate: an orphaned claim past the grace lets the decision resume normally.turn-store-contract:claimedAtOrstamps once, reports that same instant to later readers,keeps a separate clock per holder, and does not claim the key it stamps.
Both grace tests were re-run with the new branch disabled and both fail, so neither passes
vacuously. The two past-grace tests pin behaviour that already worked, as regression guards.
Verification
packages/control-plane: 2253 passed, 4 skipped, EXIT 0.make typecheckEXIT 0, zero error lines.make check-linksEXIT 0.make lint: every hook passes except hadolint, which cannot reach a Docker daemon in thisenvironment; no Dockerfile is touched.
claimedAtOris proven against thefake here; its only Redis-specific surface is a colon in a field name and string values.
Known limit
shortcut:in the code — a claimant that stalls between its claim and its create for longer thanthe grace is still stepped over. Telling that apart from a crash needs lease renewal, which §5.1's
no-Lua/WATCH/MULTI rule forbids today; the issue accepts the same residual under option 1.
Closes #989
Assisted-By: Claude Code