Skip to content

feat: per-turn token and wall-clock caps, cancel for a running async turn, and per-subject fairness (#391) - #856

Merged
cwiklik merged 12 commits into
rossoctl:mainfrom
cwiklik:feat/391-turn-budgets-cancel
Nov 18, 2026
Merged

cwiklik merged 12 commits into
rossoctl:mainfrom
cwiklik:feat/391-turn-budgets-cancel

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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: caps was already validated at submission, stored
on 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

  • Control plane: caps.costUsd is refused at submission (400 invalid_request). There is no
    price table anywhere in the runtime, so accepting the field promised an enforcement that never
    happened. A narrowing, taken while /v1 is Preview — per-turn cost attribution and the price
    table it needs are split out as Per-turn cost attribution: a price table, and caps.costUsd enforced instead of refused #859.
  • Control plane: DELETE on a running turn sets cancelRequested and leaves the state at
    running, answering 202. The state deliberately does not move, because every redelivery CAS is
    written against the open states. 409 now means only "already terminal".
  • Worker: caps.tokens rides onto TurnConfig.budgetTokens, 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 was needed: both sides already share one Redis
    keyspace, so the DELETE writes a flag the worker polls.
  • 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.

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 is
one 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:

  • The worker reads the claimed entry's owner (one HGET, new TurnStore.owner) 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. The counter is the same SubjectCounter instance the
    sync /turn route holds; two counters would let one subject hold 2× its cap.
  • 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, which is why the run moved into its own function.
  • The hand-back is XCLAIM … JUSTID RETRYCOUNT <before this delivery> (new WorkQueue.defer),
    not an XACK plus 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.)
  • async_deferred_subject joins §7's counters, plumbed through the worker stats row to the
    admin /metrics. 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.

What this is not (review must-fix 1, recorded in spec §12, ADR-0047 and every operator doc that
mentions the knob): SubjectCounter is per worker and in-process, and a worker runs one queued leaf
at a time, so the cap max(1, ⌊S/2⌋) is never reached by the drain alone. It paces an owner's
mixed 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 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.

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.md is corrected
too.

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
costUsd is refused above rather than enforced).

Assisted-By: Claude Code

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]>
@cwiklik
cwiklik requested a review from pdettori as a code owner November 17, 2026 16:30
@cwiklik cwiklik added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 17, 2026
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]>
@cwiklik cwiklik changed the title feat: per-turn token and wall-clock caps, and cancel for a running async turn (#391) feat: per-turn token and wall-clock caps, cancel for a running async turn, and per-subject fairness (#391) Nov 17, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-43 and deploy/vm/env/supervisor.env.example:22-25 say 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.

Comment thread harness/src/run-turn.ts Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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".

Comment thread harness/src/leaf-job-runner.ts Outdated
// 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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/work-queue/src/queue.ts Outdated
// 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], {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. */

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 typecheck after 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') → getTurn printed FINAL 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 } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cwiklik

cwiklik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

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.

SubjectCounter is per worker and in-process, and a worker runs one queued leaf at a time, so the cap max(1, ⌊S/2⌋) is never reached by the drain alone. What it binds is an owner's mixed load — their interactive turns and their queued leaves share one budget, so an owner whose leaves are running cannot also fill the worker with /turns. What it does not bind is 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.

Reworded in spec §12, docs/api/CHANGELOG.md, docs/operations/sizing-and-scaling.md, docs/reference/configuration.md (SH_TURNS_PER_SUBJECT), deploy/vm/README.md, deploy/k8s/README.md and ADR-0047, plus a shortcut: comment at the check itself. #391's fourth criterion stays open for the cluster-wide half.

New test, packages/server/test/async-drain.integration.test.ts (real Redis, real stream, the production admitOwner wiring): owner A's three older entries are deferred unrun and unpenalised (state: queued, attempts: 0, no credential minted) while owner B's later turn is claimed and runs first, and A's backlog drains once their interactive slot is released.

Must-fix 2 — caps.tokens could raise the deployment cap. resolveBudgetLimit now treats it as a ceiling only: it can narrow SH_BUDGET_TOKENS, never raise it.

Suggestion A — a cancel that races a claim was refused. cancel() is two-pass: queued → cancelled, running → a cancel request with the state left running, so every redelivery CAS against OPEN_STATES still wins. The 409 reports the turn's fresh state rather than the one read before the race.

Suggestion B — cancelRequested reported forever. The status projection gates on the state, not the flag: the flag is never cleared (the record is kept for the status read's TTL), so a leaf that finished before noticing the cancel would otherwise read done plus cancelRequested: true for the rest of that TTL.

Suggestion C — an already-aborted signal still started work. runLeaf checks the signal before the kind dispatch, so a reclaimed delivery whose deadline has already passed leases nothing and finalizes failed: budget through the ordinary path. The drain also honours an existing cancel flag before admitOwner and claimTurn: a turn that must not run mints no credential, writes no issuance to the audit log, takes no fairness slot and leases no sandbox.

Nits. 1: caps.{tokens,wallClock} must be positive safe integers. 2: defer() and touch() share one owner-checked Lua script, so a defer cannot steal an entry back from the consumer that reclaimed it. 3: cancelTurn returns the 202 body as CancelledTurn, and TurnStatus carries cancelRequested. 4: /metrics sums async_deferred_subject across workers.

Also corrected the stale "a running leaf is not interrupted (409 turn_not_cancellable)" step in docs/concepts/dispatch-archetypes.md.

Verification. make typecheck and SKIP=hadolint-docker make lint clean; packages/server 592/592; control-plane, work-queue and harness green apart from three pre-existing environment failures on files this branch does not touch (context-overlay.test.ts — macOS mv into a chmod a-w directory; real-worker.integration.test.ts — tsx missing at the worktree root; and mocactl 5 s timeouts under full parallel load, all of which pass in smaller batches, with no assertion failures). The live end-to-end cancel-timing and budget checks still need Docker, which is down on this machine.

Follow-ups, not in this PR. The cluster-wide half of per-subject fairness (#391 stays open); a mocactl cancel command (cancelTurn has no CLI caller yet — belongs with #381); the frame-level async transcript owed from #390's review.

Note: #856 and #861 both edit spec §12 and docs/concepts/dispatch-archetypes.md, so whichever merges second needs a small conflict resolution.

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 clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread harness/src/run-leaf.ts
return [
budgetVoterExtension(sessionManager, {
limit,
baseline: branchSpend(sessionManager) ?? 0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread harness/src/leaf-job-runner.ts Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/server/src/turn-claim.ts Outdated
* 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cwiklik

cwiklik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Merged main in (0ebeab8f); the PR is mergeable again.

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 change-policy.md's version list, and decision 5's literal updated — 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 (21 + 9), make typecheck, make lint, control-plane 1989, server 599, harness 939 — the single harness failure is the pre-existing macOS-only context-overlay case, which CI passes.

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]>

@clawgenti clawgenti left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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."

Comment thread packages/server/src/turn-claim.ts Outdated
// 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 } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 =

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: docs/api/harness-openapi.yaml:211-222 is rewrapped at <=96 characters, matching the descriptions around it.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cwiklik

cwiklik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Second review round addressed in 462c7987. Point by point:

  1. caps are per delivery, and nothing said so. Added to the openapi caps schema description, the 1.29.0 changelog bullet, and a comment above budgetVoters' baseline in run-leaf.ts: a worker that dies mid-leaf has its turn redelivered and the retry gets a fresh token budget and a wall clock anchored at its own dequeue — a retry must not fail on its predecessor's spend — so the aggregate across a turn's three deliveries can reach 3× the cap. Sized as a per-attempt ceiling, documented as one.

  2. An unbounded defer could starve an owner forever. Correct, and it was the worst kind of starvation: never run, never dead-lettered, and turnExp never starting because it is anchored at a dequeue that never comes (the defer also refunds the attempt budget, so nothing bounded the loop). Added DEFER_CEILING_MS = 600_000, measured from the entry's own Redis stream id — the id's millisecond part is the enqueue time, so this needed no new metric and no new Redis call. Past the ceiling the entry runs one leaf over its owner's share and logs that it did; async_deferred_subject counts defers in aggregate and cannot distinguish "paced for 90 s" from "waiting since this morning", so the log line is the one trace a starving owner leaves. SH_TURNS_PER_WORKER still caps the worker. Two tests: runs-past-ceiling, and keeps-deferring-below-it. Spec §12 records the ceiling.

  3. An unusable caps.tokens / turnExp was dropped silently. Now logged. Still coerced rather than refused — both were validated at submission, so an odd value means a control plane older or newer than this worker, and refusing makes the turn unrunnable, which is a worse answer to a version skew. But degrading enforcement with no trace meant an operator met it as a turn that over-ran its cap. Absent still says nothing (that's most turns). Test asserts both names appear and that a bare caps warns nothing.

  4. Why a failed pre-claim cancel poll reads as "no cancel". Documented at the catch: 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. Turning the catch into a refusal would make a blip strand a turn nobody asked to cancel.

  5. Coercion hoisted beside the value it guards, so the two cannot diverge.

  6. cancel()'s retry loop — pushing back on this one. Two CAS passes are enough and a third would be wrong, not just redundant: CAS_STATE_LUA returns 0 only when the state is outside the allowed set or the record is gone, and TurnStore.guard() maps every transport failure to a thrown CpError('redis_unavailable') — it never produces a false CAS failure. The sole transition out of running is a terminal one, so falling out of the loop is an honest conflict, not a lost race, and a third pass would re-read a turn that is already final. The 409's message is built from a fresh read for the same reason. Added that as a comment inside the existing doc; no behaviour change. Happy to revisit if you see a path where guard() lets a transport error through as a 0.

  7. setHb/clearHb renamed to setTimer/clearTimer — the watchdog shares the seam, so the heartbeat name was misleading. No production caller existed; only tests used it.

  8. Harness 429 subject_quota_exceeded description rewrapped.

Not run locally: packages/server/test/async-drain.integration.test.ts (real Redis) and the Kind e2e — no redis-cli or Docker on this machine — so CI is the first place the defer ceiling meets a real stream.

Assisted-By: Claude Code

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread docs/api/openapi.yaml Outdated
info:
title: MOCA control plane
version: 1.28.0
version: 1.29.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_reclaims is "XAUTOCLAIM firing. Read net of async_deferred_subject (below)", and §7 states outright that neither counter alone is the dying-worker signal.
  • deploy/k8s/README.md:1351-1356: async_deferred_subject rising 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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cwiklik

cwiklik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Also rebased-by-merge onto upstream/main (aea71cf2), which had moved again: #716 took control plane 1.29.0, so this branch's contract is now 1.30.0 (data plane 1.6.0 ships with it). CHANGELOG section renumbered, change-policy's two version mentions bumped, and configuration.md keeps upstream's two new rows (SH_OIDC_MAX_PENDING_PER_SOURCE, SH_TRUSTED_PROXY_HOPS) alongside this branch's MOCA_TURN_MAX_S text. Green locally: make typecheck, make lint, the contract test (21), and the full control-plane suite (2001).

MERGEABLE again.

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]>
@cwiklik

cwiklik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@pdettori all three addressed — the must-fix in aea71cf2, the two suggestions in a9c4b068.

must-fix, version collision. Merged main and renumbered to 1.30.0: openapi version, the CHANGELOG heading (#716's 1.29.0 now sits below it), the data-plane table row (1.6.0 ships with 1.30.0), both change-policy mentions, and the PR body. configuration.md resolved as main's two new rows (SH_OIDC_MAX_PENDING_PER_SOURCE, SH_TRUSTED_PROXY_HOPS) plus this branch's MOCA_TURN_MAX_S text. MERGEABLE.

async_reclaims double-counts defers. You're right, and I took the documenting option because keeping the two signals apart isn't available: a hand-back and a crash come back on the same XAUTOCLAIM with the same delivery count — the defer's RETRYCOUNT: n - 1 is exactly what the reclaim re-increments — so the drain has nothing to discriminate on without new per-entry state. Now stated in four places: spec §7's table row and the prose beside async_deferred_subject, deploy/k8s/README.md's watch table and the paragraph under it, and the two code sites that quoted the old reading (async-worker.ts's counter, leaf-job-runner.ts's outcome doc). The rule is async_reclaims net of async_deferred_subject is the dying-worker signal.

turnExp restarts on every redelivery. Also right, and deliberate — documented rather than changed, same as the caps.tokens thread, which the previous round already settled as per-delivery in the openapi caps schema and the changelog. Anchoring once is the worse branch: the grants are minted from turnExp, so a reclaimed delivery would be handed credentials that expire the instant they are issued — a turn that cannot be retried at all rather than one that may run long after a worker died. So turnExp's own description now says "the absolute end of THIS DELIVERY" and why, spec §5.4 says dequeue means each dequeue and names the aggregate (cap × maxAttempts), and the anchor in turn-exchange.ts carries the same note. Your point about the already-past-deadline short-circuit being reachable only through clock skew stands and that is what it is there for.

Green locally: make lint, make typecheck, contract + turn-exchange (57), async-worker + turn-claim (73), leaf-job-runner (33), full control-plane suite (2001) after the merge.

Assisted-By: Claude Code

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The spec's §4.3 amendment cites docs/api/CHANGELOG.md 1.27.0 for the costUsd refusal, but the entry lands in 1.30.0 in this PR.
  2. The spec and ADR-0047 amendment say a turn's own cap "overrides" SH_BUDGET_TOKENS, but resolveBudgetLimit takes Math.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.
  3. The shared-SubjectCounter wiring — 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (resolveBudgetLimit takes 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 (resolveBudgetLimit takes 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 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in af9e1af, at source level — packages/server/test/worker-boot.test.ts, next to the existing prepareServerProcess boot-call checks:

  • server.ts contains exactly one new SubjectCounter(, exported as subjectCounter, and the sync route acquires on that identifier;
  • worker.ts is matched against the whole argument object, armAsyncLeafWorker({ counter: runtime.counter, subjects: subjectCounter }), plus a not.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.

Comment thread harness/src/leaf-job-runner.ts Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread harness/src/run-leaf.ts
});

// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cwiklik cwiklik Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(duplicate of the reply above — posted twice by mistake)

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cwiklik added a commit to cwiklik/moca that referenced this pull request Nov 18, 2026
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 ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 a try/catch, logs the lost attempt refund, and still returns deferred (new test drives a throwing defer);
  • one SubjectCounter per worker is pinned at source level (worker-boot.test.ts: exactly one new SubjectCounter( in server.ts, and worker.ts passes that instance to armAsyncLeafWorker);
  • the real wireAbort bridging and post-prompt abort guard now have a unit test on the real realProduceSolve (cancel mid-prompt, no diff capture);
  • ADR-0047 and the spec now say a turn's caps.tokens can only narrow SH_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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@cwiklik
cwiklik merged commit aeff414 into rossoctl:main Nov 18, 2026
17 checks passed
webchang added a commit to webchang/moca that referenced this pull request Nov 19, 2026
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]>
@pdettori pdettori added this to the v0.11.0 milestone Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants