Repository navigation
feat(control-plane): async turn submission and turn records (#387) - #704
Conversation
The pure half of the async turn record (async fan-out spec §5.1, §4.1): the nine states with `queued`/`running` as the only non-terminal pair, owner-hashed keys, and body validation for the three leaf kinds. No Redis and no HTTP yet. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Spec §10's parity table keeps all three async leaf kinds, including the explicit spelling `converge` for the default verdict leaf -- runLeaf already treats an absent `kind` and `kind: 'converge'` identically (harness/src/run-leaf.ts). The parser required `kind === undefined`, so a caller spelling it out (as rossoctl#390's fan-out orchestrator may) got 400 envelope_invalid instead of 202. Both spellings now parse to the same internal `kind: 'verdict'` discriminant and the same stored envelope (`{ item }`, no `kind` field): the envelope normalises to the absent form so the turn record keeps one representation instead of two that mean the same thing. `kind: 'verdict'` itself stays refused -- it is the internal discriminant, never a wire value. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
The async turn record's only writer (async fan-out spec §5.1): a non-terminal record carries no TTL and gets `LEAF_RESULT_TTL_SECONDS` plus a margin at its terminal transition, a per-owner OPEN set the fan-out quota counts with one ZCARD, and an HSETNX idempotency claim that returns the first turn's id to a resubmission. `CpRedisLike` gains `hSetNX`, `expire` and `zCard`. One implementation serves both backings; test/helpers/turn-store-contract.ts runs it against the in-memory fake and against Redis on 6379. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ontract The contract suite exercised TurnStore's TTL ordering (expire only at a terminal transition) without ever asserting it, against either backing -- a refactor that moved expire into create() would have kept the whole suite green. MakeTurnStore now also yields resultTtlSeconds/ttlMarginSeconds and a ttlOf(turnId) observer (the fake's recorded `expires`, or a real TTL call keyed the same way the store writes it), and two new cases pin: a queued/running record carries no TTL at all, and done/cancelled get exactly resultTtlSeconds + ttlMarginSeconds (within a small band on the real-Redis backing, to tolerate clock drift between EXPIRE and TTL). Also drops `expect(now).toBeGreaterThan(0)`, a leftover assertion that proved nothing about the code under test. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
The submitter's whole interface to the queue (async fan-out spec §5.1): enqueue(turnId) and nothing else, so no envelope, credential or config can reach the stream and everything authoritative stays in the turn record for §5.4's dequeue-time resolution. Stream `leaf-queue` and group `leaf-workers` are exported constants -- the names rossoctl#389's restored RedisWorkQueue reads, where a mismatch would enqueue successfully and never drain. MemoryTurnQueue exists so a test can assert queue DEPTH, which §8 names as the assertion for a refused submission. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ncel
POST /v1/sessions/{id}/turns answers 202 with the turn id alone, GET reads state and
attempts from the record plus the result once written, DELETE cancels a queued turn and
409s anything else (async fan-out spec §4.1, §4.4, §4.5).
Submission order is specified rather than incidental: ownership, shape, the workloadId
501, the MOCA_TENANCY=single gate, the per-owner quota, idempotency, then create-and-
enqueue. The quota is checked pre-enqueue so a refusal leaves nothing behind, and a
failed enqueue finalizes the record rather than leaving a queued turn nothing will claim.
`sessionScoped: true` is route-table data the router never reads, so each handler calls
assertOwner first -- which is also what the authz enumeration sweep requires.
tenancy.ts moves into this package: knative-server already depends on it, and two copies
of isTenancyNearMiss would be two near-miss policies.
Refs rossoctl#387
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…ult on terminal Two submissions could both read the same terminal holder of one idempotency key: the first released, re-claimed and created its record, and the second then deleted that LIVE claim and created a second record and a second queue entry -- the duplicate fan-out idempotency exists to prevent (async fan-out spec §4.3). The release is now conditional on the stale holder actually read (TurnStore.releaseIdempotencyKeyIf), so the loser's release is a no-op, its second claim loses too, and it returns the winner's turn id. getTurn attaches `result` only once the turn is terminal. The result key is per session and shared with the synchronous path, so a session that ran an interactive turn and then submitted an async one reported `queued` beside the PREVIOUS turn's result, which a caller polling for completion would read as this turn's (§4.4). Three tests that could not fail are now able to: the failed-enqueue compensation asserts the `failed` state and the released key directly on the keyspace, rather than inferring both from a retry that succeeds either way; the submission audit asserts the turn id in the audit STREAM, which needed turnDeps to stop pointing `streams` at a different fake than its own `index` writes to; and the quota message assertion now discriminates the count from the limit. Drops the unused envelopeOf export. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
configFromEnv reads MOCA_ASYNC_QUEUED_PER_OWNER (default 50), MOCA_TENANCY (default single) and LEAF_RESULT_TTL_SECONDS, and depsFromEnv builds the TurnStore and the queue from the existing client -- no new connection, URL or secret. One boot contract genuinely changes: the control plane now calls readTenancy, which throws on a NEAR-MISS NAME, so a control-plane env carrying a misspelled tenancy switch no longer boots. That is the contract the worker has had, and a tenancy switch silently ignored is worse than one that fails loudly; the env example says so in full. The quota gets its own countEnv rather than intEnv, because 0 is meaningful here -- an operator writing 0 means "no async on this deployment", and falling back to 50 would be the opposite of the ask. Both variables are optional, so no unit, setup.sh or installer changes; compose and k8s pass them through, k8s with optional: true. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
POST /v1/sessions/{id}/turns, GET and DELETE on {turnId}, a turnId path parameter, a
TurnStatus schema, and the six error codes Tasks 1 and 4 added to CP_ERROR_CODES.
No new test: openapi-contract.test.ts already compares the document against the route
table in BOTH directions and the Error enum against CP_ERROR_CODES by set equality, and
mocactl's contract suite compares it against the client's actual calls. A third
hand-written assertion would be a third thing to keep in sync.
The descriptions carry the two things a client gets wrong unaided: idempotencyKey
defaults to the session id (so a fan-out is N sessions, not N turns), and `attempts` is
descriptive -- the queue's delivery count is the only retry-exhaustion authority.
Refs rossoctl#387
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The shared router reads the body before the handler runs (server.ts:126-139) and throws invalid_json for both malformed and EMPTY bodies, since this route does not set bodyRequired: false. The response said the route could only answer invalid_request or envelope_invalid, so a client sending no body got a code the document denied existed. createSandbox already documents the same three-way 400; this matches it. getTurn and cancelTurn are deliberately unchanged: GET and DELETE skip the body block, so invalid_json is unreachable there and listing it would be a new inaccuracy. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ancel submitTurn, getTurn and cancelTurn on ControlPlaneClient, with the request and status types transcribed from openapi.yaml -- mocactl declares no @moca/* dependency (layering.test.ts), so the contract suite against the document is what keeps the two copies honest. Types and client only: no CLI command. What a `mocactl turn` subcommand should print while polling, whether it blocks, and what a failed turn's exit code is are a UX design nothing in rossoctl#387 or ADR-0047 decides. The client is what the orchestrator (rossoctl#390) needs, and it is useful the moment it exists. ControlPlaneApi.cancelTurn and HarnessApi.cancelTurn are different operations and both keep their names: the harness interrupts a streaming turn over its own connection, this removes a QUEUED turn from the queue. That neither can do the other's job is exactly why DELETE answers 409 for a running async turn. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…e field
The refusal message now names its replacement -- POST /v1/sessions/{id}/turns with
async:true -- instead of dead-ending at "it was removed" (ADR-0047 §4.2, verbatim). The
route itself stays removed permanently: it is unauthenticated when SH_REQUIRE_AUTH is
off, which would be a second trust model for one queue.
http-api.md, leaf-and-envelope.md and dispatch-archetypes.md say what is actually true
now: submission is implemented, the drain loop (rossoctl#389) is not, so a submitted turn is
recorded and queued and runs once the consumer ships. Writing "implemented" unqualified
would send callers to a route that accepts their work and leaves it sitting.
Deletes LeafEnvelope.async?: boolean, whose comment still claimed "the HTTP layer
enqueues instead of running inline" -- nothing reads it (the refusal tests the raw parsed
body), and a field that lies about itself invites someone to wire to it.
Refs rossoctl#387
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…fusals turn-e2e.test.ts submits over real HTTP with a signed token, drains with a fake worker against a real Redis consumer group, and reads the result back. Its load-bearing assertion is that the stream entry's field set is exactly ['turnId']: everything the worker used came from the record, which is the contract rossoctl#389's drain loop must honour. A fake queue on both sides would only prove the fake is self-consistent. Also covers the §5.1 TTL invariant against a real key lifetime -- TTL -1 while queued, 86400 + 3600 after, where the unit contract can only see that expire() was CALLED -- the fan-out shape (three leaves are three sessions, because the idempotency key defaults to the session id), the resubmission that must not create WORK rather than merely answering the same id, cancel leaving the stream entry in place while flipping the record, and the quota refusing over the wire without growing the stream. two-subject.test.ts gains the three cross-subject cases: alice cannot submit on bob's session, her read of bob's turn is byte-identical to her read of an unknown one, and her DELETE neither succeeds nor cancels -- a 404 that still cancelled would be a denial of service dressed as an authorization failure. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
… near-miss scan packages/control-plane/test/main.test.ts names MOCA_TENANCEY deliberately, in a boot test asserting a misspelled variable is refused rather than ignored. The repo-wide near-miss scan flagged that fixture as if it were a real variable name. Excluding the file is right because the name is a fixture; the assertion itself stays untouched, since a false positive on a real variable would crashloop a correctly configured deployment. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…s and the VM The turn record's TTL is derived from this value plus a 1 h margin, so the record always outlives the result it explains (spec §5.1). Only the compose stack passed it: on k8s and the VM an operator raising the retention moved the worker's results but not the records, inverting the invariant for exactly the deployments where retention gets tuned. Both entries are optional/commented like their neighbours, so an existing moca-settings or env file still boots and unset still means 86400. Refs rossoctl#387 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ition
TurnStore.releaseIdempotencyKey's own doc comment claimed the key was
"released when the turn goes terminal", but nothing called it from
finalize() or cancel() -- the only two authors of a terminal state. The
key (sh:cp:turnidem:<owner>:<key>) was written at submission and then
kept forever with no TTL, since the two actual release call sites
(claimKey's lazy step-over, and the enqueue-failure compensation) only
ever fire conditionally. Verified against real Redis: a turn finalized
with `claim -> create -> markRunning -> finalize('done')` left the key
present with TTL -1 while the turn record correctly expired at
resultTtl+margin -- an unbounded, unexpiring keyspace with no reaper.
Release it inside toTerminal, the single choke point both finalize()
and cancel() already route through, using the COMPARE release
(releaseIdempotencyKeyIf) rather than a blind del: a newer submission
may have re-claimed the key by the time this turn goes terminal, and a
blind delete would remove that live claim instead of this turn's own.
Placed between the state write and the open-set removal, preserving
toTerminal's existing record-first/open-set-second/TTL-last order (the
TTL stays the only irreversible step).
Added a TurnStore-contract assertion (runs against both the in-memory
fake and real Redis) that a resubmission after a turn reaches terminal
gets a brand-new turn id rather than the key still pointing at the
finished one.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The final whole-branch review deleted `if (rec.tombstone) throw
new CpError('session_not_found', ...)` from submitTurn and the entire
1115-case control-plane suite stayed byte-identical green -- the guard
was correct but unpinned, so a future refactor could drop it silently.
It matters more once a deleted session's turn can leak (see the F2
commit): accepting a submission after tombstone would create exactly
the kind of record nothing can ever collect.
Verified RED: removing the guard failed only this new test (1 of 29),
nothing else. Restored.
Left getTurn and cancelTurn alone, per the review's own note that the
asymmetry there is a behavioural question the spec doesn't settle, not
a defect to fix in this pass.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…I contract The final whole-branch review dropped `lost` from TurnStatus.state's enum in openapi.yaml and both contract suites (40/40 mocactl, 15/15 control-plane) stayed green. Nothing mechanical kept the document's nine-state list in step with the implementation's: mocactl hand-transcribes AsyncTurnState (layering.test.ts forbids it importing control-plane types), so the OpenAPI document was the only place a drift between the two nine-state lists could have been caught, and it wasn't checking. Added a set-equality assertion against TURN_STATES, mirroring the existing Error.properties.error.enum <-> CP_ERROR_CODES check in the same file (same shape, same reasoning: the implementation's own list, not a second hardcoded copy). Verified RED: dropping `lost` from the yaml failed only this new test. Restored. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…quota slots deleteSession's cascadeDelete touched session data, the runtime hash, the owner sessions zset and the session key, but never the owner TURNS zset or the turn record itself. A queued or running turn whose session was deleted kept its record (correct per §5.1, since it's non-terminal) and kept its member in the owner's open set, so it went on counting against the per-owner quota forever -- nothing else in this branch can ever move it to terminal once its session is gone. Verified against the fake with asyncQueuedPerOwner: 1: submit, delete the session, submit again on a fresh session -> refused 429, with the turn record still present and countOpen still 1. Added TurnStore.deleteSessionTurns(sessionId, owner), called from deleteSession after cascadeDelete. The cleanup lives on TurnStore rather than as a dataKeys entry in ownership.ts because a turn key is derived from a turnId, not a sessionId, and a session may have had several turns over its life -- OwnershipIndex would have to restate TurnStore's own key derivation to express it, which this project rules against (see the leafResultKey precedent). `deps.turns` is optional (absent on the sandbox profile, which mounts no turn routes), so the call is optional-chained. Added a handler-level test with the per-owner limit set to 1: submit, delete the session, submit on a fresh session, expect 202 rather than 429. Verified RED by removing the deleteSessionTurns call; restored. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
CodeQL flagged js/polynomial-redos (high) on the Kubernetes service-link exemption in isTenancyNearMiss. The regex predates this branch (63a584b, 2026-09-28); Task 4 moved tenancy.ts from knative-server into control-plane, so CodeQL analysed it under a path it considers new. The alert is real, not a false positive. `SERVICE_PORT(_[A-Z0-9_]+)?$` trailing an alternation whose own literal is all `[A-Z0-9_]` lets the engine split a name that repeats `_SERVICE_PORT` quadratically many ways: 4x the input took ~16x the time, and an 832 KB name took 70 s. Split the named-port shape out into a string lastIndexOf plus an anchored single-quantifier test. Every quantifier that remains in the regex runs over a character set its neighbours cannot match. The exemption's behaviour is unchanged -- the six service-link fixtures still pass. readTenancy's input is environment-variable names an operator sets, not request data, so this was never request-reachable; it is fixed rather than dismissed because the fix is small and the quadratic is genuine. Mutation-verified: restoring the old regex fails the new test in 7.3 s. knative-server 438/438, control-plane 1120 passed / 3 skipped, typecheck clean. Refs rossoctl#387, rossoctl#686 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…key release Three findings from a senior-developer review of this branch, each reproduced by a probe before being fixed. 1. The per-owner fan-out quota was not atomic. submitTurn read countOpen and then compared it, so every submission of a parallel batch read the same under-limit count before any other had written anything and all of them passed: against real Redis, 100 concurrent submissions were ALL accepted with the limit at 5, while the same code run sequentially accepted exactly 5 of 20. This quota is the only containment spec §4.3 has for the unbounded fan-out §3 assumes a submitter is misbehaving about, so a 429 that does not hold under concurrency is no containment at all. The quota is now decided by the write. TurnStore.reserveOpenSlot ZADDs the candidate turn id into the per-owner open zset and then ZCARDs it, so the count a submission reads includes itself and only one of an over-limit batch can be under the limit; releaseOpenSlot gives the slot back on the two paths that never create a record (the refusal, and a deduplicated resubmission). Single commands on one key, so parallel callers serialize in Redis rather than in the handler -- no new CpRedisLike verb, and no Lua (§5.1). A burst can now refuse a whole batch, since all of them write before any of them read. "Never more than the limit" is the invariant and is asserted; "exactly the limit" is not promised. That direction is the safe one: a refused caller retries and is admitted, whereas an over-admitted turn has already fanned out. 2. The enqueue-failure compensation released the idempotency key blindly, and this PR's own F1 fix is what made that unsafe: finalize's terminal transition already releases the key, so a resubmission can find the turn terminal, step over it (claimKey's stepover) and claim the key for its own live turn in between -- and the blind del then deletes THAT claim, so the next submission wins the freed key outright and fans out a second turn for one key, the duplicate §4.3 exists to prevent. The comment asserting this call site was the safe one for a blind release stayed behind when F1 landed. It compares now. releaseIdempotencyKey is deleted outright: with this call site converted, no caller can know it still holds the claim, which is the only precondition under which a blind delete is sound. One release verb. 3. getTurn reported a result for a cancelled turn. It gated the result on isTerminalState alone, but §4.5 defines `cancelled` as withdrawing a turn that was still `queued` -- it is never reached from `running`, so no leaf ever ran and nothing was ever written for it. The result key is per SESSION and shared with the synchronous path, so a cancelled turn handed back whatever the session's previous interactive turn had left there: the same stale-result conflation the code already refuses for `queued`, on the one terminal state it does not apply to. Mutation-verified, six mutations and six reds: read-then-check in the handler accepted all 12 of a burst against a limit of 3; the same inside the store admitted 40 of 40 against a limit of 5 on REAL Redis; dropping the dedup-path slot release let five retries of one 202 exhaust a quota of 2; dropping the refusal-path release burned 12 slots on turns that never existed; restoring the blind release wiped a newer live claim; dropping the `cancelled` exclusion put the previous turn's result back in the body. The real-Redis contract case is deliberate -- finding 1 was proven on real Redis, and a fake whose concurrency is one event loop is not where that invariant has to hold. control-plane 1128 passed / 3 skipped, knative-server 438/438, typecheck clean. Refs rossoctl#387, rossoctl#686 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Reviewed at b58b513. This adds the control-plane half of async fan-out (#387): POST/GET/DELETE /v1/sessions/{id}/turns, a Redis turn record with the §5.1 TTL invariant, an owner-scoped idempotency claim, a per-owner quota decided by a write, and a queue port that can only XADD a turn id. The design is careful. Compare-and-release is used everywhere, the cancelled state never surfaces a stale result, and session delete now reclaims open turns. Tests cover both the in-memory and real-Redis backings.
No blocking issues. Two suggestions inline: (1) a caller-chosen idempotencyKey is owner-wide, so reusing it on a second session dedupes onto the first session's turn and returns a turn id that 404s on that session; (2) a reserved quota slot is never released if a later Redis step throws, so a transient 503 can burn a slot permanently, the same class as F2. Plus one nit on a misleading comment about parsing LEAF_RESULT_TTL_SECONDS.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, knative-server, mocactl), K8s/compose/VM deploy config, OpenAPI + docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 21 commits, all signed-off: yes
CI status: passing (all 17 checks green, including k8s-kind-e2e)
| } | ||
|
|
||
| const idempotencyKey = parsed.idempotencyKey ?? rec.sessionId; | ||
| const claim = await claimKey(turns, rec.owner, idempotencyKey, candidate); |
There was a problem hiding this comment.
suggestion — A caller-chosen idempotencyKey is scoped to the owner, not the session (idempotencyKeyKey(owner, key)). If one key is reused on two sessions, the second POST /v1/sessions/B/turns dedupes onto session A's live turn. It returns 202 {sessionId: "B", turnId: <A's turn>} and enqueues nothing for B. The caller's next GET /v1/sessions/B/turns/<that id> then answers 404, because turnOnSession checks turn.sessionId === rec.sessionId. B's work is silently never queued, and the turn id the server gave back can't be polled.
The default key (the session id) can't hit this. A client that uses one key per logical job across retries, or a constant key, can. Two fixes would work: include the session in the key (idempotencyKeyKey(owner, sessionId, key)), or treat a holder on a different session as a conflict (409) rather than a dedupe. A test with the same key on two sessions would pin whichever behaviour you pick. If owner-wide keys are intended, the spec and OpenAPI should say so, and the 202 shouldn't claim sessionId: B for A's turn.
| // `reserveOpenSlot` writes first and counts after, so the count a submission sees includes | ||
| // itself and only one of any over-limit batch can be under the limit. | ||
| const candidate = `t-${deps.newId()}`; | ||
| const held = await turns.reserveOpenSlot(rec.owner, candidate, deps.now()); |
There was a problem hiding this comment.
suggestion — Nothing releases the reserved slot if a later step throws. If claimKey (HSETNX/HGETALL/DEL) or turns.create raises redis_unavailable after this line, or the process dies before create/releaseOpenSlot, the candidate stays in sh:cp:owner:<h>:turns with no hash. countOpen is a bare ZCARD, so that member counts against the quota forever. This is the same "slot burned for the deployment's lifetime" class as F2, reached through a transient Redis blip instead of a session delete. deleteSessionTurns can't reclaim it either, because get() returns null and the loop continues.
Two options: wrap everything from reserveOpenSlot to create in a try { … } catch { await turns.releaseOpenSlot(...).catch(() => {}); throw }, which covers the 503 case. You could also have deleteSessionTurns (or an occasional prune) zRem members whose hash is missing and whose score is older than some bound, which covers the crash case. Minor related point: concurrent dedup retries of one live turn each hold a slot briefly, so near the limit a retry storm can produce spurious 429s for other sessions. That's acceptable, but worth a line in the doc comment.
|
|
||
| function turnRecordTtlFromEnv(env: NodeJS.ProcessEnv): number { | ||
| // Matches server.ts:49's parseInt of the same variable: one deployment, one meaning. | ||
| const result = countEnv(env, 'LEAF_RESULT_TTL_SECONDS', 86_400); |
There was a problem hiding this comment.
nit — The comment says this "matches server.ts:49's parseInt of the same variable", but it doesn't. countEnv refuses anything that isn't ^(0|[1-9][0-9]*)$, while knative-server's parseInt('86400s', 10) accepts 86400s, 86400 and 86400.5. One shared moca-settings value can therefore boot the worker and crash-loop the control plane. Strict is the better behaviour, so I'd fix the comment rather than the code. Better still, make the worker strict too in a follow-up so both processes refuse the same values.
Sixteen ADRs still said Proposed although their decisions are in code on main. Each status line now names the merged PRs that implemented it and the date the core landed (format of ADR-0042), and notes what is still owed where only part is built: - 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041) - 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225) - 0032 (rossoctl#249, rossoctl#350, as amended by MI1) - 0035 (rossoctl#251; ADR-0048 adds lease mode beside it) - 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481) - 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620) - 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed) - 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed) - 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the security review's lease sections are signed off) The README index follows, and its 0033 row, which still said Proposed after rossoctl#249 accepted the ADR, is corrected. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Implements #387 — the control-plane half of P6.4 async fan-out
(spec §4.1–4.5, §5.1, §5.4, §6.4, §7, §9;
ADR-0047).
Three authenticated routes let a caller submit a turn that is queued rather than run inline,
poll its state, and cancel it while queued:
POST /v1/sessions/{id}/turns202 {sessionId, turnId}GET /v1/sessions/{id}/turns/{turnId}200 {turnId, state, attempts, result?}DELETE /v1/sessions/{id}/turns/{turnId}202|409Nine states:
queued → running → paused \| responded \| done \| solved \| failed \| cancelled \| lost.This is the submission half only. The consumer that drains the queue is #389 and does not
exist yet — so a submitted turn stays
queueduntil that lands. The asymmetry is deliberate, andthe docs say so in both halves rather than implying a working pipeline.
Design points worth a reviewer's attention
credentialNameis a name, resolved against the owner's credentials at dequeue, never carried.Pinned by a set-equality assertion on the stream entry's fields, at unit level and again
end-to-end against a real stream.
xAddand no read verb, soclaim/ack/touch/ensureGroupare unreachable by construction rather than by convention —a submitter that can claim is a submitter that can be mistaken for a worker.
the terminal transition, to
LEAF_RESULT_TTL_SECONDS+ 1 h, so a record always outlives theresult it explains. A record that expired while queued would be a turn that silently vanished.
idempotencyKeydefaults to the session id (§4.3), so a session holds at most one async turnin flight and a resubmission is deduplicated rather than queued behind. A fan-out of N leaves is
therefore N sessions.
because a 403 is an existence oracle.
cancelledis never reachable fromrunning(§4.5). Interrupting a running async turn needsa signal addressed to the single worker holding it, which does not exist; interactive cancel
rides the turn's own connection and an async turn has none.
import. The duplication is the rule's price; the OpenAPI contract suite is what keeps the copies
honest.
Review findings fixed in this PR
A whole-branch review found two defects that per-task review missed, both because they only bite
once a consumer exists:
095db973). The recordexpired at 90,000 s while the key pointing at it had no TTL and no collector — an unbounded
keyspace nothing would ever delete. It was also reachable today, not only via Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389, since
DELETE → cancel()is a terminal transition. Released now attoTerminal, the single chokepoint for both
finalize()andcancel(), using the compare-release: a blind delete woulddrop a key a newer submission had already re-claimed.
34ebaa2f).The quota counts members of the owner's turns zset, which the cascade never touched; with the
orphaned record unable to reach terminal, submit-then-delete enough times wedged async submission
for the deployment's life, with no record visible to explain why.
leaf:result:was cascadedwhile the record was not, so the record outlived the result it pointed at — the inverse of §5.1.
Both fixes are mutation-verified: removing the key release turns the store contract red on both
backings (in-memory fake and real Redis), and removing the session cleanup fails exactly the
quota-reclamation test. Two unpinned assertions were also closed (
ddbd6fd2,0b43a0fd) aftermutation showed the suite stayed green without them, and
LEAF_RESULT_TTL_SECONDSnow reaches thek8s and VM deployments, not just compose (
0aaf37d5) — raising retention on the worker alone hadinverted the TTL invariant for exactly the deployments where retention gets tuned.
Testing
and supervisor — all green.
of Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389's drain loop; it is the minimum that proves the contract between the two halves — that a
consumer holding only what the queue carries can rebuild everything it needs. A fake on both
sides would prove only that the fake is self-consistent.
Two pre-existing macOS-only failures are outside this change and left alone: harness
context-overlayand provisionerseed(8 cases), bothmkdtempSync(tmpdir())+mvpermissionerrors under
/var/folders. The provisioner suite's last change predates this branch's base commit.Carried into #389
getTurn/cancelTurncarry no tombstone guard whilesubmitTurndoes — the spec does notsettle whether they should.
shadows it in the cross-subject cases.
leafResultKeyis defined in both the control plane and the harness (forced: the control planedeclares no harness dependency). The real risk is not the duplicated name but a sanitization
divergence — the harness writes under a possibly tenant-prefixed, sanitized id while
getTurnreads the raw one. They agree only because session ids are UUIDs and an authenticated request
cannot name a tenant.
losthas exactly one intended author: the reaper.Refs #387, #686
Assisted-By: Claude Code