Repository navigation
Closed
Labels
enhancementNew feature or request
Milestone
Description
Part of the Coding-agent subagents epic (#378). Item B2, milestone B-M1. Depends on B1 (#386).
Goal
An authenticated caller submits a leaf turn on its own session with async: true and gets 202 straight away. The control plane records an owned turn record and queues a reference to it, with no bearer token in the queue.
Current state (verified on main @ 24c6f5e)
- Control-plane routes: discovery, device auth,
/v1/me,/v1/sessions(create, list, get, delete),/v1/sessions/{id}/resources,/v1/sessions/{id}/token,/v1/credentials,/internal/credentials. There is no turn submission (packages/control-plane/src/routes.ts). - The route table is read three times: by the router, by the authz enumeration test, and by the OpenAPI drift test (
routes.tsheader comment). - Data-plane async returns 501 under authentication (
packages/knative-server/src/server.ts:838-850). - Session keyspace:
sh:cp:session:<sid>andsh:cp:owner:<subjectHash>:sessions(MU1 §7.2).
Scope
- The routes chosen in Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386, owner-scoped.
assertOwnercomes throughsessionScoped: truein the route table. - The turn record in Redis beside the session record: its states and fields as Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386 decides.
- The idempotency key: a second submission with the same key returns the first turn.
- Audit entries (subject, session, turn, decision), and a hook for per-subject quota (Coding-agent subagents B13: budgets, per-subject quotas and cancel #391, Supervisor: per-subject admission quota #360).
docs/api/openapi.yaml, and mocactl client types.- Retire the data-plane 501 for callers of the new route, per Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386.
Acceptance
- The authz enumeration and OpenAPI drift tests include the new routes.
- Another subject's session gets 404 (a two-subject test in the style of VM demo B: two users log in with mocactl against the P6 VM (device-flow acceptance, ownership checks) #367 / PR test: automated two-subject test for VM demo B (#367 item 3) #371).
- An idempotent resubmission returns the same turn.
- An end-to-end test with a fake worker passes.
Out of scope
- Grants (Coding-agent subagents B3: grants minted at dequeue from the turn record (no bearer in the queue) #388), the consumer (Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389), events (Coding-agent subagents B6: owner-scoped event stream of session and turn state #392).
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 B2: control plane — async turn submission and turn records[/-][+]Coding-agent subagents B2: control plane — async turn submission and turn records[/+]docs: close #386's remaining acceptance items (sequencing, MU1/MI1 wo…
cwiklik commentedon Nov 6, 2026
Design landed — this issue's scope is now specified rather than open. #386 closed with
docs/specs/2026-11-05-p6-async-fan-out-design.mdand ADR-0047 (#696, merged316056a7). Posting the decisions here so whoever picks this up works from the spec rather than re-deriving it, per the spec's §12 obligation.First, two corrections to the body above. It says "verified on
main@ 24c6f5e", which predates #691's removal of the Knative/KEDA path. Still true: there is no turn-submission route in the control plane, the route table is read three times, and the session keyspace is as described. No longer true: data-plane async does not return501under authentication — #691 madeasync: trueanswer400 async_removedunconditionally, and §4.2 keeps that route removed permanently. So scope item 6 ("retire the data-plane 501 for callers of the new route") has nothing left to retire; what replaces it is updating the refusal message to name this route, which the docs half of already landed in #697.The route shape (§4.1). Async is on the turn, not at session creation, so one session can mix interactive and async turns:
There is no
runnoun and no second/v1/runs(#279's resolution).202, not200— the response carries theturnIdand nothing else, no result and no partial state. One refusal carries over from the removed route: an async turn naming aworkloadIdanswers501 workload_runs_unavailableat submission, before admission and before the enqueue, so it stays a synchronous refusal instead of becoming a dead-letter.The turn record (§5.1) — scope item 2. Fields:
turnId,owner(flat subject string, asSessionRecord.owner),tenant,sessionId,cfg(bundle digest),credentialName(a name, resolved server-side at dequeue — never the credential),caps,idempotencyKey,envelope,state,attempts. States:The five middle terminals mirror
LeafResult's discriminants, so a result maps to a state with no translation. Stored likeSessionRecord: Redis hash plus per-owner zset viaOwnershipIndex.Two things about it are easy to get wrong, so they are specified rather than left open:
attemptsis descriptive, written from the queue entry'sdeliveryCountat claim. It is not a second authority for retry exhaustion — the queue'sdeliveryCountis the only one. Testing both can produce two answers that disagree.LEAF_RESULT_TTL_SECONDSplus a margin, set when the turn reaches a terminal state. If the record expired on a schedule from creation, a caller polling a finished turn would get404("never submitted") for a turn that succeeded. The invariant worth a test: a record must never expire while its turn is live, and never outlive its own result by more than the margin.Status read (§4.4) —
GET /v1/sessions/{sessionId}/turns/{turnId}→200 {turnId, state, attempts, result?},404for an unknown turn. The record is the single source of truth for state;resultcomes fromleaf-result-storeonce written.GET /runs/statusis deliberately left exactly as it is — it infers status from the result store (server.ts:1163answers{status:'queued'}when no record exists), and that inference conflates queued, never-submitted and reaped-as-lost. Extending it to consult the turn record would change a live route's responses on top of the admission change §5.3 already costs. The two routes coexist with one source of truth each.Cancel (§4.5) —
DELETE /v1/sessions/{sessionId}/turns/{turnId}→202 | 409. Aqueuedrecord flips tocancelledand the drain loop drops it at claim. Arunningleaf is not interrupted: theDELETEanswers409naming the state, because interrupting one needs control-plane-to-specific-worker machinery that does not exist (interactive cancel, ADR-0040, rides the turn's own connection; async has none). Owed in §12.Idempotency — scope item 3 —
idempotencyKeydefaults to the session id, matching the retry contractdispatch-archetypes.mdalready documents for synchronous leaves. A resubmission with a key in a non-terminal state returns202with the existingturnId. Two consequences to implement deliberately: a fan-out of N leaves is N sessions rather than N turns in one session (each leaf has its ownleafSessionIdand result record, so the default gives each a distinct key for free); and a session therefore has at most one async turn in flight, deduplicated rather than queued behind, which matches interactive409 turn_in_progress.New scope this issue did not have: the per-owner fan-out quota (§4.3).
MOCA_ASYNC_QUEUED_PER_OWNER, default 50, followingMOCA_CONTEXT_MAX_WORKLOADS_PER_OWNER(default 5) for naming and shape. It counts non-terminal turns (queued+running), not lifetime submissions. Enforced here, in the control plane, before the enqueue, answering429 async_quota_exhausted— so a refusal leaves nothing behind, and the thing to assert in a test is the queue depth, not the error body. It reads the per-owner zset the record already lives in (ownership.ts:209-211), so there is no second index to drift. It is distinct fromSH_TURNS_PER_SUBJECT(#360): that one is per worker, in-process, and counts turns executing; this is per deployment, in Redis, and counts turns waiting. Both apply. This is the only containment against unbounded fan-out in M1, so it ships with this issue rather than after it, and §7 adds anasync_quota_refusalscounter — the one async counter that does not ride the worker'sstatsIPC row, since no worker ever sees a refused submission.Milestone placement (§9). This issue's full scope is M2; M1 ships a working drain under
MOCA_TENANCY=singlewith submission, the quota, the status read and queued-only cancel. So the submission route, the record, the quota and the status read are M1-blocking; the complete multi-tenant record is not.Scope items 4 (audit, quota hook) and 5 (
openapi.yaml, mocactl types) are unchanged by the design.fix(control-plane): answer a pathological variable name in linear time
fix(control-plane): decide the async quota by a write, compare every …
feat(control-plane): turn record types, keys and submission validation
fix(control-plane): accept kind:converge in parseTurnSubmission
feat(control-plane): TurnStore over a widened CpRedisLike
fix(control-plane): assert the §5.1 TTL invariant in the turn-store c…
feat(control-plane): TurnQueue port, one XADD of a turn id
feat(control-plane): async turn submission, status and queued-only ca…
fix(control-plane): compare-and-release the idempotency key, gate res…
feat(control-plane): wire the async turn settings through boot
docs(api): document the async turn routes in openapi.yaml
6 remaining items
Merge pull request #704 from cwiklik/feat/387-async-turn-submission
cwiklik commentedon Nov 10, 2026
The M1 slice of this issue has landed. #704 merged as
11da422d(22 commits,01c0c464..b58b5137, 17/17 checks). Every scope item and all four acceptance criteria above are discharged; what remains under this number is the M2 half, which spec §9 assigns to this issue and gates behind #388. Leaving the issue open as that tracker rather than closing and re-cutting it, so #378's list and the spec's §9 reference keep pointing at one number.Scope, as delivered
assertOwnerthroughsessionScoped: trueroutes.ts:232-256—POST /v1/sessions/{id}/turns,GET …/turns/{turnId},DELETE …/turns/{turnId}, all threesessionScoped: true, profileHARNESS(b45336fb)turn-record.ts(types, keys,parseTurnSubmission) andturn-store.ts(1b80ce9c,64e18d4f), over a widenedCpRedisLike—zCard,hSetNX,expireadded, no Lua and no WATCH/MULTI/EVALTurnStore.claimIdempotencyKey(HSETNX, so two concurrent submissions cannot both believe they were first) plusturn-handlers.claimKey's one-retry stepover for a holder whose turn is already terminalturn_submitted,turn_cancelled,turn_refused(subject, session, turn, decision, and the credential name). The hook turned out to be the quota itself — see belowopenapi.yamland mocactl client types9294c970,92895a62,b71ae6a1—submitTurn/getTurn/cancelTurnonControlPlaneApiasync: trueanswer400 async_removedunconditionally;a85d5beepoints that refusal at this route and drops the dead envelope fieldNew scope from the design, also shipped: the per-owner fan-out quota (§4.3).
MOCA_ASYNC_QUEUED_PER_OWNER, default 50, counting non-terminal turns, enforced before the enqueue, answering429 async_quota_exhaustedwith theasync_quota_refusalscounter. It ships here rather than after, per §9, because it is M1's only containment against the submitter §3 assumes.Acceptance
route-authz-enumeration.test.ts:26filtersROUTESonsessionScopedand sweeps whatever it finds, and the OpenAPI drift test reads the same table.0b43a0fdadds one pin the table cannot give — the nineTurnStatusvalues documented inopenapi.yamlmust be exactlyTURN_STATES, no more and no fewer.two-subject.test.ts:199-244: submit, status and cancel on B's session with A's token, plus an unknown turn id. Handler-level atturn-handlers.test.ts:111,:499,:558— each asserting the 404 happens before the body orparams.turnIdis read, so a stranger gets no existence oracle from the error code.turn-e2e.test.ts:288, asserting the queue depth does not grow.turn-e2e.test.ts— submit/drain/read-back, the §5.1 TTL invariant across a live turn, a three-leaf fan-out landing as three sessions each with its own turn and result (the §4.3 consequence of defaulting the key to the session id), queued-only cancel, and the quota refusal with the stream not growing.Two things found on the way that were not in the plan
34ebaa2f). A turn key is keyed byturnId, notsessionId, socascadeDeletecould not name it;TurnStore.deleteSessionTurnsnow reclaims the open ones. Terminal turns are left alone — they already carry a TTL (§5.1).b58b5137). Read-then-check cannot hold a limit against parallel submitters: measured against real Redis, 100 concurrent submissions were all accepted with the limit at 5, because every ZCARD ran before any other submission had written anything.reserveOpenSlotnow ZADDs the candidate and counts after, so a submission sees itself in its own count. "Never more than the limit" is the asserted invariant; "exactly the limit" is deliberately not promised, since a burst can refuse a whole batch and the safe direction is a refused caller retrying.What is left here, and what gates it
The M2 half of this issue, per §9 ("Control-plane turn record and submission API complete (#387)") and §9.1's table ("M2 — requires S2 (grants, token endpoint)"):
turn_expimplemented (MI1 §6.1). §5.4 found it specified in MI1 and present in no TypeScript in the repo; expiry today is alwaysexp = iat + ttlSeconds. The policy is settled in §5.4 —turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), clamped at mint in the control plane, with turn start meaning dequeue and not enqueue.MOCA_TENANCY=singleonly.turn-handlers.ts:110refusesmultiby name withasync_tenancy_unsupported(501), recorded in ADR-0047 as a dated conditional refusal whose lifting criterion is exactly items 1 and 2.So this issue cannot proceed before #388, which §5.4 notes is larger than it reads for precisely that reason. #389 (B4, the P6 consumer) depends on both.
Six smaller items from #704's own reviews are carried into #389 rather than here, listed in that PR's description. The one worth repeating is a real defect rather than a nicety:
leafResultKeyis duplicated between the control plane and the harness with a sanitization divergence —harness/src/run-leaf.ts:91-102,183-185writes under a possibly tenant-prefixed, sanitized id whilegetTurnreads the raw one, so a result can be written where the status read will never look. Nothing exercises it until a real leaf runs, which is #389.docs(api): document the dequeue exchange, and the version the turn ro…
docs(spec): record M1's drain-loop decisions and correct §5.5's resul…
feat(work-queue): restore the leaf queue consumer over an injected cl…
feat(control-plane): GET /metrics for §7's async_quota_refusals
test: §8's Redis integration matrix for the async drain
feat(control-plane): mint and refresh a turn's two grants (#388)
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…
cwiklik commentedon Nov 18, 2026
Landing note: all six scope items shipped, no gap found — closing
Verified on
main@6ea986d7. M1 landed in #704 (b45336fb, "async turn submission, status and queued-only cancel") and was recorded there; everything since went in under #388's, #390's and #391's numbers, which is the only reason this issue still reads as open.mainsessionScoped: true750686e2)packages/control-plane/src/routes.ts:302-336—POST/GET/v1/sessions/{id}/turns,GET …/{turnId}/artifacts/{kind},DELETE …/{turnId}, every oneauth: 'api'andsessionScoped: true, soassertOwnercomes through the route table exactly as this item askedturn-store.tsholds owner, tenant, session, credential name and caps (turn-handlers.test.ts:83), withmodelandsandboxTierpinned atturn-store.ts:163-165, and no TTL while queued (turn-handlers.test.ts:120)turn-handlers.ts:131— defaults to the session id. A resubmission on a non-terminal key returns the FIRST turn id (turn-handlers.test.ts:289); two submissions racing past the same terminal holder create ONE turn (:310); an explicit key allows two turns on one session (:345)turn_submittedwritten atturn-handlers.ts:184-189, into the audit stream and not only the log line (turn-handlers.test.ts:423). The quota hook shipped asMOCA_ASYNC_QUEUED_PER_OWNER(default 50,main.ts:375): refusal with 429 and nothing enqueued (:179), the quota held against simultaneous arrivals (:194), the reserved slot freed on a dedup (:239)docs/api/openapi.yamland mocactl client typesdocs/api/openapi.yaml:1931,:2022,:2077;packages/mocactl/src/api/control-plane.tsandtypes.tsasync_runs_unavailableis gone from the codebase entirely; the data-plane route answersasync_removed(packages/server/src/server.ts:1407)Acceptance, re-read against that
routes.ts, so the four routes are covered without being named:route-authz-enumeration.test.ts, andopenapi-contract.test.ts's "documents every implemented route", "implements every documented route" and "uses the same operationId on both sides".turn-handlers.test.ts:131(before the body at all),:594(beforeparams.turnId),:779(before touching the turn). A tombstoned session and a missing principal are covered alongside them.turn-handlers.test.ts:289.turn-e2e.test.ts:298,describe('async turn, end to end (#387 acceptance)'), over real HTTP and a real Redis stream: the entry is drained, the claim goes through the HTTP hop, and the result and artifact are read back.On the confirm-or-close pass
#686's 2026-11-17 status comment flagged this as the one child where a confirm-or-close pass might still turn up missing work, so I checked all six scope items and all four acceptance criteria individually rather than inferring from the PR list. No gap. The only item whose evidence is not a line of this issue's own code is item 6, and that is by design — #687 decided the data-plane route is replaced rather than restored.
Epic #686 then has #388 (a landing note, no code) and #391 (PR #856, in review) left.
Assisted-By: Claude Code