Repository navigation
Closed
Labels
enhancementNew feature or request
Milestone
Description
Part of the Coding-agent subagents epic (#378). Item B3, milestone B-M1. Depends on B2 (#387) and MI1 S2, or the interim that B1 (#386) chooses.
Goal
When a worker takes an async turn off the queue, it gets that turn's inference and sandbox grants from the control plane, minted from the turn record. No caller bearer token is ever stored in the queue (MI1 §6.5).
Current state (verified on main @ 24c6f5e)
- Today's exchange: the worker presents the caller's session token plus
SH_EXCHANGE_TOKENtoPOST /internal/credentials(packages/control-plane/src/exchange.ts). In direct mode on the VM it gets the user's real secret back. - MI1 S2 (Proposed) replaces this with
POST /internal/turn-grantsand/internal/grants/refresh(§6.2), withturn_expas an absolute cap (§6.1). - A queued turn has no session token when it is dequeued. That's the problem §6.5 describes.
Scope
- A dequeue-time exchange: the worker presents the turn record id plus
SH_EXCHANGE_TOKEN, and the control plane checks the record's state, owner, tombstone and deadline, then mints the grants. - Refresh up to
turn_exp, with the long-turn policy from Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386. - Before S2: the interim Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386 chooses (for example, the credential resolved from the record,
MOCA_TENANCY=singleonly), flagged in code and docs as interim, with a test that refuses it undermulti.
M2 remainder (this issue, after the M1 interim landed in #713)
- Both audiences' grants (MI1 §6.1), replacing the M1 interim's resolved-credential return value.
-
turn_expand refresh, with Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386's long-turn policy. Already settled in spec §5.4:turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), clamped at mint, with turn start meaning dequeue and not enqueue. - The tenancy gate lifts, in both places that hold it:
turn-handlers.ts(submission) and the dequeue check inturn-exchange.ts. ADR-0047 records it as a dated conditional refusal whose lifting criterion is exactly the two items above. - Pin
modelandsandboxTierto the turn record. Today the dequeue exchange reads both from the LIVE session whilecredentialNameandcfgcome from the record (spec §5.1 copies only what a turn must spend unchanged). So aPATCH /v1/sessions/{id}between submission and dequeue moves an already-queued turn onto the new model — andupdateSession's own "a turn in flight keeps its model" does not cover it, because an async turn's exchange can be an hour after its submission. Pinning means adding both fields to the record, which is why it is M2 and not a different read. Raised in feat(control-plane): resolve an async turn's credential at dequeue (#388 M1) #713 review; the user-facing caveat is documented in fix(control-plane): #713 review follow-ups — correct the refusal docs, bound the dequeue turn id #714.
Acceptance
- A test reading the stream proves no bearer token is ever in the queue.
- A tombstoned session's queued turn is refused at dequeue.
- Refresh is refused after
turn_exp. - The interim path is refused under
multi. - A turn queued before a
PATCHthat switches the session's model still runs on the model it was submitted with.
References
- MI1 §6.1, §6.2, §6.5, §6.6; ADR-0032, ADR-0033
Working conventions (for a fresh session)
- Workspace:
git fetch, then create a worktree fromrossoctl/main(never localmain), under.worktrees/. Populate and buildpi-fork(git submodule update --init --recursive && cd pi-fork && npm ci && npm run build), thenpnpm install. A worktree without the pi-fork build does not typecheck. - Plans: write the plan with
superpowers:writing-plansintodocs/plans/<date>-<slug>.md. Plans are gitignored and never committed. Write it in chunks, one append per task. - Pre-flight table: list every process entrypoint, systemd unit, env example and shell/Go launcher whose boot contract changes, not only TypeScript call sites.
- Tests: Redis on 6379 must be up. Use each package's own
node_modules/.bin/vitest. vitest can exit non-zero with every test green, so grep the log forErrors. Redirect long output to/tmp/kagenti/....make lintskips untracked files. - Commits:
git commit -swithAssisted-By: Claude (Anthropic AI) <[email protected]>, neverCo-Authored-By. - Shared KVM rig: alert the owner before using it, record a manifest of what you install, and verify cleanup.
- Don't push or open PRs without the owner's go-ahead.
Metadata
Metadata
Assignees
Labels
enhancementNew feature or request
Activity
[-]Claude Code subagents B3: grants minted at dequeue from the turn record (no bearer in the queue)[/-][+]Coding-agent subagents B3: grants minted at dequeue from the turn record (no bearer in the queue)[/+]docs: design the P6 async fan-out replacement (#686, #386)
docs: answer #386 items 2 and 5 as written, not as paraphrased
cwiklik commentedon Nov 6, 2026
Design landed, and it makes this issue bigger than its body reads. #386 closed with
docs/specs/2026-11-05-p6-async-fan-out-design.md§5.4 and ADR-0047 (#696, merged316056a7). Posting the decisions per the spec's §12 obligation.The finding that resizes this issue:
turn_expdoes not exist in code. Scope item 2 above ("refresh up toturn_exp") and #386 item 5 both read like a policy to tune on an existing field. MI1 §6.1 specifies it — "an absolute cap: turn start +MOCA_TURN_MAX_S", withexp = min(now + MOCA_GRANT_TTL_S, turn_exp)andMOCA_TURN_MAX_Sdefaulting to 1800 — but no TypeScript in the repo implements it.grep -rn 'turn_exp\|turnExp' packages harnessreturns nothing outside docs. Expiry today is alwaysexp = iat + ttlSeconds, clamped only for sandbox tokens by the resource's ownexpiresAt. So this issue has to buildturn_exp, not configure it, and that is where §9's M1/M2 split comes from: M1 ships without it underMOCA_TENANCY=single, and M2 is gated behind it.Building it is discharging MI1 S2's own spec rather than adding to it — worth stating so the two are not designed twice.
"Turn start" is dequeue, not enqueue. A leaf that waits an hour in the queue must still get its full
MOCA_TURN_MAX_S, and a grant minted at enqueue would already be expired on arrival. §5.4 flags this as a semantic MI1 §6.1 does not currently pin down — a correction S2 needs regardless of async fan-out.The mint sequence (§5.4), for scope item 1:
turnId(plus its own identity /SH_EXCHANGE_TOKEN).cancelledor already terminal, resolvescredentialNameagainst the owner'sSubjectDocument, and mints an inference grant and a sandbox grant —aud: moca-inference/moca-sandbox, claim sets per MI1 §6.1's table.state → runningas a compare-and-set fromqueued; a record alreadyrunningis a redelivery and staysrunning.attemptsis written from the entry'sdeliveryCount.runLeafwith the grants.Step 2's check is "not terminal", not "
queued" — this is the subtle one. A narrower check defeats goal 3 in exactly the case it exists for. Step 3 setsrunningon the first claim, so every redelivery arrives with the record alreadyrunning: a crash-reclaimed entry, a drained one, and aretryableoutcome thatprocessOnereturns without acking all look identical to the mint. Refusing those would ack and drop them — and because a non-terminal record carries no TTL (§5.1) and attempt exhaustion is the only author oflost, the record would be stranded inrunningforever with no entry left for the reaper to find. The mint refuses only a withdrawal (cancelled) and an already-terminal turn.It also must not test
attempts.deliveryCountis the single authority for exhaustion, checked byprocessOne's dead-letter branch before the mint is reached. Two counters that can disagree is the shape §5.1's heartbeat note rejects for liveness. The record'sattemptsis descriptive only.The long-turn policy (§5.4), which #386 item 5 asked for explicitly:
MOCA_TURN_MAX_Sstays the deployment-wide ceiling at its 1800 s default. Raising it would desynchronise it from its sibling worker deadlines and change every interactive turn too.turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S). Theminis the whole policy. A caller asking for more is clamped, not refused — refusing would make a client's cap request a deployment-coupling concern.MOCA_TURN_MAX_Sto 3600 is the supported route — auditable, deployment-wide. Note this is narrower than item 5's phrasing ("allows hour-long detached turns") implies, deliberately: letting an untrusted caller name its own expiry above the ceiling hands it control of how long its own credential lives.One question is left open and it is yours to close: whether refresh past
turn_expis refused outright (MI1 §6.2's current rule) or whether a leaf that is provably still running may extend once. §5.4 says refusing is the safe default and what M2 should ship; the §6.2 claim heartbeat is what a future extension would key off, since it already proves liveness. Pick one and record it.On scope item 3, the pre-S2 interim. §9 places M1 before S2 using exactly this interim — the credential resolved from the turn record at dequeue,
MOCA_TENANCY=singleonly, with async undermultirefused by name. The spec is explicit that the cost is a tenancy gate and that the gate must be a named refusal with a lifting criterion rather than silence, in the shape ADR-0041 used for its own deprecation window. This issue's acceptance criterion "the interim path is refused undermulti" is therefore M1-blocking, not M2.Unchanged and still correct in the body above: the current exchange (
exchange.ts, session token +SH_EXCHANGE_TOKEN→POST /internal/credentials), and that a queued turn has no session token at dequeue. Note the body says "verified onmain@ 24c6f5e", which predates #691 — but nothing in this issue's current-state section was changed by that removal.Acceptance gains one case from the design: a redelivered entry whose record already says
runningmust still mint. That is the failure this issue is most likely to ship with, since it only shows up after a crash or a drain.feat(control-plane): resolve a turn's credential at dequeue from its …
feat(control-plane): mount the dequeue exchange at POST /internal/tur…
test(control-plane): drain a turn through the real dequeue exchange
docs(api): document the dequeue exchange, and the version the turn ro…
Merge pull request #713 from cwiklik/feat/388-dequeue-credential-exch…
cwiklik commentedon Nov 10, 2026
The M1 interim slice of this issue has landed. #713 merged as
bb89a84e(6 commits,11da422d..1c6e1567, 17/17 checks). Scope item 3 and three of the four acceptance criteria above are discharged; items 1 and 2 are the M2 half, which §9.1 gates behind MI1 S2. Leaving this open as that tracker rather than closing and re-cutting, same as #387.What landed
POST /internal/turn-credentials,auth: 'exchange'(routes.ts:337). A worker that has just taken a turn id off the stream presents it plus the deployment-wideSH_EXCHANGE_TOKEN, and the control plane resolves the credential that turn spends from the turn record it wrote at the authenticated enqueue (turn-exchange.ts). MI1 §6.5's requirement is the whole reason the endpoint is shaped this way: no bearer token is ever stored in the queue, and at dequeue there is no session token left to present.Everything after deciding which subject and credential are in play is shared verbatim with the session exchange —
resolveInference,refuseMisdirectedSecret,placeholderFor,sessionTier— so an async turn spends exactly the credential an interactive one would, and an injector added to a deployment narrows what a worker holds on both paths.Six checks, each failing closed, in this order:
turn_not_found(404)turn_not_claimable(409)session_not_found(404)session_not_found(404)singleasync_tenancy_unsupported(501)resolveInference(record)Unknown-session and owner-mismatch answer identically, with nothing to distinguish them. Check 3's owner compare is load-bearing rather than belt-and-braces:
resolveInferencereadsownerandcredentialNameoff the record it is handed, so a record whose owner disagrees with its session's would otherwise be a request for whichever subject's credential it names. Check 5 runs before check 6 deliberately — a gate that fired afterwards would already have read a secret it is forbidden to return, andturn-exchange.test.ts:227pins that ordering by deleting the credential and asserting the answer stays the tenancy refusal.Three decisions worth recording, because none of them is obvious from the diff:
queued → runningstays with Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389's consumer, which already holdsdeliveryCount.SH_EXCHANGE_TOKENis one deployment-wide secret, so a write here would let every holder of it flip an arbitrary turn out ofqueued— and sincecancelacceptsqueuedonly, make a caller's own turn permanently uncancellable. No window opens by leaving it there:markRunningre-checks terminality itself, so aDELETElanding between the two calls is still refused.running, not justqueued(§5.4). The first claim writesrunning, so every redelivery — crash-reclaimed (§6.2), drained (§6.3), or aretryableoutcome left unacked — arrives on a record that already saysrunning. Refusing those would ack and drop exactly the entries crash recovery exists for.attemptsis never tested. The queue entry'sdeliveryCountis the single authority on exhaustion, checked by the consumer's dead-letter branch before it ever calls here. A second limit read off the record could only disagree with it, and would strand a turn the queue still intends to deliver.The audit write is deliberately not best-effort, unlike the submission routes'
auditBestEffort: those audit a write that already happened, so swallowing keeps a repair path open during an outage. Here the audit is the only record that a credential left the control plane, so a failed write refuses the credential rather than issuing one off the books. The entry carries the credential's name, never its value (§7.2), and the test asserts that against the whole stream rather than just the one entry.No boot contract changes: no new environment variable, no entrypoint, systemd unit, env example or launcher touched. The only caller arrives in #389.
Acceptance
turn-e2e.test.tsdrains a real stream entry and asserts its fields are exactly['turnId'], then runs the whole claim through the HTTP hop from that one field.turn-exchange.test.ts:191. This matters more here than on the interactive path: a tombstoned session's queue entries are still on the stream, so without check 4 aDELETE /v1/sessions/{id}would be followed by its leaves running anyway, each one spending the owner's credential.multi.turn-exchange.test.ts:214, by name. Asserted even thoughsubmitTurnalready refusesmulti— that refusal stops new submissions, while a deployment flipped tomultiwith entries already on the queue would otherwise drain them down the single-tenant path this gate exists to forbid.turn_expis left to M2. There is no grant to refresh.One gap found by review, after the tests were green
The post-merge review mutation-tested the new code — delete a line, run the suite, see whether anything fails — and found that removing
refuseMisdirectedSecret(resolved, …)fromexchangeTurnCredentialleft all 1152 control-plane tests green. The check is shared with the session exchange, so every test that covered it lived on the session path (exchange-auth-header.test.ts) and passed either way. That is the one failure on this path that costs a user their key rather than only failing the turn: in direct mode a rawsk-ant-…key would be sent to a gateway host that is notapi.anthropic.com(#368).1c6e1567adds the test on the async path specifically, verified load-bearing the same way: with the call removed, exactly one test fails and it is that one.touchBundleon this path is still uncovered — it is best-effort by design, so a silent no-op costs a bundle TTL refresh and not a turn.What is left here, and what gates it
Scope items 1 and 2, per §9.1's "M2 — requires S2 (grants, token endpoint)":
turn_expand refresh, with the long-turn policy from Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386. The policy is already settled in §5.4 —turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), clamped at mint, with turn start meaning dequeue and not enqueue.turn-handlers.ts:110(submission) and check 5 above (dequeue). ADR-0047 records it as a dated conditional refusal whose lifting criterion is exactly items 1 and 2.Two decisions handed to #389
Both are written down here rather than left to be rediscovered:
envelope. A worker needs one to run the leaf, and the e2e test'sfakeWorkergets it by callingturns.get(turnId)directly against Redis (turn-e2e.test.ts:183) — outside the HTTP hop. So this endpoint is not the complete claim handshake its own description implies. Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389 decides: eitherenvelopejoins the response, or the description says plainly that the worker reads the record directly.sandboxTierandmodelare read from the LIVE session, whilecredentialNameandcfgare pinned to the record. §5.1 copies onto the record only what a turn must spend unchanged, so the two it does not copy can only be read from the session as it is now. The consequence is real: aPATCH /v1/sessions/{id}between submission and dequeue moves an already-queued turn onto the new model.updateSession's own "a turn in flight keeps its model" does not cover it, because an async turn's exchange can be an hour after its submission. Pinning them means adding both to the turn record — M2 work, not a different read here.Also still carried into #389, unchanged from #704's list: the
leafResultKeysanitization divergence (harness/src/run-leaf.ts:91-102,183-185), which remains the one real defect among them — a result can be written where the status read will never look, and nothing exercises it until a real leaf runs.Assisted-By: Claude Code
fix: pin the turn-id shape in the API contract and test the coupling
docs: correct the dequeue exchange's refusal claims and the async cod…
fix(control-plane): bound the turn id the dequeue exchange reads
feat(work-queue): restore the leaf queue consumer over an injected cl…
9 remaining items
feat(control-plane): mint a turn's grants from the turn record
feat(control-plane): mint turn grants at dequeue under multi tenancy (r…
feat(knative-server): accept grant mode and drain async under multi (r…
test(cp): end-to-end async turn under multi tenancy (rossoctl#388)
docs: grants at dequeue, and the tenancy gate as a boot contract (ros…
Merge pull request #822 from cwiklik/feat/388-m2-grant-redemption
docs: a draft Project page with the roadmap and evidence; async fan-o…
review(389): pin the exact runLeaf call, and name detachable turns
docs: a draft Project page with the roadmap and evidence; async fan-o…
cwiklik commentedon Nov 18, 2026
Landing note: M2 shipped in #807 and #822, and the one open question is already answered in code — closing
M1 was recorded here by #713. M2 was never recorded, which is the only reason this is still open. Verified on
main@6ea986d7.main32b34d75, "mint a turn's grants from the turn record")grant-exchange.ts:182—grantsForTurnmints from the turn record;GRANT_AUDIENCESatgrant.ts:37, with the refresh route the only caller that legitimately accepts eitherturn_expand refresh, with #386's long-turn policyc5ed823e, "mint turn grants at dequeue under multi tenancy")turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), anchored at dequeue and not enqueue.ttlSecondsisMOCA_TURN_MAX_S, soexp == turn_expand nothing refreshes mid-turn — decision D4, with its reasoning and itsshortcut:limit recorded atgrant-exchange.ts:161-181turn-handlers.test.ts:165asserts async is ADMITTED underMOCA_TENANCY=multiand thatasync_tenancy_unsupportedis not returned. Dequeue:turn-exchange.ts:187records the gate as gone.main.ts:255names the boot contract that replaced the per-request refusalsThe open policy question is answered — in shipped, tested code
What #686's status comment still listed as open here was ADR-0047's question: past
turn_exp, is a refresh refused outright, or may a still-running turn extend? It ships as refused outright:turn_expis carried forward unchanged on refresh, so refreshing cannot extend a turn however many times it happens (grant-exchange.ts:209,refreshTurnGrants).verifyGrantraisesgrant_invalidon a grant whoseturn_exphas passed, before the session is read at all.grant-exchange.test.ts:264("refuses outright once turn_exp has passed, rather than extending the turn"),grant.test.ts:199(a grant pastturn_expwhose ownexpis still in the future),grant.test.ts:121(expclamped down toturn_exp, and minting refused once the turn is out of time),grant-redeem.test.ts:34.The async spec's own wording for this — "refusing is the safe default and what M2 should ship" (§5.4) — is what M2 shipped, so there is nothing left to answer or split out.
Also closed since the M1 comment
The two decisions that comment handed to #389 are both resolved:
envelopejoins the claim response (turn-exchange.ts:231,301,sessionIdapplied last so a stored envelope cannot override the record's own) rather than the worker reading Redis behind the HTTP hop, andmodelandsandboxTierare pinned to the turn record (#788,turn-store.ts:163-165), so aPATCH /v1/sessions/{id}between submission and dequeue can no longer move an already-queued turn onto a new model. TheleafResultKeysanitization divergence carried over from #704 — the one real defect on that list — was fixed in #840.Epic #686 then has only #391 (PR #856, in review) left.
Assisted-By: Claude Code
docs: a draft Project page with the roadmap and evidence; async fan-o…