Skip to content

Coding-agent subagents B2: control plane — async turn submission and turn records #387

Closed

Description

@pdettori

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.ts header comment).
  • Data-plane async returns 501 under authentication (packages/knative-server/src/server.ts:838-850).
  • Session keyspace: sh:cp:session:<sid> and sh:cp:owner:<subjectHash>:sessions (MU1 §7.2).

Scope

  1. The routes chosen in Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386, owner-scoped. assertOwner comes through sessionScoped: true in the route table.
  2. 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.
  3. The idempotency key: a second submission with the same key returns the first turn.
  4. 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).
  5. docs/api/openapi.yaml, and mocactl client types.
  6. 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

Out of scope

Working conventions (for a fresh session)

  • Workspace: git fetch, then create a worktree from rossoctl/main (never local main), under .worktrees/. Populate and build pi-fork (git submodule update --init --recursive && cd pi-fork && npm ci && npm run build), then pnpm install. A worktree without the pi-fork build does not typecheck.
  • Plans: write the plan with superpowers:writing-plans into docs/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 for Errors. Redirect long output to /tmp/kagenti/.... make lint skips untracked files.
  • Commits: git commit -s with Assisted-By: Claude (Anthropic AI) <[email protected]>, never Co-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.

Activity

  1. added
    enhancement
    on Sep 30, 2026
  2. changed the title [-]Claude Code subagents B2: control plane — async turn submission and turn records[/-] [+]Coding-agent subagents B2: control plane — async turn submission and turn records[/+] on Oct 13, 2026
  3. added a commit that references this issue on Nov 6, 2026
  4. cwiklik commented on Nov 6, 2026

    @cwiklik
    Contributor

    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.md and ADR-0047 (#696, merged 316056a7). 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 return 501 under authentication — #691 made async: true answer 400 async_removed unconditionally, 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:

    POST /v1/sessions/{sessionId}/turns
      { kind, prompt | item | problemStatement, repoUrl?, ref?, async: true, idempotencyKey? }
      → 202 { sessionId, turnId }
    

    There is no run noun and no second /v1/runs (#279's resolution). 202, not 200 — the response carries the turnId and nothing else, no result and no partial state. One refusal carries over from the removed route: an async turn naming a workloadId answers 501 workload_runs_unavailable at 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, as SessionRecord.owner), tenant, sessionId, cfg (bundle digest), credentialName (a name, resolved server-side at dequeue — never the credential), caps, idempotencyKey, envelope, state, attempts. States:

    queued → running → paused | responded | done | solved | failed | cancelled | lost
    

    The five middle terminals mirror LeafResult's discriminants, so a result maps to a state with no translation. Stored like SessionRecord: Redis hash plus per-owner zset via OwnershipIndex.

    Two things about it are easy to get wrong, so they are specified rather than left open:

    • attempts is descriptive, written from the queue entry's deliveryCount at claim. It is not a second authority for retry exhaustion — the queue's deliveryCount is the only one. Testing both can produce two answers that disagree.
    • The record's TTL is not the result TTL. A non-terminal record carries no TTL at all; the TTL is LEAF_RESULT_TTL_SECONDS plus 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 get 404 ("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?}, 404 for an unknown turn. The record is the single source of truth for state; result comes from leaf-result-store once written. GET /runs/status is deliberately left exactly as it is — it infers status from the result store (server.ts:1163 answers {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. A queued record flips to cancelled and the drain loop drops it at claim. A running leaf is not interrupted: the DELETE answers 409 naming 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 — idempotencyKey defaults to the session id, matching the retry contract dispatch-archetypes.md already documents for synchronous leaves. A resubmission with a key in a non-terminal state returns 202 with the existing turnId. 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 own leafSessionId and 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 interactive 409 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, following MOCA_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, answering 429 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 from SH_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 an async_quota_refusals counter — the one async counter that does not ride the worker's stats IPC 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=single with 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.

  5. 6 remaining items

  6. added a commit that references this issue on Nov 10, 2026
  7. cwiklik commented on Nov 10, 2026

    @cwiklik
    Contributor

    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

    Item Where it landed
    1. The routes from #386, owner-scoped, assertOwner through sessionScoped: true routes.ts:232-256 — POST /v1/sessions/{id}/turns, GET …/turns/{turnId}, DELETE …/turns/{turnId}, all three sessionScoped: true, profile HARNESS (b45336fb)
    2. The turn record in Redis beside the session record turn-record.ts (types, keys, parseTurnSubmission) and turn-store.ts (1b80ce9c, 64e18d4f), over a widened CpRedisLike — zCard, hSetNX, expire added, no Lua and no WATCH/MULTI/EVAL
    3. Idempotency key: a second submission returns the first turn TurnStore.claimIdempotencyKey (HSETNX, so two concurrent submissions cannot both believe they were first) plus turn-handlers.claimKey's one-retry stepover for a holder whose turn is already terminal
    4. Audit entries, and the quota hook turn_submitted, turn_cancelled, turn_refused (subject, session, turn, decision, and the credential name). The hook turned out to be the quota itself — see below
    5. openapi.yaml and mocactl client types 9294c970, 92895a62, b71ae6a1 — submitTurn / getTurn / cancelTurn on ControlPlaneApi
    6. Retire the data-plane 501 Nothing left to retire. As the design comment above predicted, #691 had already made async: true answer 400 async_removed unconditionally; a85d5bee points that refusal at this route and drops the dead envelope field

    New 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, answering 429 async_quota_exhausted with the async_quota_refusals counter. It ships here rather than after, per §9, because it is M1's only containment against the submitter §3 assumes.

    Acceptance

    • Enumeration and drift tests include the new routes. Neither needed editing to cover them, which is the point of both: route-authz-enumeration.test.ts:26 filters ROUTES on sessionScoped and sweeps whatever it finds, and the OpenAPI drift test reads the same table. 0b43a0fd adds one pin the table cannot give — the nine TurnStatus values documented in openapi.yaml must be exactly TURN_STATES, no more and no fewer.
    • Another subject's session gets 404. Over real HTTP in 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 at turn-handlers.test.ts:111, :499, :558 — each asserting the 404 happens before the body or params.turnId is read, so a stranger gets no existence oracle from the error code.
    • An idempotent resubmission returns the same turn. turn-e2e.test.ts:288, asserting the queue depth does not grow.
    • End-to-end with a fake worker passes. 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

    • A deleted session used to leak its open turns' quota slots (34ebaa2f). A turn key is keyed by turnId, not sessionId, so cascadeDelete could not name it; TurnStore.deleteSessionTurns now reclaims the open ones. Terminal turns are left alone — they already carry a TTL (§5.1).
    • The quota had to be decided by a write (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. reserveOpenSlot now 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)"):

    1. turn_exp implemented (MI1 §6.1). §5.4 found it specified in MI1 and present in no TypeScript in the repo; expiry today is always exp = 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.
    2. Grant-at-dequeue with both audiences (Coding-agent subagents B3: grants minted at dequeue from the turn record (no bearer in the queue) #388), replacing the M1 interim where the credential is resolved from the turn record under MOCA_TENANCY=single only.
    3. The tenancy gate lifts. turn-handlers.ts:110 refuses multi by name with async_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: leafResultKey is duplicated between the control plane and the harness with a sanitization divergence — harness/src/run-leaf.ts:91-102,183-185 writes under a possibly tenant-prefixed, sanitized id while getTurn reads 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.

  8. modified the milestones: v0.11.0, v0.12.0 on Nov 17, 2026
  9. cwiklik commented on Nov 18, 2026

    @cwiklik
    Contributor

    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.

    Scope item Where Evidence on main
    1. The routes from #386, owner-scoped via sessionScoped: true #704, plus the artifacts route in #840 (750686e2) packages/control-plane/src/routes.ts:302-336 — POST/GET /v1/sessions/{id}/turns, GET …/{turnId}/artifacts/{kind}, DELETE …/{turnId}, every one auth: 'api' and sessionScoped: true, so assertOwner comes through the route table exactly as this item asked
    2. The turn record in Redis beside the session record #704, fields extended by #788 turn-store.ts holds owner, tenant, session, credential name and caps (turn-handlers.test.ts:83), with model and sandboxTier pinned at turn-store.ts:163-165, and no TTL while queued (turn-handlers.test.ts:120)
    3. The idempotency key #704 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)
    4. Audit entries, and a hook for per-subject quota #704 turn_submitted written at turn-handlers.ts:184-189, into the audit stream and not only the log line (turn-handlers.test.ts:423). The quota hook shipped as MOCA_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)
    5. docs/api/openapi.yaml and mocactl client types #704, #840 docs/api/openapi.yaml:1931, :2022, :2077; packages/mocactl/src/api/control-plane.ts and types.ts
    6. Retire the data-plane 501 for callers of the new route #687's recorded decision ("replaced, not restored"), #691 async_runs_unavailable is gone from the codebase entirely; the data-plane route answers async_removed (packages/server/src/server.ts:1407)

    Acceptance, re-read against that

    1. The authz enumeration and OpenAPI drift tests include the new routes. Both are table-driven off routes.ts, so the four routes are covered without being named: route-authz-enumeration.test.ts, and openapi-contract.test.ts's "documents every implemented route", "implements every documented route" and "uses the same operationId on both sides".
    2. Another subject's session gets 404 — three times, each asserting the refusal lands before the handler reads anything it should not: turn-handlers.test.ts:131 (before the body at all), :594 (before params.turnId), :779 (before touching the turn). A tombstoned session and a missing principal are covered alongside them.
    3. An idempotent resubmission returns the same turn — turn-handlers.test.ts:289.
    4. An end-to-end test with a fake worker passes — 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions