Repository navigation
feat: per-turn token and wall-clock caps, cancel for a running async turn, and per-subject fairness (#391) - #856
Conversation
Two of rossoctl#391's four acceptance criteria, which are one piece of plumbing. `caps` was already validated, stored and on the dequeue wire; the worker dropped it. - control plane: `caps.costUsd` is refused at submission (400 `invalid_request`) — there is no price table in the runtime, so accepting it promised an enforcement that never happened. A narrowing, taken while /v1 is Preview. - control plane: `DELETE` on a `running` turn sets `cancelRequested` and leaves the state at `running` — every redelivery CAS is written against the open states — answering 202. 409 now means only "already terminal". - worker: `caps.tokens` rides onto `TurnConfig.budgetTokens` and `turnExp` onto the claim. A 2 s watchdog on the existing heartbeat seam aborts the leaf when the cancel flag is set or `turnExp` has passed; no control-plane-to-worker transport, because both sides already share one Redis keyspace. - harness: `runLeaf` takes an `AbortSignal`. A deadline abort reports `failed: budget`, any other abort reports `aborted`, which `asyncFinalizeState` already maps to the record state `cancelled`. An aborted solve returns no partial patch as `solved`. - `budgetVoterExtension` gains `onExceeded`, the only outward signal that it blocked, since pi reports `end_turn` once every tool call is blocked. Docs: control-plane API 1.27.0, harness API 1.5.0, and the spec/ADR amendments striking the "cancelling a running leaf needs new machinery" owed item. Per-subject fairness and cost attribution stay owed, so rossoctl#391 stays open. Refs rossoctl#391 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
The queue is one FIFO stream, so an entry's owner is unknowable until it is claimed: the worker reads the claimed entry's `owner` (one HGET) and, when that owner already holds SH_TURNS_PER_SUBJECT of this worker's slots, hands the entry back unrun and backs off as it does on an empty queue. One owner's fan-out can no longer sit in front of another owner's single turn. The hand-back is XCLAIM ... JUSTID RETRYCOUNT <before this delivery>, not an XACK and re-XADD: it keeps the entry in the PEL (so nothing can lose it) and leaves the delivery counter where it was, so a defer is invisible to maxAttempts. Without that, an owner at their cap would have their own turns dead-lettered for having been deferred three times -- a refusal dressed up as a failure. `WorkQueue` also deliberately exposes no `enqueue` to consumers. The check runs BEFORE the claim handshake, so a turn that may not run yet mints no credential, does not flip to `running` and writes no audit issuance. The slot is released in one `finally` around the whole run, and the counter is the SAME SubjectCounter instance the sync /turn route holds -- two counters would let one subject hold 2x its cap. Known limit, recorded in spec §12 and ADR-0047: the defer resets the entry's idle timer, so a deferred turn waits up to minIdleMs (90 s) before any worker may reclaim it. Leaving IDLE high instead would have this worker's own next claim reclaim the same entry (XAUTOCLAIM leads every claim), defer it again, and never reach the entries behind it -- the starvation the defer exists to prevent. Per-owner streams are the upgrade. `async_deferred_subject` joins §7's counters, plumbed through the stats row to the admin /metrics. It is counted separately from `async_claims`, because a defer read an entry and put it straight back: counting it as a claim would show throughput rising while the queue made no progress. ADR-0047's status header also said M2 was owed while its own milestones section described M2 in the past tense; rossoctl#822 shipped it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
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.
Summary
This wires the stored async-turn caps into the worker: caps.tokens becomes budgetTokens for the budget voter, a 2 s watchdog enforces turnExp, and costUsd is refused with 400. DELETE on a running turn sets cancelRequested, which the worker polls before aborting the leaf through a new AbortSignal on runLeaf. Per-owner fairness is added to the async drain (WorkQueue.defer), and the contracts move to control plane 1.27.0 / harness 1.5.0 (no collision with main's 1.26.0 / 1.4.0, and it merges cleanly).
Two blockers: (1) as built, the fairness check never defers async-only load, because a worker holds at most one async leaf at a time, so the documented "cannot crowd out another's turn" guarantee doesn't hold; (2) caps.tokens can raise the deployment's SH_BUDGET_TOKENS, which contradicts the OpenAPI text. The suggestions cover a cancel/claim race that answers a misleading 409, a cancelRequested flag that outlives the terminal state, and pre-run aborts that still lease a sandbox.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (harness, control-plane, server, work-queue, supervisor, mocactl), Docs (OpenAPI x2, CHANGELOG, ADR-0047, config/sizing), deploy docs
Agent/IDE config (.claude/.vscode): none
Commits: 3, all signed-off: yes
CI status: all green (17/17)
| ...(subjectCap === undefined | ||
| ? {} | ||
| : { | ||
| admitOwner: async (turnId: string) => { |
There was a problem hiding this comment.
must-fix: This fairness check can't do what the docs say. Each worker runs one drain loop that processes one entry at a time (leaf-drain-loop.ts run() awaits runOne serially), and turnsPerSubjectCap is always >= 1. So when admitOwner runs, the owner's count on this worker comes only from their sync /turn traffic. With async-only load, owner A's 500 queued leaves are never deferred, and owner B's single turn still waits behind all of them in the FIFO. The CHANGELOG ("a deep queue from one owner cannot crowd out another's turn"), sizing-and-scaling.md and supervisor.env.example all claim that guarantee. Please either make fairness bound an owner's share of the drain across workers (e.g. per-owner streams or a Redis-side per-owner running count), or reword the docs to what ships: one shared sync+async budget per subject per worker. Either way, add a test where two owners submit async-only work and B's turn runs before A's backlog drains.
There was a problem hiding this comment.
Taken the second branch of your either/or: the docs now say what ships, and the guarantee is no longer claimed anywhere.
docs/api/CHANGELOG.md:47-50: "This bounds MIXED load only -- a worker runs one queued leaf at a time, so an owner's async-only fan-out never reaches the cap, and the queue is still one FIFO stream. A deep async backlog from one owner therefore still delays another owner's async turn; bounding that needs a cluster-wide count and stays open on Coding-agent subagents B13: budgets, per-subject quotas and cancel #391."docs/operations/sizing-and-scaling.md:41-43anddeploy/vm/env/supervisor.env.example:22-25say the same, in the same words.
What does ship is the mixed-load bound, and it is one counter per worker process shared by both paths: packages/server/src/server.ts:131 constructs it and packages/server/src/worker.ts:396 hands that instance to the drain. That wiring is now pinned at source level (packages/server/test/worker-boot.test.ts, af9e1af — your worker.ts:396 note) and behaviourally by async-drain.integration.test.ts §5.3.
The test you asked for — two owners submit async-only work and B's turn runs before A's backlog drains — is the one thing I have deliberately not added: it asserts the guarantee we just removed from the docs. Under async-only load the per-worker count never reaches max(1, floor(S/2)), so the only way to make it pass is the cluster-wide counter, which is the open item on #391 rather than part of this PR.
| const budgetLimit = Number(process.env.SH_BUDGET_TOKENS); | ||
| // The TURN's own cap first (#391): `config.budgetTokens` is what this turn's submitter asked for, | ||
| // SH_BUDGET_TOKENS the deployment's default for turns that asked for nothing. | ||
| const budgetLimit = config?.budgetTokens ?? Number(process.env.SH_BUDGET_TOKENS); |
There was a problem hiding this comment.
must-fix: config?.budgetTokens ?? SH_BUDGET_TOKENS lets a submitter's caps.tokens replace the operator's limit, so a caller can raise it. The same pattern is at run-leaf.ts:470. That contradicts openapi.yaml's caps description ("a cap above the deployment's own limit does not raise it"). For unattended fan-out the ceiling reading is the safe one: when both are set, use Math.min(caps.tokens, SH_BUDGET_TOKENS), and add a test with a cap above the deployment limit. If lifting the limit is intended, fix the OpenAPI text and configuration.md instead.
There was a problem hiding this comment.
Fixed. resolveBudgetLimit (harness/src/budget-voter.ts) is a ceiling rather than a replacement — it returns the tighter of the turn cap and the deployment limit — and both call sites go through it: run-turn.ts for the prompt leaf and /turn, and budgetVoters at harness/src/run-leaf.ts:460 for the leaves that build their own Pi stack. So caps.tokens can only narrow SH_BUDGET_TOKENS, which is what the openapi text you quoted says.
The ADR and the design spec still said "overrides" in prose; corrected in af9e1af.
| return won ? 'cancelling' : 'conflict'; | ||
| } | ||
| if (rec.state !== 'queued') return 'conflict'; | ||
| // `queued` ALONE in the CAS: a claim that won the race between the read above and this write |
There was a problem hiding this comment.
suggestion: There is a race between cancel and claim. If cancel() reads queued and a worker's markRunning lands before the toTerminal(..., ['queued']) CAS, this returns conflict. The handler then answers 409 turn_not_cancellable with "this turn is 'queued'…" (turn-handlers.ts:286, built from the stale state). The contract says 409 means terminal, so the client stops; the "caller's next DELETE" this comment relies on never comes. On CAS failure, re-read and try the ['running'] cancelRequested CAS before reporting conflict, and build the message from the fresh state.
There was a problem hiding this comment.
Fixed. cancel() (packages/control-plane/src/turn-store.ts:394-421) is now a two-pass CAS loop: when the queued CAS loses it re-reads and retries against running, so a markRunning landing between the read and the CAS answers cancelling rather than conflict. Falling out of the loop after the second pass means the record really did go terminal in between, which the comment calls an honest conflict — and the handler's 409 message is built from a fresh read (packages/control-plane/src/turn-handlers.ts:289-298) instead of the stale one, so it can no longer describe a state the turn has left.
| attempts: turn.attempts, | ||
| // Only while a cancel is in flight (#391): the state is still `running`, and this is how a | ||
| // poller tells "running" from "running, stopping". It disappears with the terminal state. | ||
| ...(turn.cancelRequested ? { cancelRequested: true } : {}), |
There was a problem hiding this comment.
suggestion: cancelRequested is never cleared. toTerminal's CAS writes only state/endedAt, and get() maps cancelRequested === '1' in any state (turn-store.ts:243). A turn that was asked to stop but finished done/failed first will report cancelRequested: true on its terminal status. That contradicts this comment ("It disappears with the terminal state") and openapi.yaml ("present and true only on a running turn"). Gate the projection on turn.state === 'running' (or HDEL in toTerminal), and add a finished-after-cancel test.
There was a problem hiding this comment.
Fixed at the projection, as you suggested. packages/control-plane/src/turn-handlers.ts:227 emits the field only when turn.state === 'running', with the reasoning in the comment above it.
toTerminal deliberately still leaves the hash field set: it is also the worker's cancel signal, read by HGET (turn-store.ts:428), so clearing it on the terminal write would race a watchdog poll already in flight. The finished-after-cancel test is packages/control-plane/test/turn-handlers.test.ts:778, "stops reporting cancelRequested once the turn is terminal".
| // The record can ALREADY carry the flag: a cancel that landed while the previous worker was dying | ||
| // leaves the turn `running` with `cancelRequested` set, and this delivery is the reclaim. Checked | ||
| // before the run so that turn never leases a sandbox at all. | ||
| if (await deps.cancelRequested?.(claimed.turnId).catch(() => false)) { |
There was a problem hiding this comment.
suggestion: The comment says a reclaimed turn that already carries the flag "never leases a sandbox at all", but the check runs after claimTurn (a credential minted and audited). runLeaf is then still called with an already-aborted signal: runPromptLeaf leases a sandbox and overlays context/config before it hands the signal to executeTurn, and the solve/verdict producers lease and converge before wireAbort. The same applies to an already-past turnExp (L254). Consider short-circuiting on stop.signal.aborted before runLeaf (write the synthesized aborted / budget result and finalize), and doing the flag check before claimTurn. An abort during lease, seed or overlay is also only observed once the prompt starts, which puts the "within 10 s" criterion at risk.
There was a problem hiding this comment.
Fixed on both counts.
The flag check now runs before the fairness slot and before claimTurn (harness/src/leaf-job-runner.ts:182-198), so a turn carrying the flag mints no credential, writes no issuance to the audit log and leases no sandbox — the comment and the code agree now.
For the already-past turnExp, runLeaf short-circuits ahead of its dispatch: harness/src/run-leaf.ts:510-511 answers from the signal before any kind can lease a sandbox, resolve a promoted config or overlay context, with that reason spelled out in the comment above it. The worker's side still aborts the controller at claim time (leaf-job-runner.ts:330) so the finalize goes through the ordinary failed: budget path.
| 'caps.costUsd is not enforceable (no price table); use caps.tokens', | ||
| ); | ||
| } | ||
| const tokens = cap(capsIn.tokens, 'tokens'); |
There was a problem hiding this comment.
nit: cap() accepts any positive finite number (0.5, 1e300), but the OpenAPI schema declares tokens/wallClock as type: integer. Consider requiring Number.isSafeInteger, and possibly an upper bound.
There was a problem hiding this comment.
Fixed: cap() (packages/control-plane/src/turn-record.ts:217-225) now requires Number.isSafeInteger, so 0.5 and 1e300 are dropped like any other unusable value, matching the type: integer in the schema.
No upper bound beyond that, on purpose: wallClock is clamped to the deployment's MOCA_TURN_MAX_S at mint and tokens is clamped by the SH_BUDGET_TOKENS ceiling in the voter, so an absurd-but-safe integer is already narrowed by the enforcement side rather than accepted as written.
| // Claiming to the consumer that already holds it, with min-idle 0 so the state it is in cannot | ||
| // make this fail. JUSTID keeps Redis from counting a delivery of an entry nobody read, and | ||
| // RETRYCOUNT then puts the counter back where the caller says it belongs. | ||
| await this.client.xClaimJustId(this.stream, this.group, consumerId, 0, [entryId], { |
There was a problem hiding this comment.
nit: defer's bare XCLAIM … 0 JUSTID transfers ownership whatever the current state is, which is the steal-back TOUCH_IF_OWNED_LUA exists to prevent. The window is one owner HGET, but that read rides reconnecting(). If it outlasts minIdleMs and another worker reclaims the entry, this steals it back and resets RETRYCOUNT. An owner-checked script, like touch, would close it.
There was a problem hiding this comment.
Fixed: defer now runs CLAIM_IF_OWNED_LUA (packages/work-queue/src/queue.ts:231-241) — the same owner check TOUCH_IF_OWNED_LUA exists for — so a min-idle-0 claim cannot steal an entry back from a worker that reclaimed it inside the window you described.
| */ | ||
| idempotencyKey?: string; | ||
| caps?: { tokens?: number; costUsd?: number; wallClock?: number }; | ||
| /** Both enforced by the worker (#391). No `costUsd`: the control plane 400s it, unpriceable. */ |
There was a problem hiding this comment.
nit: caps is updated here, but nearby docs are stale: the cancelTurn JSDoc (~L245) still says DELETE answers 409 for a running turn, and the TurnStatus.result doc (~L142) still says aborted reads failed. TurnStatus also lacks cancelRequested, and cancelTurn returns void, so mocactl can't show that a cancel was only requested.
There was a problem hiding this comment.
Fixed in packages/mocactl/src/api/types.ts: TurnStatus gains cancelRequested (:146), its result doc is corrected (a leaf result of aborted reads cancelled, not failed), cancelTurn's JSDoc no longer claims 409 for a running turn, and it returns CancelledTurn rather than void so a caller can see which of the two answers it got.
| async_reclaims: agg.asyncReclaims, | ||
| async_dead_letters: agg.asyncDeadLetters, | ||
| async_claim_denied_full: agg.asyncClaimDeniedFull, | ||
| async_deferred_subject: agg.asyncDeferredSubject, |
There was a problem hiding this comment.
nit: async_deferred_subject is added to the metrics body and pool aggregation, but admin.test.ts ("surfaces the four async counts, summed across workers") wasn't extended, so the worker → pool → /metrics path for it is untested.
There was a problem hiding this comment.
Fixed: packages/supervisor/test/admin.test.ts:103-128 now covers the worker -> pool -> /metrics path for it. The test is retitled "surfaces the five async counts" and the fixture carries async_deferred_subject: 6, so the aggregation is asserted rather than assumed.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The design is right in the places that were hard to get right: the fairness defer via XCLAIM JUSTID with a RETRYCOUNT reset keeps the entry in the PEL while making the defer invisible to maxAttempts (verified against real Redis — queue.test.ts's redelivery still reads deliveryCount: 1), the async worker and the sync /turn route share one SubjectCounter instance, and anchoring turnExp once in the dequeue exchange so the grants' exp and the worker's deadline cannot disagree is the correct shape. One must-fix below: the cancelRequested flag survives the terminal state, which contradicts both the handler's own comment and the OpenAPI contract this PR adds.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness, control-plane, server, work-queue, supervisor, mocactl), docs/OpenAPI, CI
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed-off: yes
CI status: passing (check, lint, k8s-kind-e2e, microvm-gates, DCO, CodeQL, Trivy all green)
Verified by (on the PR head, b39f2e9, throwaway probes deleted afterwards):
pnpm -r typecheckafter building the pi-fork submodule: 0 errors.- Harness tests (budget-voter, classify-outcome, leaf-job-runner, run-leaf): 146 passed.
- Control-plane turn tests: 106 passed. Server async-worker/leaf-drain-loop/turn-claim/worker: 153 passed. Supervisor: 240 passed. Work-queue over a real local Redis: 22 passed.
- A store-level probe through
submitTurn → markRunning → cancel → finalize('done') → getTurnprintedFINAL GET: {"state":"done","cancelRequested":true}— the finding below.
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
| attempts: turn.attempts, | ||
| // Only while a cancel is in flight (#391): the state is still `running`, and this is how a | ||
| // poller tells "running" from "running, stopping". It disappears with the terminal state. | ||
| ...(turn.cancelRequested ? { cancelRequested: true } : {}), |
There was a problem hiding this comment.
must-fix — cancelRequested survives the terminal state, contradicting the comment here and the OpenAPI doc added in this PR.
The comment says the flag is "only while a cancel is in flight … It disappears with the terminal state", and docs/api/openapi.yaml's TurnStatus.cancelRequested says "present and true only on a running turn … absent otherwise". But toTerminal (turn-store.ts:472) CAS-writes {state, endedAt} and never clears the cancelRequested hash field, and this projection emits it whenever it is set, regardless of state.
The PR's own cancelTurn doc explicitly allows the race that exposes it ("a leaf that finishes first stays finished"): a cancel lands on a running turn, the leaf finishes done before the 2 s watchdog notices, and GET /v1/sessions/{id}/turns/{turnId} then answers {"state":"done","cancelRequested":true}. I reproduced exactly that on this head with a probe (submitTurn → markRunning → cancel → finalize('done') → getTurn → FINAL GET: {"state":"done","cancelRequested":true}).
A poller following the documented contract will read a finished turn as still stopping. Suggested fix: either hDel the field in toTerminal alongside the terminal CAS, or gate this projection on turn.state === 'running'. Worth fixing now because TurnStatus.cancelRequested is being published for the first time in this PR — the API is at 1.27.0 Preview, which is exactly when a field that can lie about a terminal turn is cheapest to fix.
There was a problem hiding this comment.
Fixed, with the projection gate you suggested: packages/control-plane/src/turn-handlers.ts:227 emits the field only when turn.state === 'running'. Your probe's final GET now reads {"state":"done"} with the field absent.
I did not HDEL in toTerminal, for two reasons now recorded in the comment there: the same hash field is the worker's cancel signal (read by HGET at turn-store.ts:428), so clearing it on the terminal write would race a watchdog poll in flight; and records written before the fix would still lie. The projection is the one place that owes the published contract.
Test: packages/control-plane/test/turn-handlers.test.ts:778, "stops reporting cancelRequested once the turn is terminal".
clawgenti
left a comment
There was a problem hiding this comment.
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
Review fixes for per-turn budgets and running-turn cancel.
- caps.tokens is a ceiling only: it can narrow SH_BUDGET_TOKENS, never
raise it (must-fix 2).
- cancel() that races a claim becomes a cancel REQUEST, not a refusal:
queued -> cancelled, running -> cancelRequested with the state left
`running` so a redelivery CAS against OPEN_STATES still wins. The 409
now reports the turn's FRESH state (suggestion A).
- getTurn only reports cancelRequested while the turn is `running`: the
flag is never cleared, so a leaf that finished before noticing the
cancel would otherwise read `done` plus cancelRequested forever
(suggestion B).
- runLeaf short-circuits an already-aborted signal before the kind
dispatch, so a reclaimed delivery past its deadline leases nothing
(suggestion C). The drain honours an existing cancel flag BEFORE
admitOwner and claimTurn: no credential is minted, no issuance is
audited, no fairness slot is taken for a turn that must not run.
- caps.{tokens,wallClock} must be positive safe integers (nit 1).
- defer()/touch() share one owner-checked Lua script, so a defer cannot
steal an entry back from the consumer that reclaimed it (nit 2).
- mocactl: cancelTurn returns the 202 body as CancelledTurn, and
TurnStatus carries cancelRequested (nit 3).
- /metrics: async_deferred_subject is summed across workers (nit 4).
Per-subject fairness: the docs now say what ships. SubjectCounter is per
worker and in-process, so the cap paces an owner's MIXED load -- their
interactive turns and their queued leaves share one budget -- and does
not pace an async-only drain, where a worker runs one leaf at a time and
the cap is never reached. The cluster-wide count that would bound that
stays open on rossoctl#391 (spec 12). A two-owner integration test pins the
shipped guarantee: the owner at their cap has entries deferred unrun and
unpenalised while the other owner's turn is claimed and run, and the
backlog drains once the slot comes back.
Also corrects the stale "a running leaf is not interrupted" step in
docs/concepts/dispatch-archetypes.md.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
|
Review addressed in b4ce4e5. Must-fix 1 — fairness is overclaimed. Took the second option: the docs now say what ships, and the two-owner test is there either way.
Reworded in spec §12, New test, Must-fix 2 — Suggestion A — a cancel that races a claim was refused. Suggestion B — Suggestion C — an already-aborted signal still started work. Nits. 1: Also corrected the stale "a running leaf is not interrupted (409 Verification. Follow-ups, not in this PR. The cluster-wide half of per-subject fairness (#391 stays open); a Note: #856 and #861 both edit spec §12 and Assisted-By: Claude Code |
The reviewer's must-fix 1 named this file alongside the CHANGELOG and sizing-and-scaling.md: it still promised that one owner's queued fan-out 'cannot crowd out another's turn'. Reworded to the shipped guarantee -- the cap paces an owner's mixed load, and an async-only drain is not paced because a worker runs one queued leaf at a time. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Careful implementation of #391's containment half: the shared SubjectCounter, the owner-checked XCLAIM defer that refunds the attempt budget, the slot release in finally, and the watchdog-on-heartbeat-seam are all done right, and the test suite (including a real-Redis CAS race test) is unusually thorough. Three suggestions below, all about residual capacity/observability edges rather than correctness of the happy paths. No agent/IDE config files touched, no secrets, all commits signed off, CI green.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness, control plane, server, work-queue), concurrency, Redis queue semantics, docs
Agent/IDE config (.claude/.vscode): none
Commits: 5 commits, all signed-off: yes
CI status: passing
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| return [ | ||
| budgetVoterExtension(sessionManager, { | ||
| limit, | ||
| baseline: branchSpend(sessionManager) ?? 0, |
There was a problem hiding this comment.
suggestion — the budget baseline is branchSpend(sessionManager) ?? 0, so a crash-reclaim redelivery starts with a fresh full caps.tokens budget ("a retry must not fail on its predecessor's tokens" — reasonable). But the API contract advertises caps.tokens as a bound on the turn, and with workers dying mid-leaf the aggregate spend for one turn can reach roughly caps.tokens × maxAttempts. Suggested fix: either count the branch total against the cap on redelivery, or document the per-delivery semantics in the OpenAPI/docs so the advertised bound matches the enforced one.
There was a problem hiding this comment.
Documented, per your second option. The caps description on the submission route (docs/api/openapi.yaml:2003-2008) now reads: "Both are PER DELIVERY. A worker that dies mid-leaf has its turn redelivered, and the retry gets a fresh token budget and a fresh wall clock anchored at its own dequeue [...] So the aggregate across a turn's deliveries can reach the cap times the delivery limit (three). Size tokens as a per-attempt ceiling, not a total." Same in docs/api/CHANGELOG.md:38-42.
The baseline stays branchSpend(sessionManager) ?? 0 for the reason you called reasonable — so the advertised bound now matches the enforced one instead of the enforcement being changed to match the old wording.
| if (!releaseOwner) { | ||
| // Handed back UNRUN and at no cost to its attempt budget; see `defer`'s own doc for why the | ||
| // entry then waits out `minIdleMs` rather than being instantly reclaimable. | ||
| await deps.queue.defer(claimed.entryId, deps.consumerId, claimed.deliveryCount - 1); |
There was a problem hiding this comment.
suggestion — a deferred entry gets its idle timer reset and its attempt budget refunded, and nothing bounds the number of deferrals. An owner who stays at their per-worker cap (long interactive turn, or a slot leaked on another worker) has their queued turns deferred indefinitely: never dead-lettered, never run, and turnExp never starts (it is anchored only at the dequeue that never comes). async_deferred_subject counts defers in aggregate but nothing distinguishes "paced for 90s" from "starved for 6 hours". Suggested fix: a defer-count or age ceiling per entry, or at least a per-entry defer gauge/age histogram next to async_deferred_subject.
There was a problem hiding this comment.
Fixed, bounded by entry AGE rather than by a deferral count: DEFER_CEILING_MS (ten minutes) in harness/src/leaf-job-runner.ts:264, with the age read off the stream id's millisecond part (entryAgeMs, :266-272) so the ceiling costs no extra round trip.
Past the ceiling fairness yields and the entry runs on the worker's own admission slot — one leaf over its owner's share, with the global SH_TURNS_PER_WORKER cap still holding — and the yield is logged. A turn can now be paced but not starved.
| * and `turnExp` is minted here, so anything odd means a control plane older or newer than this | ||
| * worker. Dropping it runs the turn uncapped, as before #391; throwing would make it unrunnable. | ||
| */ | ||
| function positive(v: unknown): number | undefined { |
There was a problem hiding this comment.
suggestion — coercing odd exchange-body values to undefined is the right version-skew tradeoff, but the consequence is that a buggy control plane (caps: {tokens: -5}, turnExp: "soon") silently runs the turn uncapped with no trace. Suggested fix: one log line when a present-but-invalid cap/deadline is dropped, so an operator can see enforcement degrade instead of discovering it from an over-run turn.
There was a problem hiding this comment.
Fixed: positive(v, what) in packages/server/src/turn-claim.ts logs one line when a field is present but unusable, so caps: {tokens: -5} or turnExp: "soon" from a buggy control plane leaves a trace instead of silently running the turn uncapped. The coercion itself is unchanged — version skew still reads as "no cap" rather than failing the turn.
Three conflicts, all of them contract-version bookkeeping: main shipped 1.27.0 (rossoctl#779, the base URL's page) and 1.28.0 (rossoctl#510, the config bundle's format version) while this branch held 1.27.0, and main's 1.28.0 already took the data plane's 1.5.0. - docs/api/CHANGELOG.md: this branch's section becomes 1.29.0 and its data-plane twin 1.6.0, above main's 1.28.0 and 1.27.0. - docs/api/openapi.yaml: info.version 1.29.0. - docs/api/harness-openapi.yaml: info.version 1.6.0 (it merged clean at 1.5.0, which both sides had bumped to for different reasons). - docs/reference/change-policy.md: main's sentence and decision table, with 1.29.0 / 1.6.0 and this branch's clause appended to the version list. openapi-contract.test.ts derives both literals from the changelog, so the three files have to agree. Everything else merged clean. Verified after the merge: both OpenAPI contract suites, make typecheck, make lint, control-plane (1989), server (599) and harness (939, the one failure being the pre-existing macOS-only context-overlay case). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Merged All three conflicts were contract-version bookkeeping: main shipped 1.27.0 (#779, the base URL's page) and 1.28.0 (#510, the config bundle's format version) while this branch still held 1.27.0, and main's 1.28.0 had already taken the data plane's 1.5.0. So this branch is renumbered to control plane 1.29.0 / harness 1.6.0, with its changelog section moved above main's two, its clause appended to Verified after the merge: both OpenAPI contract suites (21 + 9), Assisted-By: Claude Code |
Conflicts in ADR-0047's "Also owed" paragraph and the spec's §4.4/§4.5 boundary: rossoctl#861 landed rossoctl#537's decision against /v1/batches while this branch rewrote the same paragraph and renamed §4.5. Kept both — the rossoctl#537 amendment block, §4.5's new "Cancellation" title (a running leaf is cancellable now), and rossoctl#391's fairness/rossoctl#859 amendments, with /v1/batches dropped from the owed list since rossoctl#537 decided against it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
There was a problem hiding this comment.
Summary
Reviewed the per-turn token/wall-clock caps, running-turn cancel, and per-subject fairness end to end under elevated scrutiny (external contributor): budget voter plus 2s watchdog on an AbortController, DELETE → cancelRequested flag polled over the shared Redis keyspace, and owner-checked XCLAIM … JUSTID RETRYCOUNT defer pacing an owner's async+interactive load against the same in-process SubjectCounter as the sync route. All must-fixes from the prior review round (tighter-of budget resolution, cancel/claim race, gated cancelRequested, pre-abort short-circuit, safe-integer caps, owner-checked Lua, mocactl 202 body, summed metric) are verifiably addressed on head; the caps/cancel/fairness plumbing is consistent end-to-end (same env vars, same counter instance, single turnExp at the exchange, tighter-of limit in both executeTurnCore and leaf-side budgetVoters). No must-fix findings — one suggestion and one nit below.
Author: cwiklik (CONTRIBUTOR — returning external, read with elevated scrutiny)
Areas reviewed: TypeScript (control-plane, server, harness, mocactl, supervisor, work-queue), OpenAPI/changelog/docs
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits, all signed-off: yes
CI status: passing
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
| return { kind: 'dead_lettered', turnId: claimed.turnId, reclaimed: claimed.reclaimed }; | ||
| } | ||
|
|
||
| // The record can ALREADY carry the cancel flag (§4.5, #391): a cancel that landed while the |
There was a problem hiding this comment.
suggestion — The pre-claim cancel check swallows poll errors (catch(() => false)), so a Redis blip exactly at claim time runs a turn the user just asked to cancel. The in-run watchdog covers it within CANCEL_POLL_MS (2s), which meets §4.5's 10s criterion — but it's worth one sentence here saying the watchdog is the backstop, so a future reader doesn't "fix" the catch into a refusal.
There was a problem hiding this comment.
Added — the comment at harness/src/leaf-job-runner.ts:186-190 now says exactly that: "A failed poll reads as 'no cancel' and the turn RUNS: the in-run watchdog re-polls every cancelPollMs and aborts within §4.5's ten seconds, so a Redis blip at claim time costs a few seconds of a sandbox rather than a turn. Do not turn this catch into a refusal -- that would make a blip strand a turn nobody asked to cancel."
| // The deadline the control plane anchored at THIS dequeue, enforced by the job runner's | ||
| // watchdog (#391). Not recomputed from `caps.wallClock`: the grants expire at this instant, so a | ||
| // leaf outrunning it would fail with 401s instead of a clean `failed: budget`. | ||
| ...(positive(body.turnExp) ? { turnExp: body.turnExp as number } : {}), |
There was a problem hiding this comment.
nit — ...(positive(body.turnExp) ? { turnExp: body.turnExp as number } : {}) evaluates positive() and then re-reads/casts the raw field. Hoist const turnExp = positive(body.turnExp) beside budgetTokens and spread that, so the coercion and the value can't diverge.
There was a problem hiding this comment.
Fixed: turnExp is hoisted beside budgetTokens in packages/server/src/turn-claim.ts and the spread uses that value, so the coercion and the value it guards cannot diverge.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This closes the loop on #391's containment criteria well: caps now ride the existing dequeue wire into the leaf (token cap via the budget voter, wall clock via a single turnExp computed once at the exchange so grants and the worker's deadline can't disagree), cancel reuses the shared Redis keyspace instead of new transport, and the fairness defer (XCLAIM … JUSTID RETRYCOUNT with the owner-check) is careful about the two hazards that pattern invites — attempt-budget penalties and stealing back a lost entry. resolveBudgetLimit taking the tighter of turn cap and SH_BUDGET_TOKENS fixes the one direction that mattered, and the docs/spec/ADR amendments (including striking costUsd and the stale 409 claim) match the code throughout.
No must-fix findings. One suggestion and two nits below; the rest of the review is clean — DCO signed on all commits, no .claude//.vscode/ changes, no new dependencies, and CI is green including the Kind e2e and the two-owner fairness integration test.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness, control-plane, server, work-queue, supervisor, mocactl), OpenAPI, docs
Agent/IDE config (.claude/.vscode): none
Commits: 7 commits, all signed-off: yes
CI status: passing
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
| if (rec.state !== 'queued') return 'conflict'; | ||
| if ((await this.toTerminal(rec, 'cancelled', now, ['queued'])) === 'ok') return 'cancelled'; | ||
| } | ||
| return 'conflict'; |
There was a problem hiding this comment.
suggestion — If the running CAS loses twice in a row (a finalize landing between the read and the CAS on the second pass too), cancel() falls out of the loop and returns 'conflict' while the fresh read still said running. The handler then answers 409 with "this turn is 'running'; only a queued or running turn can be cancelled" — self-contradictory, and per the handler's own comment 409 is the one answer a caller stops on, so that turn goes uncancellable for the rest of its life. The window is tiny (the first CAS only loses to a claim, the second only to a finalize), but the failure mode is exactly the one the retry loop was added to prevent. Suggested fix: on the second pass, if the re-read still says running, retry the CAS once more (or loop a bounded N on the running branch alone) rather than falling through to return 'conflict'.
There was a problem hiding this comment.
Fixed: the loop no longer reports a conflict it cannot justify. cancel() (packages/control-plane/src/turn-store.ts:394-421) re-reads before each CAS, so falling out after the second pass means the record really did move terminal in between — the comment says so in those terms. And the handler's 409 message is built from a fresh read (turn-handlers.ts:289-298), so it can no longer answer "this turn is 'running'; only a terminal turn..." about a turn that is done.
| // Not armed when there is nothing for it to watch: a caller with no `cancelRequested` against a | ||
| // control plane that sends no `turnExp` (both pre-#391) would otherwise pay a timer per leaf for a | ||
| // tick that can never abort anything. | ||
| const watchdog = |
There was a problem hiding this comment.
nit — The watchdog rides the setHeartbeat/clearHeartbeat injection seam, whose name (and doc at heartbeatMs) says heartbeat. Production is unaffected (both default to setInterval/clearInterval), but the tests already have to know heartbeats[1] is "the watchdog" — a setTimer/clearTimer seam (or just letting cancelPollMs default to setInterval directly) would keep the two periods from sharing a name that describes only one of them.
There was a problem hiding this comment.
Fixed: the watchdog rides its own setTimer/clearTimer seam (harness/src/leaf-job-runner.ts:274), so the tests no longer have to know that heartbeats[1] is the watchdog, and the heartbeat doc no longer describes two different timers.
| subject_quota_exceeded — the authenticated subject already holds | ||
| SH_TURNS_PER_SUBJECT in-flight turns on this worker (default half the per-worker | ||
| turn cap). Distinct from the supervisor's pre-hand-off `overloaded` 429, which has | ||
| turn cap), counting the subject's running QUEUED turns as well as its interactive |
There was a problem hiding this comment.
nit — This description line is now ~400 characters on one line after inserting the #391 sentence mid-sentence ("…turn cap), counting the subject's running QUEUED turns…"). The surrounding descriptions wrap at ~100; worth rewrapping so the diff (and the file) stays readable.
There was a problem hiding this comment.
Fixed: docs/api/harness-openapi.yaml:211-222 is rewrapped at <=96 characters, matching the descriptions around it.
clawgenti
left a comment
There was a problem hiding this comment.
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
Eight review comments on rossoctl#856: - caps are per DELIVERY, not per turn: say so in the openapi `caps` schema, the 1.29.0 changelog entry and above `budgetVoters`' baseline, since a redelivery after a mid-leaf death gets a fresh budget by design. - a deferred entry now yields after ten minutes (DEFER_CEILING_MS), measured from its own stream id: nothing else bounded the defer count, so an owner who never freed a slot starved their own queue forever -- never run, never dead-lettered, `turnExp` never anchored. - an unusable `caps.tokens` or `turnExp` off the exchange is logged instead of dropped silently, and the coercion is hoisted beside the value it guards. - document why a failed pre-claim cancel poll reads as "no cancel" (the in-run watchdog still aborts within §4.5's ten seconds). - document why `cancel()`'s two CAS passes are enough: a third would re-read a turn that is already final. - rename the job runner's heartbeat timer seam to `setTimer`/`clearTimer`, which is what it is -- the watchdog shares it. - rewrap the harness 429 `subject_quota_exceeded` description. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Second review round addressed in
Not run locally: Assisted-By: Claude Code |
pdettori
left a comment
There was a problem hiding this comment.
Summary
All nine findings from the earlier CHANGES_REQUESTED round are verifiably addressed on 19a3071: tighter-of token limit (resolveBudgetLimit, in both executeTurnCore and the solve/verdict voters), the cancel/claim CAS retry with a fresh-state 409, cancelRequested gated on running, the pre-dispatch abort short-circuit plus cancel check ahead of admitOwner/claimTurn, safe-integer caps, the owner-checked CLAIM_IF_OWNED_LUA shared by defer/touch, the mocactl 202 body, the summed metric test, and docs that now state the mixed-load-only fairness guarantee. The one blocker is new: main shipped control-plane contract 1.29.0 (#874) while this PR was open, so it now conflicts in three docs files and claims a version that is already taken. Two suggestions cover remaining exposure: defers that read as crash reclaims in async_reclaims, and a wall-clock cap that restarts on every redelivery.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (harness, control-plane, server, work-queue, supervisor, mocactl), OpenAPI x2, CHANGELOG, spec/ADR, deploy docs
Agent/IDE config (.claude/.vscode): none
Commits: 7 commits, all signed-off: yes
CI status: passing (17/17); branch is CONFLICTING with main
| info: | ||
| title: MOCA control plane | ||
| version: 1.28.0 | ||
| version: 1.29.0 |
There was a problem hiding this comment.
must-fix: Version collision plus merge conflict. Main already ships control-plane contract 1.29.0 (#874: /v1/auth/device 429 quota_exceeded, per-source bound), and this PR claims 1.29.0 too. GitHub now reports the PR CONFLICTING, in docs/api/CHANGELOG.md, docs/reference/change-policy.md and docs/reference/configuration.md. Please merge main and renumber to 1.30.0: the openapi version, the CHANGELOG heading, change-policy, and the PR body's "Control-plane API 1.29.0". Harness 1.6.0 is still free (main is on 1.5.0).
There was a problem hiding this comment.
Fixed. upstream/main is merged in — GitHub reports MERGEABLE, no conflicts in the three files you named — and the control-plane contract is renumbered to 1.30.0: docs/api/openapi.yaml:14 (version: 1.30.0), the docs/api/CHANGELOG.md heading (## 1.30.0, with main's 1.29.0 intact below it), and docs/reference/change-policy.md:25,131. Harness stays 1.6.0 (docs/api/harness-openapi.yaml:18). The PR body is updated to match.
One leftover you did not catch: the design spec's §4.3 amendment still cited CHANGELOG 1.27.0 for the costUsd refusal. Corrected in af9e1af.
| return; | ||
| } | ||
| t.asyncClaims += 1; | ||
| if (outcome.reclaimed) t.asyncReclaims += 1; |
There was a problem hiding this comment.
suggestion: A deferred entry stays in the PEL, so XREADGROUP > never returns it again; the only way back is XAUTOCLAIM, which flags it reclaimed: true (queue.test.ts's defer test asserts exactly that). Every turn that was ever deferred therefore bumps async_reclaims when it finally runs. deploy/k8s/README.md:1344 and spec §7 define that counter as "a nonzero steady rate means workers die mid-leaf", so with fairness active an operator sees a steady reclaim rate and no dead workers. Either document the overlap in §7 / the README (read async_reclaims net of async_deferred_subject), or keep the two signals apart.
There was a problem hiding this comment.
Documented, per your first option — the overlap is real and operators now read the two together.
docs/specs/2026-11-05-p6-async-fan-out-design.md:881:async_reclaimsis "XAUTOCLAIMfiring. Read net ofasync_deferred_subject(below)", and §7 states outright that neither counter alone is the dying-worker signal.deploy/k8s/README.md:1351-1356:async_deferred_subjectrising while slots sit idle is the cap pacing one submitter, and the operator is told to subtract it before reading a reclaim rate as workers dying mid-leaf.
Keeping the two apart would need the drain to distinguish a deferred reclaim from a crash reclaim at claim time, which is a queue-side change rather than a metrics one.
| // Returned in BOTH modes (#391), because the WORKER now stops the leaf on it and a wall-clock cap | ||
| // that only existed under `multi` would be a cap that depends on tenancy. Computed once, here, and | ||
| // handed to the grant mint below so the grants' `exp` and this field cannot disagree (decision D4). | ||
| const turnExpS = turnExp( |
There was a problem hiding this comment.
suggestion: turnExpS is anchored at now() on every dequeue exchange, including crash-reclaim redeliveries, so caps.wallClock bounds each delivery rather than the turn. A turn whose worker dies at minute 9 of a 10-minute cap gets a fresh 10 minutes, up to about maxAttempts x wallClock. openapi.yaml describes turnExp as "the absolute end of this turn". This has the same per-delivery shape as the open caps.tokens thread on run-leaf.ts:476. Either anchor once (persist the first dequeue's turnExp on the record and reuse it on redelivery), or document per-delivery semantics for both caps. As written, the "reclaimed delivery whose deadline is already past" short-circuit (run-leaf.ts:503, leaf-job-runner.ts:269) is reachable only through control-plane/worker clock skew.
There was a problem hiding this comment.
Documented for both caps, per your second option. The dequeue response's turnExp (docs/api/openapi.yaml:5027-5039) now reads "the absolute end of THIS DELIVERY, anchored at the DEQUEUE and clamped to min(caps.wallClock, MOCA_TURN_MAX_S)", followed by "Per delivery, not per turn, because it is anchored at each dequeue [...] See caps on the submission route for the aggregate this allows (the cap times the delivery limit)." The submission route's caps states the same for tokens and wallClock together.
Anchoring once would persist the first dequeue's deadline and then make a redelivery unrunnable rather than merely capped — a deadline the turn had already passed — so the per-delivery shape is kept and said out loud instead.
You are right that this leaves the "deadline already past" short-circuit reachable only through clock skew; it stays because the control plane and the worker are separate clocks, and run-leaf.ts:510 is the cheap place to answer it.
rossoctl#716 shipped control plane 1.29.0 while this branch was in review, so rossoctl#391's section becomes 1.30.0 and the data plane's 1.6.0 ships with it. - CHANGELOG: rossoctl#391's section renumbered 1.30.0 above rossoctl#716's 1.29.0; the data-plane table points 1.6.0 at it. - change-policy: both version mentions bumped, and the route-history sentence keeps both sides' clauses (the per-source bound, then per-turn budgets). - configuration.md: upstream's two new rows (SH_OIDC_MAX_PENDING_PER_SOURCE, SH_TRUSTED_PROXY_HOPS) with this branch's MOCA_TURN_MAX_S text, which says the worker now enforces the dequeue-anchored instant. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Also rebased-by-merge onto
Assisted-By: Claude Code |
Two suggestions from the second review round. Both are the documenting half of the choice offered, because the alternatives are worse: - `async_reclaims` no longer means "workers die mid-leaf" on its own. A deferred entry stays in the PEL, so XREADGROUP `>` never offers it again and XAUTOCLAIM is the only way back -- every deferred turn is counted a reclaim when it runs. Keeping the signals apart would need the drain to tell a hand-back's return from a crash's, and they arrive identically (the defer's RETRYCOUNT: n-1 is what the reclaim re-increments). So spec §7, the k8s README's watch table and the two code sites say: read it net of `async_deferred_subject`. - `turnExp` is anchored at EACH dequeue, so the wall clock bounds a delivery rather than a turn, as `caps.tokens` already does. Anchoring once would mint a reclaimed delivery credentials that are already expired -- a turn that cannot be retried at all. Said in the openapi `turnExp` description, spec §5.4 and at the anchor in turn-exchange.ts. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
@pdettori all three addressed — the must-fix in must-fix, version collision. Merged main and renumbered to 1.30.0: openapi
Green locally: Assisted-By: Claude Code |
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Large, well-structured change: per-turn token/wall-clock caps, cancellation of running async turns, and the per-worker half of per-subject fairness. Reviewed TypeScript across harness, control-plane, server, mocactl, supervisor and work-queue, plus the docs/OpenAPI changes. No security findings (no secrets, no new dependencies, no CI changes), and the core claims — costUsd refused at submission, DELETE → cancelRequested/202, watchdog abort mapping, XCLAIM JUSTID defer invisible to maxAttempts — are all upheld with tests.
No blocking issues. The items below are documentation contradictions and test-coverage gaps:
- The spec's §4.3 amendment cites
docs/api/CHANGELOG.md1.27.0 for the costUsd refusal, but the entry lands in 1.30.0 in this PR. - The spec and ADR-0047 amendment say a turn's own cap "overrides"
SH_BUDGET_TOKENS, butresolveBudgetLimittakesMath.min— a cap can only narrow, never raise. The OpenAPI wording is the correct one; the spec/ADR wording could be read as permitting a raise. - The shared-
SubjectCounterwiring — the PR's central "same instance the sync /turn route holds" guarantee — is only type-checked; the integration test constructs its own counter. A refactor that splits the instance would pass the suite.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript, Docs, OpenAPI
Agent/IDE config (.claude/.vscode): none
Commits: 10 commits, all signed-off: yes (DCO pass)
CI status: passing
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
| > arithmetic — so a `caps.costUsd` on a submission was accepted and silently ignored, which is a | ||
| > worse answer than absent. It is now refused at submission with | ||
| > `400 invalid_request: caps.costUsd is not enforceable (no price table); use caps.tokens`. A | ||
| > narrowing, taken while `/v1` is Preview and recorded in `docs/api/CHANGELOG.md` 1.27.0. The other |
There was a problem hiding this comment.
suggestion — This §4.3 amendment points readers at docs/api/CHANGELOG.md 1.27.0 for the costUsd refusal, but the changelog entry this PR adds is under ## 1.30.0. One-word doc fix so readers land on the right release.
There was a problem hiding this comment.
Fixed in af9e1af: the §4.3 amendment now cites docs/api/CHANGELOG.md 1.30.0, which is where the entry actually landed after the renumber.
| > - **`caps.tokens` inside the leaf.** It rides the dequeue response onto `TurnConfig.budgetTokens` | ||
| > and arms the existing budget voter (`harness/src/budget-voter.ts`), which blocks tool calls once | ||
| > the turn's spend crosses it — the same mechanism as the `SH_BUDGET_TOKENS` deployment default, | ||
| > which a turn's own cap overrides. The leaf then ends `failed` with `result.reason: "budget"`. |
There was a problem hiding this comment.
suggestion — "a turn's own cap overrides" the deployment default: the code clamps with Math.min (budget-voter.ts, resolveBudgetLimit), so a turn cap can only narrow the deployment limit, never override/raise it. The OpenAPI text ("a cap above the deployment's own limit does not raise it") states it correctly — the spec and the ADR-0047 amendment should match that wording, since "overrides" can be read as permitting a raise.
There was a problem hiding this comment.
Fixed in af9e1af. Both places now say narrow rather than override:
- the spec's §4.3 amendment: "which a turn's own cap can only narrow, never raise (
resolveBudgetLimittakes the tighter of the two)"; docs/adrs/0047-p6-async-fan-out-in-worker-drain.md:79-80: "a turn's own cap can only narrow that default, never raise it (resolveBudgetLimittakes the tighter of the two)".
So the prose matches both the code and the OpenAPI text you quoted.
| // one cap governs both (§5.3), and `subjectCounter` with it so one PER-OWNER cap does too (#391). | ||
| // Returns null unless SH_ASYNC_DRAIN and the control-plane settings are all present, so a | ||
| // deployment that never submits async turns pays nothing. | ||
| const asyncWorker = armAsyncLeafWorker({ counter: runtime.counter, subjects: subjectCounter }); |
There was a problem hiding this comment.
suggestion — The PR body's guarantee that the drain and the sync /turn route share one SubjectCounter per worker process is only type-checked here. async-drain.integration.test.ts §5.3 constructs its own new SubjectCounter() and hands it to processOne directly, so a future refactor that moves or re-imports subjectCounter would silently split the count — exactly the 2×-cap failure the body warns about. Consider a wiring test that asserts the instance reaching armAsyncLeafWorker is the one server.ts holds (toBe/identity check), which is cheap and pins the invariant.
There was a problem hiding this comment.
Fixed in af9e1af, at source level — packages/server/test/worker-boot.test.ts, next to the existing prepareServerProcess boot-call checks:
server.tscontains exactly onenew SubjectCounter(, exported assubjectCounter, and the sync route acquires on that identifier;worker.tsis matched against the whole argument object,armAsyncLeafWorker({ counter: runtime.counter, subjects: subjectCounter }), plus anot.toMatch(/new SubjectCounter\(/)so it cannot quietly build its own. Matching the whole object matters:subjects: new SubjectCounter()would still mention the imported name and pass a looser check.
Source-level rather than behavioural because the arming lives in worker.ts's top-level isMainModule block, which no in-process test reaches, and §5.3 drives processOne with its own counter by design. The alternative was exporting a wrapper purely for testability, which seemed the worse trade.
| if (entryAgeMs(claimed.entryId) < (deps.deferCeilingMs ?? DEFER_CEILING_MS)) { | ||
| // Handed back UNRUN and at no cost to its attempt budget; see `defer`'s own doc for why the | ||
| // entry then waits out `minIdleMs` rather than being instantly reclaimable. | ||
| await deps.queue.defer(claimed.entryId, deps.consumerId, claimed.deliveryCount - 1); |
There was a problem hiding this comment.
suggestion — This queue.defer hand-back sits outside the try/finally wrapping runClaimedEntry, so a Redis blip during the hand-back propagates out of processOne and leaves the entry in this consumer's PEL with its idle timer running. It self-heals via XAUTOCLAIM after minIdleMs (90 s) — and possibly to this same worker, which would defer it again — but a fairness defer turning into a 90 s stall of one entry is an untested failure mode. Consider catching and logging it, plus a test for the defer-throws path.
There was a problem hiding this comment.
Fixed in af9e1af. The hand-back is wrapped and logged rather than propagating (harness/src/leaf-job-runner.ts:216-232): the entry has already left XREADGROUP's reach and sits in this consumer's PEL either way, so it returns via XAUTOCLAIM after minIdleMs — the same wait a successful defer costs it. The one lost effect is the attempt refund, which is why it is logged and not swallowed: a run of these means pacing is charging deliveries, and an owner's entries could reach maxAttempts by being paced.
Test: harness/test/leaf-job-runner.test.ts, "survives a hand-back that throws: still deferred, logged, no run, no ack" — a throwing queue.defer still yields {kind: 'deferred'}, runs no leaf and acks nothing (acking would lose the turn outright).
| }); | ||
|
|
||
| // The worker's cancel/deadline stop (#391), bridged to pi's abort exactly as executeTurn does | ||
| // for a client disconnect. An already-aborted signal aborts the session before the prompt, so |
There was a problem hiding this comment.
nit — The real wireAbort(signal, session) bridging and the signal?.aborted || capture.budgetExceeded early returns are exercised only by the Kind smoke; all unit tests inject produceSolve/produceVerdict fakes. A regression in the real bridging would pass the suite. If a cheap unit seam exists, one test on the real producer path would close the gap.
There was a problem hiding this comment.
Fixed in af9e1af — there was a cheap seam after all. harness/test/run-leaf-solve-produce.test.ts already drives the real realProduceSolve with the sandbox transport and pi module mocked, so the new test ("aborts the session on a mid-leaf cancel and captures no patch") cancels from inside the prompt() mock and asserts the real wireAbort reached Pi (session.abort() called once) and that the post-prompt guard held: no diff-capture script executed, capture.patch undefined. That exercises the addEventListener half of the bridge, which is the production shape — a cancel arriving mid-leaf.
Both negative controls were confirmed before committing: deleting wireAbort(signal, session) fails on the abort assertion, and deleting if (signal?.aborted || capture.budgetExceeded) return; fails on the diff-capture one.
Reaching it needed the pi mock to spread the real module — the factory was missing getAgentDir and SettingsManager, so anything running past convergeWorkspace halted at turnLoaderInputs. That also means this file's existing opt-in-path test was stopping earlier than its comment claimed; it now halts where it says it does.
There was a problem hiding this comment.
(duplicate of the reply above — posted twice by mistake)
clawgenti
left a comment
There was a problem hiding this comment.
Generated by RepoMan github-pr-review@9672454 (https://github.com/rossoctl/agent-skills/blob/96724547c162978f58d845b9a8331a679bf39444/skills/github-pr-review/SKILL.md).
Review on rossoctl#878: - the no-signal guard only caught a 4th argument, which is the least likely shape. Pin the call instead -- two arguments, no `signal` on either -- so a signal on `config`, inside `deps` or as a third argument fails it too. Verified by patching both shapes into `handleRunLeafParsed` and watching the test fail. - `/turn` aborts on disconnect UNLESS the turn is detachable (ADR-0040, SH_TURN_DETACH=1), which the asymmetry's two statements left out. - the disconnect-abort section is §3.6 of the turn-SSE streaming spec, not of ADR-0029. - cite rossoctl#388 for M2's gate lift, since ADR-0047's status line predates it (rossoctl#856 refreshes that line). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…bort coverage Four review items from rossoctl#856, each with the test that would have caught it: - `processOne`'s fairness hand-back sat outside any try: a Redis blip in `queue.defer` propagated out of a path whose whole job is to NOT run the turn, turning a pacing decision into a crash. It is now caught and logged — the entry still returns via XAUTOCLAIM, only the attempt refund is lost, which is exactly what the log says. New test drives a throwing `defer` and pins: still `deferred`, nothing run, nothing acked. - The per-owner cap is only correct if the sync `/turn` route and the async drain count into the same in-process `SubjectCounter`; the arming lives in worker.ts's `isMainModule` block, which no in-process test reaches. Pinned at source level in worker-boot.test.ts, next to the existing boot-call checks: exactly one construction, in server.ts, and the worker passes that instance rather than building its own. - `realProduceSolve`'s real `wireAbort` bridging and its post-prompt abort guard were exercised only by the Kind smoke — every unit test injects a `produceSolve` fake, so deleting either passed the suite. One test on the real producer now cancels mid-prompt and asserts the session was aborted and no partial patch was captured. Reaching it needed the pi mock to spread the real module (`getAgentDir`, `SettingsManager`), which also stops the existing opt-in-path test from halting earlier than its comment claims. - ADR-0047 and the design spec said a turn's `caps.tokens` "overrides" the deployment default. It cannot: `resolveBudgetLimit` takes the tighter of the two, so a turn cap can only narrow `SH_BUDGET_TOKENS`. Also corrects the changelog version the spec cites (1.27.0 -> 1.30.0). Verified: harness 943 passed (one pre-existing macOS-only failure in context-overlay.test.ts, present on a clean tree), @moca/server 602 passed including async-drain against real Redis, typecheck and lint clean. Both abort-coverage negative controls confirmed failing before the fix. Refs rossoctl#391 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.
Summary
All items from the previous rounds are closed at this head, and our b39f2e9 CHANGES_REQUESTED items remain fixed.
The head adds one own commit, af9e1af2 ("fix(391): PR #856 review — defer hand-back, counter wiring, abort coverage"), on top of a clean merge of current main (4126d4ff; git show --remerge-diff is empty, no hand resolution). The fix commit closes all five of clawgenti's a9c4b068 items, each with a test:
- the fairness hand-back (
queue.defer) is now inside atry/catch, logs the lost attempt refund, and still returnsdeferred(new test drives a throwingdefer); - one
SubjectCounterper worker is pinned at source level (worker-boot.test.ts: exactly onenew SubjectCounter(inserver.ts, andworker.tspasses that instance toarmAsyncLeafWorker); - the real
wireAbortbridging and post-prompt abort guard now have a unit test on the realrealProduceSolve(cancel mid-prompt, no diff capture); - ADR-0047 and the spec now say a turn's
caps.tokenscan only narrowSH_BUDGET_TOKENS, never raise it (resolveBudgetLimit=Math.min); - the spec's CHANGELOG citation is corrected from 1.27.0 to 1.30.0.
The author's replies at this head (2026-11-18 14:37–14:39 UTC) answer every open thread from this round — our four, clawgenti's five, and pdettori's two — and were spot-checked against the code: cap() now requires Number.isSafeInteger; mocactl TurnStatus gained cancelRequested with the stale cancelTurn/result docs corrected; the watchdog has its own setTimer/clearTimer seam; the harness OpenAPI is rewrapped under 96 chars; and the CHANGELOG, sizing doc, supervisor.env.example, spec §7 and deploy/k8s/README.md now state the mixed-load-only fairness bound and read async_reclaims net of async_deferred_subject. caps/turnExp are documented as per-delivery, with the cap × delivery-limit aggregate stated explicitly.
pdettori's 19a3071 must-fix (version collision + conflicts) is also resolved: control plane 1.30.0 / harness 1.6.0 against main 1.29.0, and the branch is mergeable: true with no conflicts. The nine inline findings from our b39f2e9 round (min budget limit, cancel/claim CAS, cancelRequested only on running, pre-claim cancel check, safe-integer caps, owner-checked defer, mocactl 202, summed metric test, mixed-load fairness wording) still verify against the head.
One carried suggestion inline: the defer ceiling is measured from the entry's enqueue time, not its first defer, so an aged backlog skips fairness on its first refusal.
pdettori's CHANGES_REQUESTED at 19a3071 still formally blocks and needs their re-review; our APPROVE clears ours. CI is 17/17 green.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (harness, server, control-plane, work-queue, supervisor, mocactl), OpenAPI x2, CHANGELOG, change-policy, spec/ADR, deploy docs
Agent/IDE config (.claude/.vscode): none
Commits: 12; 11 signed off (the unsigned one is the main-merge commit), DCO passes
CI status: 17/17 green
Drafted by an AI reviewer and approved by a human before posting.
| * above costs no extra read. An id that does not parse reads as age 0, i.e. keep pacing it: the | ||
| * fairness cap is the behaviour worth preserving when the clock is unknowable. | ||
| */ | ||
| function entryAgeMs(entryId: string): number { |
There was a problem hiding this comment.
suggestion: entryAgeMs reads the stream id, so the ceiling measures time since enqueue, not since the first defer. An entry that sat in the queue for more than ten minutes before any worker reached it skips fairness on its very first refusal — and a deep backlog, the case the defer exists for, is exactly that. Suggest measuring from the first defer (a first-deferred timestamp kept beside the entry), or documenting this as a queue-age ceiling in sizing-and-scaling/README next to the mixed-load wording. Minor: the id carries Redis server time while Date.now() is the worker's, so skew between them shifts the ceiling.
Brings 15 upstream merges since 2eb0219, among them the R2 host sampler in its reviewed form (rossoctl#904), the workspace-reset marker (rossoctl#895), turn budgets and cancel (rossoctl#856), the egress allow-all option (rossoctl#886), the sbx installer token (rossoctl#888), and the docs site with the product-name prose (rossoctl#884, rossoctl#885, rossoctl#899). One conflict, deploy/sbx/template-onboarding/README.md: upstream's product-name wording for the deploy/sbx table, keeping the fork's mint-login.sh row. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Summary
Two of #391's four acceptance criteria — "a turn over its token cap ends
failed: budget" and"cancel releases the sandbox within 10 s" — plus the per-worker half of per-subject fairness. The
first two turn out to be one piece of plumbing:
capswas already validated at submission, storedon the turn record and carried on the dequeue wire; the worker simply dropped it. Part of epic #686
(P6 async fan-out), milestone M1's last owed containment. #391 stays open for the cluster-wide
half of fairness (see below).
Per-turn caps and cancel
caps.costUsdis refused at submission (400 invalid_request). There is noprice table anywhere in the runtime, so accepting the field promised an enforcement that never
happened. A narrowing, taken while
/v1is Preview — per-turn cost attribution and the pricetable it needs are split out as Per-turn cost attribution: a price table, and caps.costUsd enforced instead of refused #859.
DELETEon arunningturn setscancelRequestedand leaves the state atrunning, answering202. The state deliberately does not move, because every redelivery CAS iswritten against the open states.
409now means only "already terminal".caps.tokensrides ontoTurnConfig.budgetTokens,turnExponto the claim. A 2 swatchdog on the existing heartbeat seam aborts the leaf when the cancel flag is set or
turnExphas passed. No control-plane-to-worker transport was needed: both sides already share one Redis
keyspace, so the
DELETEwrites a flag the worker polls.runLeaftakes anAbortSignal. A deadline abort reportsfailed: budget; anyother abort reports
aborted, whichasyncFinalizeStatealready maps to the record statecancelled. An aborted solve returns no partial patch assolved.budgetVoterExtensiongainsonExceeded— the only outward signal that it blocked, since pireports
end_turnonce every tool call is blocked.Per-subject fairness
An owner's queued leaves are now paced against the same per-subject budget as their interactive
turns, so an owner whose fan-out is running cannot also fill the worker with
/turns. The queue isone FIFO stream, so an entry's owner is unknowable until it is claimed — which makes this a
check-and-hand-back rather than a filter on the read:
owner(one HGET, newTurnStore.owner) and, when thatowner already holds
SH_TURNS_PER_SUBJECTof this worker's slots, hands the entry back unrun andbacks off as it does on an empty queue. The counter is the same
SubjectCounterinstance thesync
/turnroute holds; two counters would let one subject hold 2× its cap.credential, does not flip to
runningand writes no audit issuance. The slot is released in onefinallyaround the whole run, which is why the run moved into its own function.XCLAIM … JUSTID RETRYCOUNT <before this delivery>(newWorkQueue.defer),not an
XACKplus re-XADD: it keeps the entry in the PEL so nothing can lose it, and leaves thedelivery counter where it was, so a defer is invisible to
maxAttempts. Without that, an owner attheir cap would have their own turns dead-lettered for having been deferred three times — a
refusal dressed up as a failure. (
WorkQueuealso deliberately exposes noenqueueto consumers.)async_deferred_subjectjoins §7's counters, plumbed through the worker stats row to theadmin
/metrics. Counted separately fromasync_claims, because a defer read an entry and put itstraight back: counting it as a claim would show throughput rising while the queue made no
progress.
What this is not (review must-fix 1, recorded in spec §12, ADR-0047 and every operator doc that
mentions the knob):
SubjectCounteris per worker and in-process, and a worker runs one queued leafat a time, so the cap
max(1, ⌊S/2⌋)is never reached by the drain alone. It paces an owner'smixed load, not an async-only drain — one owner's deep backlog is still served FIFO ahead of
another owner's single turn. Binding that needs a cluster-wide per-owner count (per-owner streams,
or a count checked at the dequeue exchange), which no in-process counter can provide; #391's fourth
criterion stays open for it. The two-owner integration test pins the shipped guarantee: the owner at
their cap has entries deferred unrun and unpenalised while the other owner's later turn is claimed
and run, and the backlog drains once the first owner's slot comes back.
Known limit, recorded in spec §12 and ADR-0047: the defer resets the entry's idle timer, so a
deferred turn waits up to
minIdleMs(90 s) before any worker may reclaim it. Leaving IDLE highinstead would have this worker's own next claim reclaim the same entry (XAUTOCLAIM leads every
claim), defer it again, and never reach the entries behind it — the starvation the defer exists to
prevent. Per-owner streams are the upgrade.
Docs
Control-plane API 1.30.0, harness API 1.6.0 (renumbered twice while in review, as main shipped
#779 and #510, then #716 took 1.29.0), and the spec/ADR amendments striking one owed item —
"cancelling a running leaf needs new machinery" (that machinery was never needed) — and recording
per-subject fairness as partly done and still owed. ADR-0047's status header also still said M2 was
owed while its own milestones section described M2 in the past tense; #822 shipped it. The stale
"a running leaf is not interrupted (409)" step in
docs/concepts/dispatch-archetypes.mdis correctedtoo.
Still owed on #391
The cluster-wide half of per-subject fairness, as above. Per-turn cost attribution is tracked
separately as #859, which wants a per-model price table that does not exist (the same reason
costUsdis refused above rather than enforced).Assisted-By: Claude Code