Repository navigation
feat(mocactl): spawn --async, a subagent backed by a turn record (#381) - #922
Conversation
rossoctl#390 moved the assistant's text out of the polled status body but gave it no route: `pickArtifact` served only `patch`, so all that survived a prompt turn was `result.summary`, clipped to MOCA_TURN_SUMMARY_BYTES (2048). A longer reply could not be read back at all. `text` is now a second artifact kind, symmetric with `patch`: described in `result.artifacts` (after the patch, with no `sha256` — nothing hashes the reply on the way in, and the fetch route already hashes what it serves for the ETag) and served whole as `text/plain; charset=utf-8`. A record whose patch capture was refused for size gains its `text`, which is the only thing such a record can serve. The artifact descriptor survives a summary cap of 0, as the patch's does: naming what can be fetched is not model prose. Contract 1.32.0, additive. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
`spawn` has only ever had one backend: a detached local worker holding a synchronous `POST /v1/runs`. That leaf has no turn id, so there is nothing to cancel, and killing the local pid leaves the server-side leaf running (rossoctl#380). This adds the async-turn backend `transport/leaf-turn.ts` was written to be replaced by. `spawn --async` creates the session as before, then queues the leaf with `POST /v1/sessions/{id}/turns` and records the turn id on the ledger row. No fork: the turn record IS the subagent, so nothing on this machine has to survive the command. `subagents` and `get` route per row — a row with a `turnId` reads `GET …/turns/{turnId}` with the API token the command already holds, and `get` fetches the reply and the patch from the turn's artifact routes once there is a result. Everything they print and write is unchanged, because the transport answers in the same `LeafResultBody` the sync one does. Opt-in rather than a swap, because the server-side drain is off by default: `armAsyncLeafWorker` returns null unless `SH_ASYNC_DRAIN` is set, and no deploy target sets it. Making `--async` the only path would submit turns nothing dequeues, queued until the reaper calls them `lost`. Arming the deploy targets is an operator-facing default, not part of a CLI change. Three smaller consequences, each with its reason in the code: - `--async --workload` is refused client-side, exit 2: the control plane answers a workload on the async path with 501, so there is no point creating a session for it. - the `--max-concurrent` preflight counts an async row as holding a slot without probing a pid; it has no child. The slot clears when `subagents` or `get` reads the turn and records a terminal state. - `noResultComing` skips its dead-pid branch for an async row: the turn state the caller just read is that row's liveness, and a turn going nowhere ends as `lost` rather than as a dead pid. Known limit, documented: an async row spawned on another machine is invisible to this one's `get` — no ledger row, no turn id. The same "one machine's ledger" shortcut `--max-concurrent` already carries. Refs rossoctl#381, rossoctl#378 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.
Review — feat(mocactl): spawn --async, a subagent backed by a turn record (#381)
Both halves are careful work; the mapping onto the sync LeafResultBody is what makes it small, and it holds.
Control plane (1.32.0)
describeArtifactslistspatchfirst, thentext, and omitstextwhen the record has none; the refused-capture case now advertises onlytext, which is exactly right (the patch bytes never left the sandbox).pickArtifactservestext/plain; charset=utf-8and returns null for an absent/empty reply. The ETag fallback is real —turn-handlers.ts:262-266hashes whensha256is missing — so the "no stored digest" choice is honest.- The projection change at cap 0 (a descriptor survives, model prose does not) is a sensible distinction and the tests pin both it and the patch-first order.
- Version bump 1.31.0 → 1.32.0 is correct against
main, and this is the only open PR touchingdocs/api/openapi.yaml; the openapi,http-api.md, CHANGELOG and change-policy edits agree with each other and with the code.
mocactl
bodyFromTurncovers every terminal state:queued/running→'queued',lost→failed/lost,cancelled→aborted/cancelled, a terminal turn with no result → its own state, and a result's finer status otherwise.mapHonestState/terminalFromBodyneed no new case, as claimed.collectfetches exactly the advertised kinds, once, and only on a read that found a result; the get test asserts onecollectand nomintSessionTokenfor an async row.--async --configworks, and for a non-obvious reason worth keeping:submitdeliberately sends noconfigRef, but the turn record copies the session's (turn-handlers.ts:147,cfg: rec.configRef ?? '') andspawnbindsconfigRefwhen it creates the session (createSession,subagent.ts:305-308).--async --workloadis refused before the session exists (the control plane's 501 is atturn-handlers.ts:105), and solve fields are carried and run by the samerunLeafthe sync route uses (async-worker.ts:340-343).LedgerRecord.turnIdoptional and written once atappendkeeps old rows working;noResultComingcorrectly skips the dead-pid branch (alostturn is already terminal in the read).
One suggestion inline about the --max-concurrent slot of a finished async row, and a body note on the same point: the description says "subagents or get reads the turn and records a terminal state", but only cmdSubagents calls ledger.updateState (:576-580); cmdGet/readLeafResult never write the ledger. The code's own comment at :172 says subagents only, so the implementation is what the comment describes — the description overstates it.
Tests: three get cases (collect+write, sync routing, cancelled, no dead-pid grace), five spawn --async cases (submit/no-fork, workload refusal before a session, no row on refusal, cap counting, solve fields) and a 124-line transport test. CI 18/18 green.
Author: cwiklik (MEMBER — maintainer). Commits: 2, both signed off.
| // Liveness-gated, not a bare non-terminal count: a stale `running` or `unknown` row — exactly | ||
| // what an unreconciled crash leaves behind — would otherwise hold a slot for good and wedge | ||
| // `spawn` permanently. A child that is gone holds nothing. | ||
| // shortcut: an async row has no child to probe, so it holds its slot until `subagents` reads the |
There was a problem hiding this comment.
suggestion: this comment is accurate — but the consequence is a small wedge worth closing. cmdGet/readLeafResult never call ledger.updateState, so collecting a finished async subagent with get leaves its row non-terminal and it keeps holding a --max-concurrent slot. The natural workflow (spawn --async ×N, get each, spawn more) then refuses at the cap with "N subagents are already running" while every one of them is done, until the user happens to run subagents (its persist loop at :576-580 is the only writer). Two cheap options: have cmdGet record the terminal state it just read (it already opened the row), or reconcile only on the refusal path — read the non-terminal async rows' turns there, which costs a round trip only when the command is about to fail anyway. The PR description already says "subagents or get … records a terminal state"; this is what would make that true.
…c row `cmdSubagents`'s persist loop was the only writer of a turn's state, so an async subagent collected with `get` kept its row non-terminal and went on holding a `--max-concurrent` slot. The natural workflow — `spawn --async` xN, `get` each, spawn more — then refused at the cap with every one of those subagents already done, until the user happened to run `subagents`. `readLeafResult` already opens the ledger row to pick its backend, so it writes the state back when the read is terminal and differs from the row. The sync path needs none of this: its detached worker records its own outcome. Refs rossoctl#381 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Addressed in 6472077 — took the first option: That also makes the PR description's "the slot clears when |
Summary
Epic #378 step 1 (child issue #381): give a spawned subagent a turn record, so it becomes cancellable (#391/B-M1) and A4/#383 clears.
spawnhas only ever had one backend — a detached local worker holding a synchronousPOST /v1/runs. That leaf has no turn id, so there is nothing to cancel, and killing the local pid leaves the server-side leaf running (the A1 contract #380 pinned). This adds the async-turn backendtransport/leaf-turn.ts:3was written to be replaced by.Two commits, deliberately separate.
1. control plane: serve an async turn's reply as a
textartifactA blocker for the CLI change, and independently a completion of #390:
projectLeafResultdropstextfrom the polled status body andpickArtifactserved onlypatch, so all that survived of a prompt leaf's reply wasresult.summary— clipped toMOCA_TURN_SUMMARY_BYTES(2048).--kind promptisspawn's default, so dispatching async without this would have turned "writes the full reply to<sid>.text" into "writes a 2 KB summary".describeArtifactsnow appends{ kind: 'text', bytes }beside the patch entry, andpickArtifactserves it astext/plain; charset=utf-8. The route's existing hash fallback supplies the ETag, text carrying no stored digest. #390 moved the assistant's text out of the polled body but gave it no route; this is that route.API contract: control plane 1.32.0. Additive, but
artifacts[0]can no longer be assumed to be the patch.2. mocactl:
spawn --asyncspawn --asynccreates the session as before, then queues the leaf withPOST /v1/sessions/{id}/turnsand records the turn id on the ledger row. No fork — the turn record is the subagent, so nothing on this machine has to survive the command, which is the whole point.subagentsandgetroute per row: a row with aturnIdreadsGET …/turns/{turnId}with the API token the command already holds (no session-token mint, no mid-wait re-mint), andgetfetches the reply and the patch from the turn's artifact routes once there is a result. Everything they print and write is unchanged, becausetransport/async-turn.tsanswers in the sameLeafResultBodythe sync transport does —mapHonestState/terminalFromBodyand all ofcmdGet's file writing are untouched.Opt-in rather than a swap, because the server-side drain is off by default:
armAsyncLeafWorker(packages/server/src/worker.ts:396) returns null unlessSH_ASYNC_DRAINis set, and no deploy target sets it (deploy/vmhas it commented out,deploy/composepasses${SH_ASYNC_DRAIN:-},deploy/k8sreads an optional ConfigMap key). Making--asyncthe only path would submit turns nothing dequeues — queued until the reaper calls themlost. Arming the deploy targets is an operator-facing default across three targets plussetup.shvalidation, so it is not folded into a CLI change.Three smaller consequences, each with its reason in the code:
--async --workloadis refused client-side, exit 2: the control plane answers a workload on the async path with 501workload_runs_unavailable, so there is no point creating a session for it.--max-concurrentpreflight counts an async row as holding a slot without probing a pid — it has no child. The slot clears whensubagentsorgetreads the turn and records a terminal state.noResultComingskips its dead-pid branch for an async row: the turn state the caller just read is that row's liveness, and a turn going nowhere ends aslostrather than as a dead pid.LedgerRecord.turnIdis written once, atappend, and its presence is the backend marker — no second column, no migration, old rows keep working.Known limit, documented
An async row spawned on another machine is invisible to this one's
get: no ledger row, no turn id, so it falls back to the sync read and finds nothing. The same "one machine's ledger" shortcut--max-concurrentalready carries.get --turn IDwould close it.Deliberately not here
mocactl cancel— epic step 2, a small change on top ofrecord.turnId, but a separate one.SH_ASYNC_DRAINby default indeploy/vm|compose|k8s.Not verified
The end-to-end run on
deploy/composewithSH_ASYNC_DRAIN=1, including the byte-compare of<sid>.textwith and without--async. That byte-compare is the real proof thetextartifact closed the data loss; everything here is unit-level against the spec.Refs #381, #378, #390
Checklist
git commit -s).make lintand the tests for the touched packages pass.packages/control-plane:turn-result,turn-handlers,openapi-contract— 82 passed.packages/mocactl: 222 passedacross
subagent-get,subagent-spawn,subagent-list,transport-async-turn(new),contract,cliandmocactl-reference, plus the whole suite green. 23 of those tests arenew, covering the state mapping (
lost,cancelled, result-status-over-turn-state,artifacts-as-kinds), that a status read carries no bytes, that
collectasks only for declaredkinds, that
spawn --asyncnever forks and writes no row on a refused submission, that anasync row holds a
--max-concurrentslot, and that--waiton an async row ignores a deadpid.
make typecheckclean.make lintis clean excepthadolint-docker, which needs aDocker daemon I do not have running locally.
docs/harness/reference/cli-mocactl.md(regenerated usage plus what--asyncbuys, itsSH_ASYNC_DRAINprecondition, the--jsonshape and the cross-machine limit),docs/harness/reference/http-api.md,docs/api/openapi.yaml(1.32.0),docs/api/CHANGELOG.mdanddocs/reference/change-policy.md.make check-linkspasses (236 files, 0 broken links).Assisted-By: Claude Code