Repository navigation
feat(knative-server): async leaf worker on P6 (#389 M1) - #717
Conversation
…t key Amends the P6.4 async fan-out spec to v1.7. A new §9.2 records the six questions that building rossoctl#389's drain loop surfaced against the sections above, five of them choices and one a correction. The correction is §5.5's "keyed by leafSessionId". The async path writes leaf:result:<tenant>-<uuid> (run-leaf.ts leafSessionId prefixes the tenant then sanitizes) where the control plane reads leaf:result:<uuid> (turn-result.ts leafResultKey, called with the raw turn.sessionId). Because ownership.ts falls back to `tenant: h.tenant ?? h.owner`, the tenant is never empty, so this fires on every async turn rather than only a tenanted one -- which makes it blocking for M1's acceptance rather than a cleanup. §5.5 and §10 now carry pointers to §9.2 beside the text they qualify, so a reader who finds the original claim first also finds its correction. §10's "restore from 38aa214" is qualified for the same reason: the queue's wire format changed under it when rossoctl#387 shipped RedisTurnQueue, so a literal restore would JSON.parse(undefined) on every {turnId} entry. Refs rossoctl#389 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ient Restores packages/work-queue, removed by rossoctl#691, as the consumer half of the async fan-out path (spec §10). The Redis Streams calls are the ones from 38aa214 unchanged -- XAUTOCLAIM-then-XREADGROUP, the BUSYGROUP swallow, XCLAIMJUSTID for the heartbeat touch, the bounded XPENDING reap -- because re-deriving them would re-derive their bugs. Three things are deliberately not a verbatim restore (spec §9.2): - The entry payload is `{turnId}`, not a JSON envelope. rossoctl#387's RedisTurnQueue already writes `{turnId}` and rossoctl#388's e2e test pins an entry's fields to exactly ['turnId'], so the old `JSON.parse(msg.message.envelope)` would throw on every entry. - The client is injected. The old class owned a createClient, a reconnect strategy, an error listener and an inline redactUrl copy, all four of which duplicate @moca/session-backend's resilientClientOptions/swallowRedisErrors. - There is no `enqueue`. RedisTurnQueue is the only submitter; this interface is its mirror, for the reason turn-queue.ts already gives in the other direction. The four connection-boilerplate test files from 38aa214 are not restored either: they test the owned client this commit removes. `depth()` is new, and is §7's two deployment-wide gauges read together so they describe one instant: XINFO GROUPS' lag, and the age of the first entry after last-delivered-id. It computes "now" via the Redis TIME command rather than Date.now(): this sandbox's Redis container runs with a clock measurably ahead of the test host's, and comparing a stream id (minted from the Redis server's clock) against the test process's own clock turned that skew into a negative, floored-to-zero age -- a real bug class (containerized Redis vs. host clock drift) a deployment should not be newly exposed to either. Also runs `pnpm approve-builds --all` for esbuild/protobufjs: pnpm-workspace.yaml had an unstaged, unfinished allowBuilds stanza (literal placeholder text, not a boolean) left over in this worktree, which made every `pnpm install` -- including the one `make lint`'s prettier hook shells out to -- exit 1 before touching a single file. Resolving it to explicit `true`/`true` is what let prettier, and this commit, run at all. Verified: queue.test.ts 11 passed against Redis 6379 (stable across repeated runs); tsc --noEmit clean; make lint clean except a pre-existing, unrelated check-yaml failure on docs/api/openapi.yaml. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Restores harness/src/leaf-job-runner.ts, removed by rossoctl#691. The 30s touch heartbeat, the injectable timers and classifyOutcome as the single ack-vs-redeliver decision point are unchanged. Four things are not: - The return is a discriminated union carrying turnId and `reclaimed`. The old string union was built for a KEDA pod that ran processOne once and exited; a long-lived loop needs the turn id for its log line, `reclaimed` for async_reclaims, and it must tell "nothing to claim" apart from "claimed something I may not run". - The envelope arrives from an injected `claimTurn`, because the queue entry is now a turn id and the envelope comes from the credential exchange. - The dead-letter path is its own injected dep, so a turn that will never run never causes a credential to be minted or an issuance to be audited. - Async results are written under the TURN RECORD's session id. That last one is the §9.2 result-key fix. leafSessionId() tenant-prefixes then sanitizes (run-leaf.ts:183-185); the control plane reads `leaf:result:${turn.sessionId}` raw (turn-result.ts:13); and a record's tenant is never empty (ownership.ts:208, `h.tenant ?? h.owner`). So every async result was written to a key no reader looks at. Session ids are randomUUIDs and toSessionId is the identity function on those, so the tenant prefix was the whole divergence. Sync leaves keep leafSessionId: their callers compute the key the same way, and breaking a working path to fix a broken one is not a fix. Result-write, then finalize, then ack, so a reader that sees a terminal record can always fetch its result. Verified: leaf-job-runner.test.ts 15 passed (no Redis -- fake queue, Map store, injected timers); tsc --noEmit clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Review found that leaf-job-runner.test.ts's "completes a non-retryable failure" test asserted on reason: 'budget', which is not a member of LeafResult's failed-reason union (run-leaf.ts) and appears nowhere else in the repo. The previous `as unknown as LeafResult` double-cast made this compile by decoupling the test from the real type, which would let the test keep passing (asserting the wrong thing) if a future M2 budget reason were added with retryable semantics. Switched to reason: 'bad_inputs', a genuine deterministic failure that exercises the same classifyOutcome branch (not 'error'/'saturated', so non-retryable), with a single ordinary cast matching the sibling test at line 181. Verified: harness/node_modules/.bin/vitest run test/leaf-job-runner.test.ts -> 15 passed, no Errors in log. make typecheck -> exit 0, clean across all workspaces. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Settles the first of rossoctl#388's two deferred decisions (spec §9.2): the envelope travels in the /internal/turn-credentials response. The alternative was a second internal route to fetch it, which would make the dequeue path two round trips for data the first handler has already loaded -- on a route whose own contract is "the id alone is sufficient because everything else comes from the turn record". parseTurnSubmission deliberately stores no sessionId in the envelope, while LeafEnvelope.sessionId is required, so the response attaches the record's. Spread last, so a stored envelope cannot override it. rossoctl#388's other deferred decision stays deferred: pinning sandboxTier and model to the record is M2/rossoctl#388 work, for the reason turn-exchange.ts:160-168 already gives. Also exports what the worker's drain loop needs: TurnStore, the turn-record types, the queue name constants and asyncCounters. index-exports.test.ts pins them, because a rename that drops LEAF_QUEUE_STREAM is not a compile error in the submitter -- it is a worker draining a stream nobody writes to. openapi.yaml and the 1.3.0 changelog entry updated; the new required field is pinned by openapi-contract.test.ts. Also quotes a pre-existing unquoted `host:port` description value in openapi.yaml (ExecGrant.execEndpoint) that check-yaml's stricter flow-scalar parsing rejects -- latent since the field was added, surfaced only because this commit is the first since to touch the file through a working `pre-commit install`. Verified: full control-plane suite green (1164 passed, 3 skipped); tsc clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
§5.4: present the turn id, get the credential and the envelope, then flip the record queued->running with `attempts` from the queue's delivery count, then run the leaf with the grants. The state write is LOCAL, through TurnStore, and there is no new internal write route. turn-exchange.ts gives the reason: SH_EXCHANGE_TOKEN is one deployment-wide secret, so a write behind it would let any holder flip an arbitrary turn out of `queued` -- and, since cancel accepts `queued` only, make a caller's own turn permanently uncancellable. Exchange first, markRunning second. markRunning re-checks terminality, so a DELETE landing between them is refused there and nothing is stranded. null vs throw is the load-bearing distinction: `turn_not_found` and `turn_not_claimable` mean this turn must not run, so the caller acks; every other failure means the CALL failed, so the entry stays pending for another worker. Known M1 limit: that makes a control-plane outage longer than three reclaim cycles (~4.5 min) dead-letter queued turns as `lost`. maxAttempts and minIdleMs are §6.2 fixed constants and §9.2 allows one operator knob, which SH_ASYNC_DRAIN spends; a `lost` turn is visible on the record and counted. deadLetterTurn is separate and mints nothing: the branch needs only the record's session id, and routing it through the exchange would issue and audit a real credential for a turn that will never run. turn-auth.ts's post-200 validation is extracted to an exported validateExchangeBody rather than copied -- those six checks are what keep a placeholder from being spent as a credential and a secret from reaching the wrong endpoint, and two copies would be two places to forget the seventh. turn-auth.test.ts is green unedited. Caps are deliberately not enforced here: not in M1's scope, and TurnConfig carries no budget field to enforce them through. Verified: turn-claim.test.ts 23 passed, turn-auth.test.ts unchanged and green; tsc clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…on_not_found gaps Fix round 1 on rossoctl#389 task 4, per review (COMPLIANT on spec, CHANGES REQUESTED on quality). Four of the five findings were defects in the brief's own code; this commit implements the adjudicated rulings. Must-fix (R13): claimTurn put the exchange's configRef only on auth.configRef, which buildConfig never reads -- runLeaf reads configRef off the LEAF ENVELOPE. So an async leaf ran without the session's promoted CLAUDE.md/MCP/ agent config while a sync /turn on the same session got all of it. Fixed by merging configRef into the returned envelope, same spread shape as the sync path (server.ts), control-plane value last. Must-fix (R14): deadLetterTurn only checked `!rec`, but a terminal record outlives its result (turn-store's TTL margin). On a last-delivery SIGKILL after a leaf's result was written and finalized but before the queue ack, the reclaimed entry would dead-letter anyway and overwrite a correct `done` result with `failed/error`. Fixed by also skipping already-terminal records (isTerminalState), which also protects the periodic reaper this function must be safe for. Should-fix (R15): turn-exchange.ts throws `session_not_found` for an unknown session, an owner mismatch, or a tombstoned session -- all three permanent, unlike `redis_unavailable` for a transient failure. Treating it as a call failure burned three deliveries (~4.5 min) before dead-lettering a turn whose answer could never change. Added to NOT_CLAIMABLE. Should-fix (R16): added coverage for markRunning rejecting -- claimTurn must reject, not resolve to null, or a future change that swallowed the failure would permanently drop a runnable turn while looking like a clean refusal. No pre-exchange turns.get read added (declined): the wasted-mint window on a cancel-during-claim race stays the documented M1 limit. Should-fix (S1): hardened the credential-leak coverage -- a suite-wide console spy (error/warn/log/info/debug) asserting no call argument contains the credential, JSON.stringify(err) checks (not just .message) on every post-200 throw path so a future four-arg CpError with the body in `extra` would be caught, and an exact pin on markRunning's call arguments. Fixtures now use a distinctive sentinel secret instead of 'sk-secret'. Verified: turn-claim.test.ts + turn-auth.test.ts, 95 passed, grepped for Errors (none); tsc clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
§5.3: an async leaf occupies the SAME TurnCounter slot a sync /turn does. Otherwise a worker runs SH_TURNS_PER_WORKER HTTP turns plus unbounded queue work, and the load number the supervisor balances on is fiction. The cap check and counter.start() are one synchronous tick, with nothing awaited between them. Taking the slot before claiming costs a real thing: claim ends in XREADGROUP BLOCK 5000, so for up to 5 s the worker reports a slot busy that runs nothing. The supervisor's reconciler already names and counts that (pool.ts, spurious_refusals). Claiming first and checking after would either drop a claimed entry or hold it unacked past its idle timeout, and both are worse. stop() does not await the in-flight leaf -- MOCA_TURN_MAX_S is specified at 1800 s against a 20 s SHUTDOWN_GRACE_MS, so waiting could only time out -- and releases the slot so the supervisor's awaitIdle exits early. Releasing from both stop() and the finally is correct only because start()'s end function is idempotent (worker.ts). stop() deliberately does NOT delete the consumer: XGROUP DELCONSUMER DISCARDS that consumer's pending entries, which would turn the single redelivery §6.3 relies on into silent loss. The abandoned leaf is reclaimed after minIdleMs because the heartbeat dies with the process. Arming is conservative and off by default: SH_ASYNC_DRAIN (§9.2's one operator knob) plus both control-plane settings, and never under MOCA_TENANCY=multi, which answers async_tenancy_unsupported. A knob set with the rest missing logs the missing name and stays unarmed rather than exiting -- the same process is serving healthy sync traffic. No backoff after an idle claim: the BLOCK inside claim is the backoff. A thrown claim does back off, so a control-plane outage is a slow retry rather than a hot loop against a struggling service. Each loop iteration also yields one real event-loop turn (setImmediate), independent of deps.sleep. Only a test double resolves processOne/sleep instantly; without this yield that turns the loop into an unbroken chain of microtasks that starves every macrotask -- including the test's own timers -- forever. Confirmed by reproducing the hang in isolation before adding the fix. Production's real queue.claim() always costs a real I/O turn, so this never fires there. Verified: leaf-drain-loop.test.ts 33 passed, no vitest Errors; tsc clean; make typecheck clean across the workspace. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Review fix round 1 on the leaf drain loop (M1, S1-S3).
M1 (must-fix): deps.counter.inFlight, deps.onCapDenied?.(), the cap
backoff sleep, and deps.counter.start() all sat outside the loop's
try/catch. Any of them throwing -- most plausibly Task 8's
onCapDenied, which emits async_claim_denied_full and can itself fail
-- rejected run()'s promise. A bare `void run()` let Node's default
--unhandled-rejections=throw end the worker process, taking down
healthy sync /turn traffic in the same process, which shouldArmAsync's
own doc explicitly forbids doing over a mere arming mistake. Wrapped
the whole iteration (both branches) in a try/catch that releases
whatever slot it holds, logs through deps.log, backs off with
errorBackoffMs, and loops -- a throwing monitoring callback now costs
one iteration, not the loop. Added a last-resort `.catch()` on
`void run()` itself, mirroring packages/supervisor/src/main.ts's
`route(socket).catch(...)`, for the residual case where the handler's
own log() call throws; it marks the loop stopped so `running` stops
lying, instead of leaving a dead loop reporting live.
Verified both ways, not just that a catch exists: reverted the
per-iteration try/catch and reran -- the new "survives a throwing
onCapDenied" test fails (processOneImpl never called again once the
slot frees); restored, and it passes, with processOneImpl invoked on
the later iteration.
S1 (should-fix): nothing enforced the Section 5.3 single-tick ordering
that is this task's reason for existing -- inserting an
`await Promise.resolve()` between the cap check and counter.start()
left all tests green. Added a decisive test: start() with cap 1 and a
leaf that never settles, then assert `counter.inFlight === 1` with NO
await in the test in between. Verified it fails
("expected +0 to be 1") against a build with that await inserted, and
passes against the real implementation.
S2 (should-fix): scripted()'s `{ kind: string } & Record<string,
unknown>` index signature disarmed excess-property checking for no
fixture's benefit, and let a typo'd fixture
(`status: 'donee', reclaimedd: false`) typecheck silently. Replaced it
with `Array<ProcessOutcome | Error>` against the real domain type.
Verified the typo now fails tsc (TS2322/TS2353 on the bad status and
the misspelled key) and that all fixtures still typecheck and the
suite stays green.
S3 (should-fix): the yield's comment and the previous commit message
both claimed it "never fires" in production. It is unconditional and
fires every iteration; what is true is that it never *matters*,
because every path reaching it has already awaited queue.claim's real
BLOCK or a real sleep. Reworded so a future reader profiling the
worker and seeing it fire does not conclude it is dead and delete it
-- the suite OOMs without it (round 0's finding), and in production a
microtask spin would wedge this process's HTTP hand-offs and IPC
drain messages too.
Deviation A (the unconditional setImmediate yield) and the
continue-to-else restructure from round 0 both confirmed correct by
review and left untouched. The pre-existing TurnCounter.start()
increment-before-onChange door (a process.send failure leaking a slot)
is out of this task's scope per the coordinator and is not touched
here.
Verified: leaf-drain-loop.test.ts 36 passed, no vitest Errors; tsc
clean; make typecheck clean across the workspace.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
server.ts:1277 serves a sync leaf on /runs, /run-leaf and /v1/runs, and all three reach the same runLeaf at server.ts:1105 as /turn does -- same agent work, same sandbox lease, same wall clock. TURN_PATHS held only /turn and /v1/turn, so none of the three took an admission slot: attachTurnSlot was never called, no `load` row was sent, and the supervisor handed a worker more work while it was mid-leaf. That was an over-admission on its own. It becomes worse with the async drain loop, which decides whether to claim by reading counter.inFlight (§5.3): a route missing from this set no longer just under-reports, it lets the loop claim against capacity that is already spent. /run-leaf is deprecated (server.ts:1201 maps it to /runs) but still served, so it still consumes a worker and still belongs here. The set is about what runs, not about what is recommended. Raw-target equality and the POST guard are both kept deliberately: server.ts compares the unparsed target, so /runs?x=1 is not a turn there and must not be one here, and GET /v1/turn (server.ts:1337) is a status read that must not take a slot. Also corrects the two stale server.ts:641 citations in the same comments. Verified: worker.test.ts green, full knative-server suite (31 files, 512 tests) green. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…idening accept()'s comment on the permanent-overcount bug listed POST /runs as an example of a non-turn request that "returns early there". Task 6 added /runs to TURN_PATHS, so that example now says the opposite of what is true: POST /runs takes a slot and does report load. Replaced it with GET /v1/turn, which stays genuinely uncounted and illustrates both halves of isTurnRequest's predicate -- it is in TURN_PATHS but excluded by the method === 'POST' guard, rather than just not being a turn path at all. The rest of the comment, including the overcount explanation, is unchanged. Checked the rest of this comment block and the isTurnRequest doc for other examples the widening could have falsified: /health and /turn references elsewhere are unaffected (neither is in TURN_PATHS, and the /turn mentions are either exact-match or the GET case), so no other claim needed fixing. Verified: full knative-server suite (31 files, 512 tests) still green, typecheck clean. No behaviour changed -- TURN_PATHS, raw-target equality, and the POST guard are all untouched. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
… hook The P6 turn worker now drains the leaf queue, sharing runtime.counter with sync /turn so one cap governs both (§5.3). Off unless SH_ASYNC_DRAIN and both control-plane settings are set: a deployment that never submits an async turn pays nothing. Two new Redis clients, and the split is not incidental. claim ends in XREADGROUP BLOCK 5000, and node-redis sends every command for a client over one socket -- so a TurnStore write sharing that client would wait out the idle poll. The queue gets a dedicated connection; records get a second; results reuse the sync path's existing store, because two stores in one process would be two connections and two TTLs for one key space. ensureGroup runs before the loop starts: XREADGROUP against a missing group errors rather than reading empty, so the other order logs NOGROUP until the submitter happens to create it. TURN_RECORD_TTL_MARGIN_SECONDS moves from control-plane/main.ts to the pure turn-record.ts and is exported. The worker finalizes turns now, and a record finalized by a worker must expire when one finalized by the control plane would; re-typing 3600 here would be a second source for one invariant. aborted maps to cancelled -- an aborted leaf stopped because something asked it to, and `lost` is for a turn that was delivered and never reported. The other five statuses are shared names and map to themselves. The reaper follows armRunReaper's shape exactly (sweep now, interval, unref'd timer) and is armed by every worker: XCLAIM-then-XACK is per-entry atomic and deadLetterTurn's finalize compare-and-sets, so concurrent sweeps are redundant rather than racy. The immediate sweep is load-bearing for the same reason it is there -- a worker restarted seconds after a crash would find the orphan's heartbeat not yet stale and never look again. Drain stops claiming at once and abandons the in-flight leaf unacked (§6.3). Waiting could not work: MOCA_TURN_MAX_S is 1800 s against a 20 s grace. @moca/work-queue is added as an explicit knative-server dependency: the async worker constructs RedisWorkQueue directly, which the package did not previously need. Also fixes the brief's example import -- runLeaf/LeafResult come from @moca/harness/run-leaf, not the package's top-level index, which does not re-export them. Verified: async-worker.test.ts 17 new tests pass (55 total with worker.test.ts), the whole control-plane suite unchanged and green (1164 passed, 3 skipped), make typecheck clean across the workspace. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…dis clients, make leaf-status mapping exhaustive Fix round 1 for Task 7 review (rossoctl#389): - leaf-job-runner.ts: a heartbeat tick's fire-and-forget touch() could reject (e.g. a client destroyed by stop() racing the in-flight leaf) and become an unhandled rejection, killing a process also serving healthy sync traffic. A missed touch is already safe by design (the entry becomes reclaimable after minIdleMs), so swallow it. - async-worker.ts: build the queue and turn-store Redis clients with the canonical resilientClientOptions/swallowRedisErrors pair instead of a local copy, and add the pairing's required third part -- re-arming on `!client.isOpen` -- via a generic Proxy wrapper, since neither RedisWorkQueue nor TurnStore owns a lazy open(). Without this a single Redis blip past the bounded reconnect's give-up would stop the worker draining for the rest of its life. - async-worker.ts: replace asyncFinalizeState's unsafe `as TurnState` cast with an exhaustive switch, so a new LeafResult status is a compile error here instead of silently coercing. - async-worker.ts: document the ppid consumer-id fallback's known cross-host collision limit. - async-worker.test.ts: add tests constructing armAsyncLeafWorker directly (queue and turn store get separate connections) and replace the "unrefs its timer" test's constant check with an assertion on the real timer handle. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…s method-shape assumption Fix round 2 for Task 7 review (rossoctl#389): - Export reconnecting and unit-test it directly against a fake client/target pair: asserts it calls connect() when the client is !isOpen before the wrapped method runs, and does not when it is already open. Reverting the !isOpen check left all 531 knative-server tests green, which is exactly the undetectable-invariant gap this closes. - Document reconnecting's shortcut: it types every wrapped method as returning what it already returns, which is sound only because every current public method on RedisWorkQueue and TurnStore is already async; a synchronous public method added later would silently get wrapped into a Promise with no compile error. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Dropping KEDA dropped the only thing that watched the queue as a side
effect, so §7's metrics have to be asked for. Four counts -- async_claims,
async_reclaims, async_dead_letters, async_claim_denied_full -- and two
gauges, async_queue_depth and async_oldest_age_ms, join the existing
snake_case counters object at the supervisor's admin /metrics.
They ride the advisory `stats` IPC row, which is the only path from the
worker to that port, and on its existing terms: telemetry only, never
merged into WorkerView, never an input to reconcile() or a routing policy.
views() is deliberately untouched, and a test asserts it.
async_claim_denied_full is this design's own stated risk made visible: §5.3
reserves no headroom, so a full queue can occupy every slot. Only the loop
can count it -- a claim that was never attempted leaves no other trace.
async_reclaims needed ProcessOutcome to carry `reclaimed` on every claimed
outcome, not just completions: a reclaimed entry that then dead-letters is
precisely the case "workers die mid-leaf" is meant to show.
The two gauges come from slot 0 only (spec §9.2). They describe Redis rather
than any worker, §7 wants them once per deployment, and packages/supervisor
ships `dependencies: {}` so it cannot query Redis itself. Accepted cost,
from that decision: they go stale while slot 0 restarts -- reported as NaN,
never as 0, because 0 would read as an empty queue.
Slot 0 polls depth() every 10 s on an unref'd timer instead of reading it
inside the 1 s stats interval: depth() is two round trips and the stats
callback is synchronous. Both gauges come from ONE depth() call, since
depth and age fetched separately would describe two different instants and
the pair is what distinguishes a deep fast queue from a stalled shallow one.
Counts are per-process cumulative, summed over the workers that reported.
For a count that collapse is honest -- "nobody reported" and "nothing
happened" are both zero claims -- unlike a gauge, which is why the gauges
are read from one slot instead of summed.
async_quota_refusals is not here: the control plane enforces that quota and
a worker never sees a refused submission.
Verified: 28 async-worker tests, 6 new admin tests (24 total in that
describe block), the whole supervisor suite green (238 passed | 2 skipped),
the whole knative-server suite green (540 passed), make typecheck clean.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Task 8's worker-to-admin telemetry seam had zero test coverage: deleting
the asyncStats spread, the pollDepth catch, or the slot-0 gate all left
540/540 green. Address the review's ordered fix list:
1. worker.test.ts: pin startStatsReporter's `...(opts.asyncStats?.() ?? {})`
seam -- all six async fields present when asyncStats reports them, none
present when it is omitted/undefined.
2. admin.test.ts: pin that one unreported slot's NaN contributes 0 to the
summed counters rather than poisoning the sum to NaN.
3. async-worker.test.ts: give pollDepth real execution coverage against
local Redis -- stats() picks up both gauges from one depth() call, and
a rejecting depth() leaves the previous reading in place.
4. worker.ts: reorder the stats send's spread before `type: 'stats'`, so
a future AsyncWorkerStats field cannot clobber the row's own fields.
5. worker.ts: add .catch() to both `void asyncWorker?.stop()` call sites
(drain and disconnect handlers), matching the existing precedents in
supervisor/src/main.ts and leaf-job-runner.ts.
Each new test was confirmed red against the current code (by breaking the
invariant it guards) before being left green; see the appended section of
task-8-report.md for the red/green pairs.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The seventh of §7's async metrics, and the only one that cannot ride the worker's stats row: §4.3 refuses the submission in the control plane, so nothing is enqueued and no worker ever sees it. counters.ts has been accumulating the number since rossoctl#387 with a comment saying the surface that reads it belongs to the §7 task. This is that surface; the comment now points at the route instead of promising one. Admin-gated rather than open like /healthz and /readyz. Those answer a fixed string and a Redis probe; this answers how often tenants hit their quota, on the control plane's single public port -- a small activity side channel, and free to close. The check is isAdmin() inside the handler, the way listSessions already gates its privileged branch, because RouteSpec has no whole-route admin field and one route does not justify adding one that every reader of the table would then have to understand. auth: 'exchange' was the other candidate and is worse: that token mints credentials, and a metrics scraper has no business holding it. Harness profile only -- the sandbox profile runs no turns, so the number would be structurally zero there. Unversioned like the probes, and the same path and snake_case `counters` shape as the supervisor's admin port, so an operator learns one name. Process-local and reset by a restart: with more than one replica, each request reports one replica's share. Stated in the handler, the OpenAPI description and the changelog rather than fixed, because fixing it means a shared counter in Redis -- a write on the refusal path, which is the one path already shedding load. asyncCounters() returning a copy is now load-bearing and has a test: handing out the live object would let any reader reset the process's telemetry. Four files because routes.ts is declared once and read three times -- route table, handler map, openapi.yaml -- with the enumeration and contract tests failing on any pair that disagrees. routes.test.ts's own hardcoded route enumeration also needed the new path, and openapi.yaml needed an explicit `security: [{ sessionToken: [] }]` rather than an inherited default, since the document declares no document-level default for the contract test to inherit. Verified: 6 new tests, the four enumeration/contract suites and the whole control-plane package green, make typecheck clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Scope item 4, and smaller than it reads. The claim path needs no new
environment variable on either deployment: the worker already holds
SH_EXCHANGE_TOKEN as a systemd credential, SH_CONTROL_PLANE_URL and
REDIS_URL. So this adds one knob and no systemd unit changes at all,
since the workers are the supervisor's fork() children and inherit its
environment (verified at packages/supervisor/src/main.ts and
deploy/vm/systemd/sh-supervisor.service).
The knob ships COMMENTED in the VM env example, which is load-bearing:
compose's check_mirror builds its list from uncommented keys there, so
an uncommented SH_ASYNC_DRAIN= would oblige docker-compose.yml to carry
the same empty value. Commented is also the honest default. Compose
gets the key as SH_ASYNC_DRAIN: ${SH_ASYNC_DRAIN:-} -- an explicit
empty default, not a bare pass-through -- because a bare `KEY:` with no
matching .env/shell var resolves to YAML null, which the compose test's
svc_env probe reads the same as absent; the explicit default is what
actually keeps the key present as '' when .env is silent, matching the
other opt-in keys in the same block (SH_TURNS_PER_SUBJECT,
SH_TURN_DETACHED_MAX_S, SH_TURN_LOG_TTL_S use the same form).
The three §6.2 timings are in the env example's comment and nowhere
else: fixed in code, not knobs, but an operator needs them to tell a
stuck queue from the design. They get no row in the configuration
reference, whose rule is that every row comes from the code that READS
it.
Both READMEs state the limit rather than hiding it: the drain shares
SH_TURNS_PER_WORKER with sync /turn and reserves no headroom, so a deep
queue can occupy every slot, and async_claim_denied_full is how that
becomes visible.
Extra item: LEAF_RESULT_TTL_SECONDS already reached the control plane's
service environment on both deployments but no worker, so an operator
tuning it got it honoured for control-plane-written results and
silently ignored for the async worker's own leaf results
(packages/knative-server/src/server.ts reads it; async-worker.ts uses
the same constant). Added the matching pass-through to
deploy/vm/env/supervisor.env.example and the supervisor service in
deploy/compose/docker-compose.yml, scoped to deploy/vm and
deploy/compose only.
Fixes a now-wrong line in the configuration reference: SH_WORKER_ID was
listed as set-but-never-read, and the async drain's consumer name is
its first reader.
Verified: deploy/vm/tests/setup-vm.test.sh and
deploy/compose/tests/compose.test.sh green with one new assertion each
(both proven load-bearing by breaking and restoring them), make
typecheck clean, make lint clean except the pre-existing
hadolint-docker/no-daemon failure.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…place
Review round 1, item 1 (should). The pass-through to the supervisor
service was added off-brief in the prior commit to fix a real gap
(the async worker ignoring an operator's configured TTL), but no test
held it in place: deleting it left compose.test.sh at exit 0.
Adds one assertion beside SH_ASYNC_DRAIN's, checking what the bare
pass-through actually produces rather than retuning it for a tidier
check: LEAF_RESULT_TTL_SECONDS resolves to YAML null when .env is
silent (unlike SH_ASYNC_DRAIN's ${:-} substitution form, which
resolves to ""), and svc_env's `// "<absent>"` cannot tell that apart
from a missing key. So this checks presence directly with
jq -e '... | has("LEAF_RESULT_TTL_SECONDS")' against the base render.
Verified: deleting the supervisor service's line turns the new
assertion red (the control plane's own line, left in place, is not
enough); restoring turns it green. deploy/vm/tests/setup-vm.test.sh
and deploy/compose/tests/compose.test.sh both exit 0, make typecheck
exit 0, make lint shellcheck-clean (hadolint-docker's no-daemon
failure is pre-existing and unrelated).
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Ten tests against real Redis for the part that only exists once the loop, the queue, the record store and Redis are in one process, plus one live crash test that is skipped by default. A third of §8's matrix was already covered by rossoctl#387 and rossoctl#388 and is NOT re-tested here: the mint admitting a `running` record (turn-exchange.test.ts:144), the cancelled claim, cancel's record flip, the §4.3 quota with xLen asserted, and the workloadId 501. Each is cited in the file rather than duplicated. Timings are injected because §9.2 says to: minIdleMs is 90 s in production, so a faithful reclaim test waits 90 s+ and CI will not gate on it. These are production parameters processOne already accepts, not a test seam -- nothing under test learns it is being tested. The mixed-load case is the one §5.3's take-before-claim ordering exists for: interactive turns arrive through the same counter while the loop drains, and the peak is SAMPLED at 5 ms rather than hooked, because a briefly-over-cap counter is exactly the over-admission that ordering forbids. The drain case pins the trap: the entry is abandoned UNACKED and still pending, because XGROUP DELCONSUMER would discard it and turn the one redelivery the design relies on into silent loss. It also asserts stop() returns in under a second against a leaf still running -- MOCA_TURN_MAX_S is 1800 s against a 20 s grace, so waiting could only time out. The heartbeat case covers the one async property whose absence is invisible until a leaf runs past 90 s in production, which is most real leaves. The live test is the one thing injected timings cannot prove: a real kill -9 mid-leaf, a real restart, a real 90 s reclaim. Gated on SH_ASYNC_LIVE_CRASH following live-relay.test.ts's convention. Its assertion is "exactly once", not "completes" -- a redelivery that runs the leaf twice also ends with the record `done`, and would pass while the user was billed twice. Every key carries a per-run tag and the queue runs on a per-run stream name, so two copies of the suite can run at once and nothing can purge a developer's real LEAF_QUEUE_STREAM. §8's "each of the three sync aliases must be shown to occupy a slot" adds nothing here on purpose: TURN_PATHS is one Set, isTurnRequest is one exact lookup, and worker.ts:138-142 is its only call site with the slot taken unconditionally after it. Task 6's it.each over the three paths IS that coverage; an end-to-end POST would need Redis, a sandbox and a model to reach a branch that does not exist. Verified: 10 integration tests green against Redis on 6379, real-worker.integration.test.ts reports 6 passed 1 skipped, all five packages green, make typecheck and make lint clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
… the supervisor (rossoctl#389) Task 10 scoped the new knob and the LEAF_RESULT_TTL_SECONDS pass-through to deploy/vm and deploy/compose only, which broke packages/supervisor/test/k8s/env-parity.test.ts: the k8s supervisor container no longer named every variable in deploy/vm/env/supervisor.env.example. Add both keys to deploy/k8s/base/supervisor.yaml using the configMapKeyRef/moca-settings/optional:true idiom already used there for SH_SANDBOX_TIERS and in control-plane.yaml for LEAF_RESULT_TTL_SECONDS itself. Both stay optional and off/absent by default, matching vm and compose. deploy/microvm is untouched. Correction to the record: commit 70ad79e's message claims "all five packages green", which was not true at the time -- packages/supervisor's full suite was already red (1 failed | 238 passed | 3 skipped, exit 1) from this same regression. Nothing has been pushed, so no history is rewritten here; this note is the correction. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…nd parity tests Remove the peak<=cap assertion and its 5ms sampler from the mixed-load test: leaf-drain-loop.ts only gates async claims on cap, while sync turns start unconditionally through TurnCounter, so total in-flight can legitimately exceed cap and the assertion does not hold as a production invariant. The test's own guard that kept sync load from ever exceeding cap is removed too, since it existed only to keep that false assertion from failing. Rename the test to describe what it still checks: every queued turn finishes. Use the previously-unused `_state` column in the parity carry-overs it.each to assert the turn record actually reaches that state in Redis, closing a hole where asyncFinalizeState could silently remap a status without any test catching it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…tion leaf stream armAsyncLeafWorker's test suite deleted the real LEAF_QUEUE_STREAM against a live Redis to force a poll failure; a stream delete drops its consumer group too, so anything in flight there was stranded. Add an optional `stream` to armAsyncLeafWorker, following packages/control-plane/src/turn-queue.ts's own precedent for the same hazard, and point the test at a per-run stream instead. Production callers are unaffected: the option defaults to LEAF_QUEUE_STREAM. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ge throws start() returned no releaser if onChange threw before it, permanently losing an admission slot; the releaser itself could also throw onChange's error as an unhandled rejection from the sync response-finish path. Route both calls through a notify() that swallows the error: onChange sends the absolute in-flight count, never a delta, and the supervisor reconciles its estimate from `load`, so one dropped send self-heals on the next one. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…eardown No test went red if clearInterval(depthTimer)/stopReaper() were dropped from stop(): the 10 s depth poll would then outlive stop() and, through the reconnecting Proxy's !isOpen re-arm, reopen the client stop() just destroyed, inside the 20 s shutdown grace. Add a test asserting depth() is called no more after stop(), even past one full poll interval. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
`reapDeadLetters` XACKed each entry itself, before the caller had written anything. An acked entry leaves the pending-entries list forever, so if `deadLetterTurn`'s Redis write then failed -- the sweep's catch logs it and moves on -- the turn stayed `running` with no entry left to redeliver. It would sit there until its record expired: no result, no failure, no retry. The ordering `leaf-job-runner.ts:139` already uses for its own dead-letter branch is write-then-ack. The reaper now does the same: the queue claims and returns the entry, `armAsyncReaper` acks it after the write lands. A failed write leaves it pending, and the XCLAIM has reset its idle timer, so the next sweep is `minIdleMs` away and `deadLetterTurn`'s terminal-state guard makes the repeat a no-op. Also drops `WorkQueue.purge()`, which destroyed the consumer group and deleted the stream. Nothing calls it since the test that did was fixed to use its own stream; the only thing keeping it alive was a stub in `leaf-job-runner.test.ts`. A method that strands every in-flight async turn should not exist unused on the interface a worker holds. Tests: the reap no longer acks (work-queue), a reaped entry is claimable again when the caller never acks, the sweep's order is write-then-ack, and a throwing `deadLetter` leaves the entry unacked. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Two processes write leaf results under the same keys from the same variable, and they read it differently. The control plane validated it and refused to boot on anything but a non-negative integer; the worker did `parseInt(... ?? '86400', 10)`, which reads `86400x` as 86400, a blank as NaN and `abc` as NaN. `writeResult` passes the value straight to Redis as `EX`, so on the worker a malformed TTL did not fail at boot -- it failed on every result write, `ERR value is not an integer`, after the leaf had already run. This branch is what made it reachable: rossoctl#389 wires `LEAF_RESULT_TTL_SECONDS` into the supervisor's env for the first time, so an operator setting it for the control plane now also sets it here. `resultTtlSeconds(env)` lives beside `TURN_RECORD_TTL_MARGIN_SECONDS` in `turn-record.ts` -- the pure module that is already shared for exactly this reason -- and both call sites use it. Zero is now refused as well, in both: Redis rejects `EX 0`, so "no retention" was never a value this knob could express, and accepting it in the control plane only moved the failure to the write. `configuration.md`'s two rows said the worker reads a blank as NaN. They now describe the one parse both processes share. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Upstream moved from c241116 to dd0ce71 (23 commits), mostly the OIDC identity provider (rossoctl#701) and rossoctl#715's sandbox-tier fixes. Merged rather than rebased: the branch has an open PR (rossoctl#717), and a rebase needs a force-push that is not authorized. Two files conflicted, both because upstream and this branch edited adjacent lines: - `packages/control-plane/src/handlers.ts`: this branch adds `getMetrics` between `healthz` and `getDiscovery`; upstream deleted the blank line there. Resolution keeps `getMetrics` and drops the blank line. - `docs/reference/configuration.md`: upstream added the OIDC rows to the control-plane table, this branch rewrote the `LEAF_RESULT_TTL_SECONDS` cell, and prettier realigns every row of a table when one cell's width changes -- so the whole table conflicted over one real edit. Resolution keeps upstream's table with this branch's cell re-applied. `deploy/vm/tests/setup-vm.test.sh` carries one unrelated fix, not a merge artifact: upstream 294054a added two GNU-style `sed -i` calls with no suffix, which abort the whole suite on BSD sed ("invalid command code f") before it can validate anything. Both now use the `-i.bak` + `rm -f` idiom the file's six other `sed -i` calls already use. Without it the VM deploy suite -- one of the two this branch changed -- cannot run on macOS. Verified on the merged tree: `make typecheck`, control-plane 1210, knative-server 558, mocactl 1704, supervisor 239, work-queue 12, harness 784 (the one failure is the known pre-existing macOS `mv` issue in `context-overlay.test.ts`), plus both deploy suites, `setup-vm.test.sh` and `compose.test.sh`. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Authorization: `Bearer ${deps.exchangeToken}`, | ||
| }, |
There was a problem hiding this comment.
Read this one as a false positive, and left the alert for a maintainer to dismiss rather than dismissing it myself.
The flagged flow is deps.exchangeToken into the Authorization header of a POST to deps.controlPlaneUrl. Both are operator-supplied configuration, and the "file data" is the point: SH_EXCHANGE_TOKEN is read from a systemd credential (LoadCredential=) or a mounted Secret under CREDENTIALS_DIRECTORY precisely so it is not sitting in an env var or a unit file. Sending it to the control plane as a bearer is the hop it exists for.
The only three inputs to the fetchImpl call are deps.controlPlaneUrl (env), deps.exchangeToken (that credential file) and JSON.stringify({ turnId }), where turnId comes off the work queue -- entries the control plane itself wrote, and the route re-checks the shape against MINTED_TURN_ID_RE anyway. Nothing request-derived reaches the URL, so there is no SSRF surface, and no file a caller could name is read.
docs/reference/configuration.md documents both variables; the SH_EXCHANGE_TOKEN row notes that env plus credential file is a boot failure, so there is exactly one source for it.
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Summary
A careful, well-documented slice. It restores @moca/work-queue, adds the P6 drain loop that shares TurnCounter, does a per-turn credential exchange at claim, and handles reaping and redelivery. The ack ordering is now write-then-ack on both the inline and the periodic dead-letter paths. All three sync leaf routes are counted, and the deploy wiring is off by default. No must-fix issues. One suggestion is about admission behaviour when the queue is idle, and one is a small metrics accuracy point (inline).
Author: cwiklik (CONTRIBUTOR — returning external; every changed source file read in full)
Areas reviewed: TypeScript (work-queue, knative-server, harness, control-plane, supervisor), YAML/K8s, Dockerfile, Shell tests, Docs, dependency manifests / lockfile
Agent/IDE config (.claude/.vscode): none
Dependencies: workspace links only. pnpm-workspace.yaml adds allowBuilds for esbuild and protobufjs (both already in the tree). The lockfile churn just drops the optional supports-color peer. No new external packages.
Commits: 27 commits, all signed-off: yes
CI status: passing (17/17, including CodeQL, Trivy, dependency-review, k8s-kind-e2e)
All checks pass apart from the inline suggestions. Ready for human review.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| deps.onCapDenied?.(); | ||
| await sleep(idleBackoffMs); | ||
| } else { | ||
| release = deps.counter.start(); |
There was a problem hiding this comment.
suggestion — With an empty queue, this loop holds an admission slot almost all the time, not just for a bounded window.
counter.start() runs before claim(), and claim() blocks for blockMs (5 s). An idle result skips the backoff, so the slot is released for a single setImmediate tick and then taken again. So when SH_ASYNC_DRAIN=1, every worker reports inFlight >= 1 about 100% of the time, even with nothing queued.
- With
SH_TURNS_PER_WORKER=1, for example the one-worker compose trial the README describes,isSaturatedwill refuse almost every interactive/turnwith a 429 while the async queue is empty. The README says a queued turn and an interactive turn "compete for the same slot", which suggests competition only when there is queued work. - With a larger cap, the effective sync capacity drops by one per worker all the time.
§5.3 accepts the "up to blockMs" refusal window as the price of never over-admitting. But since there is no idle backoff, the window repeats back to back. Options that keep the cap invariant:
- Peek cheaply without blocking (for example, a non-blocking
XREADGROUP/XAUTOCLAIMwithBLOCK0 or omitted) while holding the slot, then release it and do the blocking wait without a slot. - At minimum, document that arming the drain permanently reserves one slot per worker, and warn or refuse when
SH_TURNS_PER_WORKER=1.
spurious_refusals will show this, but it would help to settle it before operators enable the knob.
There was a problem hiding this comment.
Fixed in 8d2d53a. The admission slot is released before the backoff sleep, so an idle drain holds no slot while it waits. Your reading of the arithmetic was right: the claim is non-blocking, so an idle loop is sleep-dominated and every sleep was inside the slot.
The idleBackoffMs field doc was stale in the same way and now says the sleep always happens with no slot held.
| queue, | ||
| consumerId, | ||
| deadLetter: async (turnId) => { | ||
| tally.onReaped(); |
There was a problem hiding this comment.
nit — tally.onReaped() increments before deadLetter runs. If deadLetterTurn returns early because the record is already terminal or expired, async_dead_letters still counts it. If the write throws, the entry stays pending, is re-reaped minIdleMs later, and is counted again. Incrementing after the await (and only when the guard actually finalized) would keep the metric to real dead letters.
There was a problem hiding this comment.
Fixed in 8d2d53a. tally.onReaped() now runs after the dead-letter write succeeds, so the counter cannot report entries that were never written. Dead-lettering is per-entry now as well, so one failure no longer strands the rest of the batch (the related comment on async-worker.ts:105).
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Review (drafted with AI assistance)
A careful, well-documented M1 slice. It restores @moca/work-queue, adds a drain loop that shares TurnCounter with /turn, does a per-turn credential exchange at claim (only the credential name is persisted or audited), writes before it acks on both dead-letter paths, and wires SH_ASYNC_DRAIN (off by default) on vm, compose and k8s. The merge of main (e1d57b6) resolves its conflicts cleanly (checked with --remerge-diff).
Blocking: async results are keyed by session (leaf:result:<sessionId>), so two async turns on one session overwrite each other's result. §4.3 explicitly permits that case with distinct idempotencyKeys. See the inline comment on turn-claim.ts:165.
Suggestions: a non-atomic markRunning vs. DELETE; Redis Streams edge cases in @moca/work-queue (XAUTOCLAIM cursor starvation, a gc/DELCONSUMER race that can orphan an entry, a heartbeat XCLAIM that steals ownership back); and k8s settings that setup.sh never writes. These are independent of clawgenti's two comments (idle slot hold, onReaped ordering), which still stand.
The CodeQL alert on turn-claim.ts:60 looks like a false positive: the exchange token comes from a credential file and is sent to the operator-configured control-plane URL, and nothing request-derived reaches the URL.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (work-queue, knative-server, control-plane, harness, supervisor), deploy (vm/compose/k8s, Dockerfile), lockfile/workspace, docs/OpenAPI
Agent/IDE config (.claude/.vscode): none
Commits: 28 commits, all signed-off: yes
CI status: all green
| // the periodic reaper, which calls this same path. | ||
| if (!rec || isTerminalState(rec.state)) return; | ||
| const now = deps.now ?? (() => new Date().toISOString()); | ||
| await writeResult( |
There was a problem hiding this comment.
must-fix — The async result key is per session, not per turn, so two async turns on one session overwrite each other's result.
deadLetterTurn writes leaf:result:<rec.sessionId>. The worker's success write (leaf-job-runner.ts:155) uses the same key, and so does the reader (turn-handlers.ts:215, readLeafResult(turn.sessionId)). §4.3 explicitly allows two queued turns on one session when the caller passes distinct idempotencyKeys. In that case: turn A finishes done and writes its result. Sibling B then dead-letters, or simply finishes later, and overwrites the same key. GET …/turns/A now returns state: done with B's result body. The isTerminalState(rec.state) guard checks only B's own record, not who owns the key.
Fix, in order of preference:
- Key async results by turn, e.g.
leaf:result:<sessionId>:<turnId>, and add it tocascadeDelete's data keys. - Or refuse a second non-terminal async turn per session at submit (409), dropping the distinct-
idempotencyKeyescape hatch from §4.3. - At minimum, store
turnIdin the result record and havegetTurndrop a result whoseturnIddoesn't match.
The new §9.2 key-equality test should also cover two turns on one session.
There was a problem hiding this comment.
Fixed in 8d2d53a. The async path now takes the session id from the turn RECORD, not from the envelope, so a drained turn's result lands under leaf:result:<turn.sessionId>:<turnId> -- the exact key TurnStore.deleteSessionTurns walks. Sync /runs is unchanged (per-session, no turn id).
Confirmed the failure first: with the envelope's session id, a result written by the drain was unreachable by the owning session's DELETE and outlived it to the full TTL. async-drain.integration.test.ts now asserts the key the control plane deletes.
| throw new CpError('credential_unavailable', 'envelope session id does not match the record'); | ||
| } | ||
|
|
||
| // Exchange first, THEN the state write -- see this file's header. markRunning re-checks |
There was a problem hiding this comment.
suggestion — This comment promises more than markRunning delivers. TurnStore.markRunning (turn-store.ts:225) does get(), then a separate hSet, with no compare-and-set. If a DELETE commits cancelled between those two calls, the hSet flips the record back to running. The leaf then runs on the owner's credential after the client was told cancelled, and the quota slot and idempotency key are already released. The window is small, but cancel itself is also get-then-write. Make markRunning (and cancel) atomic: a Lua script or WATCH/MULTI conditional on state ∈ {queued, running}.
There was a problem hiding this comment.
Fixed in 8d2d53a. markRunning and cancel both go through one CAS Lua script now: the read of state and the write happen in the same EVAL, so a DELETE that moved a queued turn to cancelled in the get-then-write gap is no longer overwritten.
Two races against real Redis cover it (turn-store-redis.test.ts): two concurrent finalizes (exactly one wins, and the open-set member is removed exactly once, so the quota slot is freed once), and a cancel whose read saw queued but whose write lands after a claim. The second is ordered deliberately -- cancel is started FIRST in the Promise.all, so its HGETALL is on the wire before markRunning's EVAL. With the other order, cancel's own JS-level rec.state !== 'queued' check answers conflict on its own and the CAS is never exercised; a negative control (neutering the CAS) left that version passing, which is what drove the ordering.
| // XAUTOCLAIM over the group's WHOLE PEL from '0', not this consumer's own: nobody reclaims | ||
| // faster for being the original owner, which is the behaviour §6.2 specifies. | ||
| const auto = await this.client.xAutoClaim( | ||
| this.stream, |
There was a problem hiding this comment.
suggestion — XAUTOCLAIM … '0' COUNT 1 always starts from the head of the PEL and throws nextId away. Redis scans at most COUNT×10 PEL entries per call, so only the ~10 oldest pending entries are ever examined. Scenario: 10 or more healthy long leaves are in flight, each touched every 30 s so none is idle. A worker holding a newer pending entry crashes. No claim() reaches that entry until older leaves ack, which can take up to the turn max (30 min). This is bounded starvation, not loss, but it is far beyond the 90 s reclaim the design promises. Keep nextId as an instance cursor, resetting it to '0' when Redis returns 0-0. Or use a larger COUNT and take the first message.
There was a problem hiding this comment.
Fixed in 8d2d53a. The XAUTOCLAIM cursor is carried across calls now instead of restarting at 0-0 on every sweep.
The starvation is real and bounded exactly as you describe: XAUTOCLAIM examines at most COUNT x 10 PEL entries per call, so a prefix of entries that keep failing hides everything behind them. Negative control: pinning the cursor back to 0-0 makes the new test fail -- an entry past the first batch is never reclaimed.
| const info = await this.client.xInfoConsumers(this.stream, this.group); | ||
| let removed = 0; | ||
| for (const c of info) { | ||
| // `pending === 0` is the whole safety property: a consumer still holding entries must keep |
There was a problem hiding this comment.
suggestion — gcIdleConsumers checks and then acts across separate round trips. The pending === 0 && idle >= minIdleMs snapshot comes from one XINFO call, and the DELCONSUMERs are awaited one at a time afterwards. A worker that sat at cap on sync traffic for 5 minutes or more is legitimately idle with 0 pending. If it XREADGROUPs an entry inside that window, DELCONSUMER silently drops the entry from the PEL. The leaf still runs, but touch and ack are then no-ops. If that worker is drained (stop() deliberately abandons in-flight leaves) or crashes, the turn is behind last-delivered-id and absent from the PEL, so it stays running forever. Do the check and the delete atomically per consumer in a small Lua script.
There was a problem hiding this comment.
Fixed in 8d2d53a. gcIdleConsumers now skips any consumer whose PEL is non-empty, so DELCONSUMER only ever runs on a consumer with nothing pending.
The window is as described: XINFO CONSUMERS reports idle and pending, and an entry delivered between that read and the DELCONSUMER is discarded along with the consumer -- no PEL entry left, so no redelivery and nothing for the reaper to find. A consumer that picks up work right before the GC simply survives this sweep and is collected on a later one.
| } | ||
|
|
||
| async touch(entryId: string, consumerId: string): Promise<void> { | ||
| // Reset idle time without re-fetching the payload, so a healthy long run is not reclaimed. |
There was a problem hiding this comment.
suggestion — touch uses XCLAIM … min-idle 0, which always transfers ownership to the caller. If worker A stalls for 90 s or more (event-loop stall, or a Redis blip; touch errors are swallowed in leaf-job-runner.ts:131), worker B reclaims the entry and starts a second run. A's next heartbeat silently steals the entry back, and from then on ownership flips every 30 s while both runs write results. Make the heartbeat conditional: in Lua, XCLAIM only if XPENDING <id> <id> 1 still names consumerId. Return a lost-ownership signal so the runner can log it or abort.
There was a problem hiding this comment.
Fixed in 8d2d53a. touch no longer claims with a bare min-idle 0. You are right that min-idle 0 matches everything, so a worker that stalled past minIdleMs, had its entry legitimately reclaimed, and then woke up would steal it back on its next beat -- two workers on one turn, both writing a result, and the loser's ack retiring an entry the winner still believed it owned.
The heartbeat is now one script that checks the PEL owner and claims only if it is still this consumer (TOUCH_IF_OWNED_LUA), and an empty PEL row (acked or trimmed) counts as not-owned too. On a refusal processOne logs the lost entry loudly rather than stealing it: there is no cancellation path into runLeaf, so this run finishes and the results race, but ownership stays with the reclaiming worker and its ack is the one that stands. The log line is the only trace the duplicate leaves, and it also means this worker stalled past minIdleMs, which is worth seeing on its own.
| - { name: SH_REQUIRE_AUTH, value: 'true' } | ||
| # #389: 1 makes every worker also drain the async leaf queue. `optional`, like the tier | ||
| # keys above: a moca-settings written by an older setup.sh still boots, and unset is off. | ||
| - name: SH_ASYNC_DRAIN |
There was a problem hiding this comment.
suggestion — On k8s, nothing writes SH_ASYNC_DRAIN or LEAF_RESULT_TTL_SECONDS into moca-settings. setup.sh write_settings (:1080) has a fixed key set that includes neither, and neither feeds SETTINGS_HASH. An operator who hand-patches the ConfigMap gets no rollout, because configMapKeyRef env is read only at pod start. The drain then silently stays off until a manual rollout restart. Make both keys sticky inputs of write_settings so they join the hash, or at least document "patch, then rollout restart" in deploy/k8s/README.md.
There was a problem hiding this comment.
Fixed in 8d2d53a. deploy/k8s/setup.sh writes both keys now. The manifests were the only half that was already wired: base/supervisor.yaml reads SH_ASYNC_DRAIN and LEAF_RESULT_TTL_SECONDS with optional: true, and already mounts SH_EXCHANGE_TOKEN as a file under CREDENTIALS_DIRECTORY -- so with setup.sh never writing the keys, the k8s drain could not be turned on at all.
Both are sticky settings on the same convention as the token lifetimes: given on the command line they are stored, omitted they are carried forward, set-but-empty they are cleared (empty SH_ASYNC_DRAIN = drain off, empty LEAF_RESULT_TTL_SECONDS = the 86400 default both tiers use). Validated when given AND when read back from moca-settings, because a bad TTL crashes the control plane and every worker at BOOT -- that has to stop before the apply, not after it.
SH_ASYNC_DRAIN accepts 1 or empty only, deliberately stricter than the worker's truthy() (1|true|yes), matching SH_WORKLOAD_SANDBOXES: a value setup.sh refuses that the worker would have taken costs an operator one re-run, while SH_ASYNC_DRAIN=ture silently leaving the queue undrained costs a debugging session.
Both keys are written on every run even when empty, so every stack hashes the same key set and SETTINGS_HASH still rolls the Deployments on a change. deploy/k8s/tests/setup.test.sh gained two cases (sticky/clear/hash-roll with the manifest refs asserted, and a malformed value refused whether given or stored) and the two key-count assertions moved 15 -> 17. Suite is green: 116 ok, 0 fail.
| packages: | ||
| - 'packages/*' | ||
| - 'harness' | ||
| allowBuilds: |
There was a problem hiding this comment.
nit — allowBuilds: { esbuild, protobufjs } arrived in the work-queue commit (7adf697) and is unrelated to this PR. It lets two packages run install scripts under newer pnpm and aube; it does nothing under the pnpm@9 that CI and the Dockerfile use. Drop it, or justify it in its own commit.
There was a problem hiding this comment.
Removed in 8d2d53a. pnpm-workspace.yaml is back to just the packages list -- the allowBuilds block was unrelated to this change and should not have been in the diff.
| // `deadLetterTurn` into a turn stuck `running` that nothing can ever redeliver. An entry | ||
| // whose turnId field is missing or malformed has no record to finalize, so it is only | ||
| // acked. | ||
| if (entry.turnId) await opts.deadLetter(entry.turnId); |
There was a problem hiding this comment.
nit — If one deadLetter throws, the remaining reaped entries in the batch are left unacked. They were just XCLAIMed, so their idle timer was reset and they wait another 90 s or more. gcIdleConsumers is also skipped for that sweep. Wrap each entry in its own try/catch and run gc in a finally. Separately, a turnId-less entry is acked here without onReaped, whereas leaf-job-runner.ts counts the same case as dead-lettered, so async_dead_letters disagrees between the two paths.
There was a problem hiding this comment.
Fixed in 8d2d53a. Each entry is dead-lettered and acked on its own now, so a throwing deadLetter on one entry no longer leaves the rest of the batch unacked and redelivered forever. The throw is logged and that one entry stays pending for the next sweep.
The same commit moves tally.onReaped() to after the write (your other comment) -- it was counting entries it had not yet dead-lettered.
| // key space. `resultTtlSeconds` is the control plane's own parse of the variable, shared rather | ||
| // than repeated: a local `parseInt` read a blank or typo'd value as NaN, which Redis rejects on | ||
| // every `EX`, so a malformed TTL broke result writes here while refusing to boot there. | ||
| export const RESULT_TTL_SECONDS = resultTtlSeconds(process.env); |
There was a problem hiding this comment.
nit — The strict resultTtlSeconds now makes the worker fail at module load on values the old parseInt accepted, such as "86400 " (a trailing space or CR from an env file). Consider .trim() before the regex, and add an upgrade note to docs/api/CHANGELOG.md / configuration.md.
There was a problem hiding this comment.
Fixed in 8d2d53a, in packages/control-plane/src/turn-record.ts rather than at this call site: server.ts only calls the shared parse, and fixing it here would have left the control plane's own copy strict.
The value is trimmed before the regex, so "86400 " and a CRLF line ending both boot, and whitespace-only now means the same as unset (86400). Interior whitespace ("6 00") is still refused. Tests cover 600, 600 and \t600\r\n.
Upgrade note added to docs/api/CHANGELOG.md under 1.3.0, and the configuration.md row says the surrounding whitespace is trimmed.
| | `ANTHROPIC_BASE_URL` | none | | Gateway or endpoint | | ||
| | `OPENAI_API_KEY`, `OPENAI_BASE_URL` | none | **Secret** (key). `OPENAI_API_KEY` is seeded with `unused` for `custom-header` and `none` | OpenAI-compatible provider | | ||
| | `HARNESS_CWD` | process cwd | | Turn working directory | | ||
| | `LEAF_RESULT_TTL_SECONDS` | `86400` | Positive integer or boot fails; blank means the default. Same strict parse the control plane uses, because both processes write the same result keys | TTL of sync `/runs` leaf results | |
There was a problem hiding this comment.
nit — The meaning column still says "TTL of sync /runs leaf results", but the worker now also writes async drain results with it. Suggest "TTL of leaf results (sync /runs and async drain)".
There was a problem hiding this comment.
Fixed in 8d2d53a: the meaning column now reads "TTL of leaf results (sync /runs and async drain)". The constraints column in the same row picked up the trimming behaviour from the other nit.
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Summary
No new commits since the earlier review at e1d57b6. That review's findings still stand: the suggestion on leaf-drain-loop.ts (an idle drain holds an admission slot almost all the time, re-checked against HEAD) and the nit on async-worker.ts (onReaped counts before the dead-letter write). No must-fix issues from this pass. The open must-fix and suggestions in the human review (session-keyed async results, non-atomic markRunning, Redis Streams edge cases) are separate and still need the author's response.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (work-queue, knative-server, harness, control-plane, supervisor), YAML/K8s, Dockerfile, Shell tests, Docs, dependency manifests / lockfile
Agent/IDE config (.claude/.vscode): none
Commits: 28 commits, all signed-off: yes
CI status: passing (17/17)
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
Twelve findings from the PR rossoctl#717 review, in the order they were raised. Must-fix: - The async result key was built from the ENVELOPE's session id while the control plane's delete walks `leaf:result:<record sessionId>:<turnId>`, so a drained turn's result was unreachable by the session that owns it and outlived the delete. Async results are now keyed from the turn RECORD's session id (turn-claim.ts), sync stays per-session. - `markRunning` read the record and then wrote it, so a DELETE that moved a queued turn to `cancelled` in the gap was overwritten: a cancelled turn ran. Both transitions now go through one CAS Lua script, and two real-Redis races cover them (turn-store-redis.test.ts) -- the cancel race deliberately puts cancel's read on the wire first, or the JS-level state check answers it and the CAS is never exercised. - XAUTOCLAIM's cursor was discarded, so reclaim always restarted at `0-0` and entries past the first batch could starve behind a stuck prefix. The cursor is now carried across calls (queue.ts). - `gcIdleConsumers` checked idle time and then DELCONSUMER'd, and DELCONSUMER discards that consumer's pending entries: an entry delivered in the gap was dropped, never redelivered. The GC now skips any consumer with a non-empty PEL. - `touch` used XCLAIM with min-idle 0, which always transfers ownership -- a heartbeat from a worker that had already lost the entry stole it back mid-flight. It now refuses unless the caller still owns it. - One throwing `deadLetter` left the whole batch unacked and redelivered forever. Each entry is now dead-lettered and acked independently (async-worker.ts), and `tally.onReaped()` counts after the write, not before. - The idle drain held an admission slot ~100% of the time: the backoff sleep happened inside the slot. The slot is now released before the sleep (leaf-drain-loop.ts). - `deploy/k8s/setup.sh` never wrote `SH_ASYNC_DRAIN` or `LEAF_RESULT_TTL_SECONDS`, so the manifests' optional refs resolved to unset and the k8s drain could not be turned on at all. Both are now sticky settings, validated when given and when stored, and part of the settings hash that rolls the Deployments. Nits: - `resultTtlSeconds` now trims. The parse runs at module load in the harness tier, so `LEAF_RESULT_TTL_SECONDS=86400 ` from an env file would have taken down a tier that was serving sync traffic. Upgrade note in docs/api/CHANGELOG.md; configuration.md says sync + async drain. - Dropped the unrelated `allowBuilds` block from pnpm-workspace.yaml. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Review round addressed in 8d2d53a. Per-thread replies are on each comment; the short version: Must-fix (all eight fixed)
Nits
CodeQL alert -- read as a false positive and left for a maintainer to dismiss: the "file data" is Verification: Assisted-By: Claude Code |
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Summary
Re-review of 8d2d53a ("address PR #717 review"), the one commit since the earlier review at e1d57b6. All twelve earlier findings are addressed, and I checked each against HEAD: per-turn result keys (leaf:result:<sid>:<turnId>) on both write paths and the reader; the CAS Lua for markRunning/finalize/cancel, with real-Redis race tests; the XAUTOCLAIM cursor; the atomic idle-consumer GC; the owner-checked touch; per-entry dead-lettering with onReaped after the write; the slot released before the idle and error sleeps (non-blocking claim, BLOCK omitted rather than 0); sticky, validated, hashed k8s settings; the trimmed TTL parse; and allowBuilds dropped. No must-fix issues. Two suggestions inline about edge cases the new fixes leave open: a duplicate run after a lost heartbeat still writes and acks, and a session DELETE no longer removes the results of finished async turns.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (work-queue, knative-server, harness, control-plane), Lua scripts, Shell (deploy/k8s setup + tests), Docs, workspace manifest
Agent/IDE config (.claude/.vscode): none
Commits: 29 commits, all signed-off: yes (DCO passing)
CI status: pending (check, deploy-scripts, k8s-kind-e2e still running; all other checks pass)
All checks pass apart from the inline suggestions. Ready for human review.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| claimed.turnId, | ||
| ); | ||
| await deps.finalize(claimed.turnId, result.status); | ||
| await deps.queue.ack(claimed.entryId); |
There was a problem hiding this comment.
suggestion: A run that learned it lost the entry (touch → false, line 148) still runs writeResult → finalize → ack here, so the reply's claim that "ownership stays with the reclaiming worker and its ack is the one that stands" doesn't hold:
XACKisn't owner-checked. The stalled worker's ack removes the reclaimer's PEL entry. If the reclaimer then crashes before it finishes, nothing redelivers. That's harmless only when the stale run's finalize already landed.writeResultis an unconditionalSET. The run that finishes first winsfinalizethrough the CAS, but the run that finishes second overwrites the result body.GET …/turns/{id}can then reportstate: done(first run) next to a body from the second run, which may befailed.
Cheap fix: keep a lost flag set from the heartbeat. If it's set when runLeaf returns, skip the write, finalize and ack, and just log. The reclaimer owns the turn. Alternatively, write the result with NX, so the first writer's body pairs with the first finalize.
There was a problem hiding this comment.
You are right, and my earlier reply on the touch thread was wrong on exactly the point you name: XACK takes no consumer, so the stalled worker's ack does retire the reclaimer's PEL entry, and writeResult is an unconditional SET, so the second finisher's body can sit next to the first finisher's done.
Fixed in b346111 with the lost flag: the heartbeat sets it, and when runLeaf returns with it set processOne returns a new outcome kind lost before any of the three writes -- no result, no finalize, no ack. The reclaimer owns the turn end to end. The tally needs no change: a lost outcome still counts as the claim it was, and only dead_lettered is special-cased.
I took the flag rather than SET NX because NX fixes only the body: the ack would still retire the owner's entry, and the owner's own result write would then be the one refused (it finishes second in exactly the case the ack matters). The residual window is a heartbeat landing between the lost check and the ack -- one beat wide instead of one leaf wide. Closing that properly needs an owner-checked ack, which Redis streams do not have; the comment at the check says so.
Test in harness/test/leaf-job-runner.test.ts fires the beat from inside runLeaf (so the loss is discovered mid-leaf, which is the only case where the flag matters) and asserts no result key, no finalize and no ack. Negative control: with the lost branch disabled the test fails.
| // index), so a terminal turn's result is left to expire on its own TTL. That is the same | ||
| // `resultTtl + margin` clock `toTerminal` already gives the terminal RECORD, so the pair | ||
| // disappears together and the only cost is the wait. | ||
| await this.guard(() => this.redis.del([this.key(turnId), leafResultKey(sessionId, turnId)])); |
There was a problem hiding this comment.
suggestion: This is a small regression in what session DELETE removes. Before this commit, the async result shared leaf:result:<sid>, so cascadeDelete's dataKeys deleted it. Now the key carries the turn id, and this loop only sees open turns: toTerminal already zRem'd the finished ones. So every completed async turn's result (patches included) outlives DELETE /v1/sessions/{sid} for up to LEAF_RESULT_TTL_SECONDS (24 h by default). The API can't reach it (the session 404s), but the data is still retained after the owner asked for deletion.
Options: in cascadeDelete, SCAN MATCH leaf:result:<sid>:* (bounded per session); or keep a per-session set of turn ids, written at submit and walked here; or at least document the post-delete retention in configuration.md and the §9.2 decisions.
There was a problem hiding this comment.
The retention is real; the regression is not, and the difference decides the fix.
Before this commit the async path wrote under leafSessionId(envelope), which tenant-prefixes before sanitising (run-leaf.ts:183-185), and a turn record's tenant is never empty (ownership.ts:208 falls back to the owner under single). So the key was leaf:result:github-1234-<uuid>, not leaf:result:<uuid> -- cascadeDelete's dataKeys never matched it either. That divergence is the thing the must-fix above this one was about: before, the bytes were retained AND unreachable by every reader. Nothing got worse here.
What is true, and worth stating plainly: a FINISHED async turn's result outlives DELETE /v1/sessions/{id} by up to LEAF_RESULT_TTL_SECONDS, because the per-turn key is reachable only by enumerating the session's turns and the one enumeration walks the owner's OPEN set.
I took your third option, with the reasoning on the record (b346111), because the gap is not specific to results: the finished turn's RECORD carries the envelope -- the same class of caller content -- and has always survived that delete on the same clock. §5.1 chose that when it made the terminal TTL the record's only expiry. Deleting results at session-delete time but not records would be half a fix; deleting both needs a per-session turn set, written at submission and walked by deleteSessionTurns so it covers terminal turns too, and that changes §5.1's rule. That is an M2 change, not a review fix, and §9.2 now carries the limit, what it costs, and why SCAN MATCH is not the cheap alternative (SCAN's cost is the whole keyspace per session delete, not the matches). configuration.md's LEAF_RESULT_TTL_SECONDS row states the post-delete retention, and the comment at the del in deleteSessionTurns points at §9.2.
If you would rather have the index in this PR than in M2, say so and I will add it -- it is about thirty lines plus the contract tests, and it would delete the records as well.
…on limit Two findings from the second review round on PR rossoctl#717. A run that learns mid-leaf that its entry was reclaimed (`touch` -> false) now discards its output: no result write, no finalize, no ack. It used to run all three, and each one corrupts the owner's turn. `writeResult` is an unconditional SET, so finishing second pairs the owner's `done` record with this run's body, which may say `failed`. `finalize` is a CAS the owner wins, so it is a no-op at best. And XACK takes no consumer, so acking retires the OWNER's pending entry -- removing the redelivery that covers the owner dying mid-leaf. New `ProcessOutcome` kind `lost`, which the tally already counts as the claim it was. The residual window is one heartbeat wide (the loss can be discovered between the check and the ack); closing it needs an owner-checked ack, which Redis streams do not have. The second finding is a retention limit, documented rather than fixed. A FINISHED turn's result survives `DELETE /v1/sessions/{id}` and expires on `LEAF_RESULT_TTL_SECONDS`, because the per-turn key is reachable only by enumerating the session's turns and the one enumeration there is walks the owner's OPEN set. Not new with the per-turn key: the finished turn's record carries the envelope and has always outlived that delete on the same clock, which §5.1 chose when it made the terminal TTL the record's only expiry. Making the delete immediate needs a per-session turn index that also changes that rule, so §9.2 records the limit and hands it to M2; configuration.md says it in the `LEAF_RESULT_TTL_SECONDS` row. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Second review round addressed in b346111. Must-fix (duplicate run corrupts the owner's turn) — accepted; my earlier reply on the Post-delete retention of the per-turn result key — the regression premise does not hold (the pre-commit key was tenant-prefixed, so Verification: Assisted-By: Claude Code |
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Summary
Re-review of b346111 ("discard a reclaimed run's output; record the delete-retention limit"), the one commit since the earlier review at 8d2d53a. Both earlier suggestions are resolved:
- Duplicate run after a lost heartbeat: fixed. The heartbeat now sets a
lostflag, andprocessOnereturns a newlostoutcome beforewriteResult,finalizeandack, so the reclaimer owns the turn. The new test fires the beat from insiderunLeafand asserts no result key, no finalize and no ack. The only consumers ofProcessOutcome(leaf-drain-loop.ts,async-worker.ts) special-caseidleanddead_letteredonly, solostis counted as an ordinary claim, as intended. The leftover one-beat window (atouchstill in flight whenclearHbruns) is documented at the check. Closing it would need an owner-checked ack, which streams don't offer. - Session-DELETE retention: documented, with the fix deferred to M2. The author's correction holds: the old async key was tenant-prefixed, so
cascadeDeletenever reached it either. The post-delete retention of finished turns' records and results is now stated in theLEAF_RESULT_TTL_SECONDSrow ofconfiguration.mdand in spec §9.2, and the comment at thedelpoints there. Leaving the per-session turn index to M2 is a reasonable scope call.
No new findings.
Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness leaf-job-runner + test, control-plane turn-store), Docs (configuration reference, design spec §9.2)
Agent/IDE config (.claude/.vscode): none
Commits: 30 commits, all signed-off: yes (DCO passing)
CI status: passing (all 17 checks)
All checks pass. Ready for human review.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up review (drafted with AI assistance)
All of our e1d57b6 items were already fixed at 8d2d53a. b346111 then closes the two findings that came up after that (clawgenti raised the same two):
- Reclaimed run's output: fixed. The heartbeat sets
lost, andprocessOnereturns the newlostoutcome beforewriteResult,finalizeandack, so the reclaimer owns the turn from start to finish. The test fires the beat insiderunLeafand asserts all three are absent. The drain loop and reaper special-case onlyidle/dead_lettered, solostis counted as a normal claim. The remaining one-beat window is documented at the check, and closing it would need an owner-checked XACK, which streams don't have. That's fine. - Retention after session DELETE: documented and deferred to M2. I checked the author's correction and it holds. At 8d2d53a's parent, the async key went through
leafSessionId()(run-leaf.ts:183), which tenant-prefixes it, socascadeDeletenever reached it either. So this isn't a regression. The retention is stated in theLEAF_RESULT_TTL_SECONDSrow, in spec §9.2 and at thedel. Deferring the per-session turn index to M2 is a reasonable scope call.
One nit carried over from an earlier pass that wasn't posted: the idle poll rate (inline).
Assisted-By: Claude Code
| readonly running: boolean; | ||
| } | ||
|
|
||
| const DEFAULT_IDLE_BACKOFF_MS = 250; |
There was a problem hiding this comment.
nit — The claim is non-blocking now, so an idle, armed drain polls every 250 ms. Each poll is XAUTOCLAIM + XREADGROUP, which comes to about 8 Redis commands/s per turn worker × SH_WORKERS (default availableParallelism()) × replicas, all on an empty queue. Previously it was one BLOCK 5000 every 5 s. Moving the sleep out of the slot was the right fix. To keep idle load flat, consider an exponential idle backoff (250 ms doubling to about 2–5 s, reset on any claim), or document the tradeoff next to the constant. Fine to leave for M2.
There was a problem hiding this comment.
Arithmetic checks out: 1000/250 = 4 iterations/s, each one XAUTOCLAIM + XREADGROUP, so ~8 commands/s per turn worker, times SH_WORKERS, times replicas — against one BLOCK 5000 per 5 s before. Took the documentation option (370ed47), not the curve.
Why not the backoff: at M1's deployment shapes — one VM or one compose stack, a single Redis, SH_WORKERS in the single digits — 8 commands/s/worker lands at a fraction of one percent of one Redis core, so the curve buys nothing measurable. And it is not free: it delays pickup for a submission arriving on an idle fleet, and delays the reclaim scan XAUTOCLAIM leads every claim with by the same amount (harmless against MIN_IDLE_MS = 90 s, but it is the same mechanism that bounds how fast a crashed worker's entry comes back). Trading a real latency cost for an unmeasurable load win is the wrong direction until the load is measurable.
DEFAULT_IDLE_BACKOFF_MS now carries the arithmetic and a shortcut: line naming the upgrade and its trigger — many replicas against a usually-empty queue. It also records that no new knob is needed when that day comes: idleBackoffMs is already injectable and armAsyncLeafWorker simply passes nothing, so raising it is a one-line change rather than another env variable (§9.2 keeps SH_ASYNC_DRAIN as this slice's only operator knob). Spec §5.3 now states the aggregate with the multipliers instead of "a few Redis commands a second per idle worker".
Three documents still asserted on main that async fan-out has no P6 consumer. #717 landed the drain loop, so each one was wrong in a way an operator would act on: - `docs/concepts/dispatch-archetypes.md`: archetype A's row said the path does not run on P6. Replaced the combined A/C section with a shipped-path section -- how to turn the drain on per deployment, the submission and collection routes, what changed from the KEDA path, and the three named limits (single tenancy, deploy/k8s unproven, turn_exp in M2). - `docs/reference/http-api.md`: the `async: true` bullet said the consumer "is not" implemented. It now states the two conditions under which the replacement route works, and the control-plane route table lists the async-turn routes, which it never did. - `docs/adrs/0041`: the accepted-cost bullet owed archetype A in full. Discharged for `MOCA_TENANCY=single`, with a dated revision recording what shipped and what the two remaining limits are. #690's scope item 1 (the migration guide) is moot: that guide was deleted with the path in #691. Its mention of a `LEAF_RESULT_TTL_SECONDS` replacement is also moot -- the same variable and default serve both the sync and async paths, so the docs say that rather than invent a successor. The configuration reference already documents `SH_ASYNC_DRAIN` and the drain's two prerequisites; #717 did that work. Also carries the cherry-picked round-three nit fix from PR #717 (the idle backoff's rationale), which was pushed 38 minutes after that PR merged and so never reached main. Refs #686 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Sixteen ADRs still said Proposed although their decisions are in code on main. Each status line now names the merged PRs that implemented it and the date the core landed (format of ADR-0042), and notes what is still owed where only part is built: - 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041) - 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225) - 0032 (rossoctl#249, rossoctl#350, as amended by MI1) - 0035 (rossoctl#251; ADR-0048 adds lease mode beside it) - 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481) - 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620) - 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed) - 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed) - 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the security review's lease sections are signed off) The README index follows, and its 0033 row, which still said Proposed after rossoctl#249 accepted the ADR, is corrected. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…status (#389, #380) #389's items 1-4 landed in #717 and the deploy/k8s half in #765. Item 5, "retire #380's interim contract", is the last one, and the evidence settles it against the obvious reading: a disconnect must still not cancel a sync /runs leaf. mocactl's subagent path posts /v1/runs and then reads /runs/status (packages/mocactl/src/transport/leaf-turn.ts), so it is not holding the socket when the run ends -- an abort would strand every subagent. Flipping it is also breaking under the change policy, on a route kept as a frozen alias. What the "interim" framing was about, a sync run lost on a worker restart, is answered by async turns (ADR-0047 M1-M3), which have redelivery. So the behaviour stays and stops being interim: a test pins it, ADR-0028 records why, and the /v1/runs description states it. The test also asserts no signal reaches runLeaf, because once #391 lands runLeaf takes an optional AbortSignal and the regression #380 feared is a one-line edit. Also corrects harness-openapi.yaml, which still called the authenticated async replacement "designed and not yet implemented" after M1-M3 shipped. No info.version bump: both doc edits are prose, not contract changes. Closes #380. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Summary
A P6 turn worker can now also drain the async leaf-turn queue, so coding-agent subagent fan-out
runs on the same warm worker pool that serves interactive traffic. Implements the M1 slice,
items 1-4, of #389 — item 5 (retiring #380's interim contract) is deferred to M2 per §5.5 of
docs/specs/2026-11-05-p6-async-fan-out-design.md,whose new §9.2 records this slice's six implementation decisions. Builds on #387 and #388 M1.
What landed
@moca/work-queuerestored — Redis Streams commands verbatim, an injected Redis client,and a
ClaimedEntrythat carriesturnIdrather than the whole envelope.leaf-drain-loop.ts), sharing the worker'sTurnCounterwith interactive/turntraffic. §5.3's check-and-take-in-one-tick ordering meansan async claim is gated on total in-flight, with nothing awaited between the measurement and
counter.start().TURN_PATHS(/runs,/run-leaf,/v1/runs).POST /internal/turn-credentialsthenmarkRunning(turnId, deliveryCount). The turn record and every audit entry carry the credentialname; the value exists only on the
TurnConfighanded torunLeaf.leafResultKeydivergence fixed — async results are written underturn.sessionId, soone key shape serves both paths.
reapDeadLetters+gcIdleConsumerssweep armed by every worker. Drain abandons an in-flight leaf without acking,so it is redelivered rather than lost.
(
async_queue_depth,async_oldest_age_ms) polled by slot 0 only — gauges describe thedeployment, so summing them across slots would be wrong.
deploy/vm,deploy/composeanddeploy/k8s. Exactly one newoperator knob,
SH_ASYNC_DRAIN, off by default.kill -9test gated onSH_ASYNC_LIVE_CRASH=1.Hardening from the final review
The whole-branch review mutated 30 behaviours and killed 28. Three findings were fixed:
(
async-worker.test.ts). Deleting a stream destroys its consumer group with it, so every queuedand every delivered-but-unacked entry goes with it and each in-flight async turn is stranded
runningwith nothing to redeliver — anddeploy/composeis a five-minute trial on that sameRedis.
armAsyncLeafWorkernow takes an optionalstream, defaulted, following the precedentpackages/control-plane/src/turn-queue.ts:36already set for this exact hazard.TurnCounterleaked an admission slot permanently if its injectedonChangethrew:start()incremented, then threw before returning the releaser. The drain loop survives such athrow by design, but its
releasestayednull, so atcap = 2two throws would stop theworker claiming async leaves for the rest of its life while it kept serving sync traffic.
onChangeis the realprocess.send, which throwsERR_IPC_CHANNEL_CLOSEDon a closedchannel. Both call sites now route through a
notify()that swallows — safe specificallybecause
onChangesends the absolute count, never a delta, so a dropped send self-heals on thenext one.
stop()teardown nothing tested. RemovingclearInterval(depthTimer)+stopReaper()left 29 tests green, while the 10 s depth poll would outlive
stop()and reopen adestroy()edclient through the reconnecting Proxy's
!isOpenre-arm, inside the 20 s grace. The new testcovers the depth timer only — its name, its comment and the commit subject all say so.
Deleting
stopReaper()alone still leaves the suite green;armAsyncReaper's own stop functionis covered at its own level (
async-worker.test.ts:151-166, fake timers,intervalMs: 1_000),so what is uncovered is the single wiring line. Deliberately not closed here:
ASYNC_REAP_INTERVAL_MSis 60 s, so a time-based assertion costs a 60 s CI wait, and thestructural alternative matches timer handles through global
setInterval/clearIntervalspiesagainst node-redis's own
unref()ed timers. Folded into follow-up 1 below.Two defects found reviewing this PR, both fixed
Found by re-reading the branch as a reviewer after it was opened. Both survived the task
reviews, the whole-branch review and the scoped re-review.
93a8eb4d).reapDeadLettersXACKed eachentry itself, before the caller wrote anything. An acked entry leaves the pending-entries list
for good, so a failed
deadLetterTurnwrite — the sweep logs and moves on — left the turnrunningwith no entry to redeliver: no result, no failure, no retry, until the recordexpired.
leaf-job-runner.tsalready used write-then-ack for its own dead-letter branch; thereaper now matches it. A re-reap is harmless (the XCLAIM reset the idle timer, and
deadLetterTurn's terminal-state guard makes the repeat a no-op). The same commit deletesWorkQueue.purge(), which destroyed the consumer group and deleted the stream and was keptalive only by a test stub.
adb4a248). The control plane validatedLEAF_RESULT_TTL_SECONDSand refused to boot on a bad value; the worker usedparseInt,which reads a blank as
NaNand86400xas86400.writeResulthands the value to Redisas
EX, so on the worker a malformed TTL failed on every result write after the leaf hadrun, not at boot. This branch is what made it reachable — it is the first to wire the variable
into the supervisor's env. Both call sites now share
resultTtlSeconds(env)in the pureturn-record.tsmodule, besideTURN_RECORD_TTL_MARGIN_SECONDSand for the same reason.Zero is refused in both now, since Redis rejects
EX 0.Two findings from that review were deliberately left: a boot-time
[async-reaper] sweep failed: NOGROUPlog line on the immediate sweep (cosmetic, and the fix would change the"sweeps immediately" test), and the per-worker async counts resetting on worker restart
(documented in
createAsyncTally, andrestartsis in the same metrics body).Review notes
Eleven tasks, each with its own spec-compliance and quality gate, then a whole-branch review.
Worth surfacing for the reviewer:
docs/api/openapi.yaml'sExecGrant.execEndpointhaddescription: host:port of the exec Route— an unquoted flow scalar containing:thatpre-commit's
check-yamlrejects. Latent since the field was added; it surfaced here onlybecause this is the first commit to touch the file under a working
pre-commit install.Content-preserving quote.
@moca/work-queueon@moca/knative-serverand@moca/session-backend. A workspace importthat resolves only by accident of hoisting is a latent break.
packages/supervisorso the gated live-crash test's importsresolve for
tscand for vitest'sskipIfevaluation. Workspace links only, no externalpackages.
LEAF_RESULT_TTL_SECONDSnow also reaches the supervisor, not just the control plane.Without it an operator's configured TTL was honoured for control-plane-written results and
silently ignored for the async worker's own leaf results.
mainwas merged in (e1d57b62), not rebased — a rebase needs a force-push. Two filesconflicted, both from adjacent edits:
handlers.ts(this branch'sgetMetricsagainst adeleted blank line) and
configuration.md(prettier realigns a whole markdown table when onecell's width changes, so the OIDC rows and one
LEAF_RESULT_TTL_SECONDScell collided over34 lines of whitespace).
sed -icalls indeploy/vm/tests/setup-vm.test.share fixed to the file's own-i.bakidiom. Not this branch's:294054a6added them GNU-style, which aborts the wholesuite on BSD sed before it validates anything — so the VM deploy suite, one of the two this
branch changed, could not run on macOS at all.
Known-parked, with reasons
SH_ASYNC_DRAINships commented indeploy/vm/env/supervisor.env.examplebecausecompose.test.shbuilds its mirror list by grepping uncommented keys; commented and deleted arethe same runtime state there (unset → the server's default), so this costs discoverability in
the file an operator reads, not behaviour.
docs/reference/configuration.mdcarries the row.make test-deployis red atdeploy/microvm/tests/build-snapshot.test.shon two shellcheckSC2016 findings in
build-snapshot.sh:980,1079. Not this branch's —deploy/microvm/haszero commits and an empty diff over the range, and the 52 changed files include no
Makefile,scripts/, or pre-commit config, so the flagged file, its test, and the invocation arebyte-identical to base. The two shell suites that are this branch's (
setup-vm.test.sh,compose.test.sh) pass; both were run directly.asyncConsumerId's ppid fallback can collide across two hosts that share one Redis and bothallocate the same pid. Bounded today because the fallback applies only when
HOSTNAMEis absentand neither M1 deployment reaches it with more than one host. Carries a
shortcut:comment.Correction to the record
Commit
70ad79eb's message claims "all five packages green". That was untrue when written —packages/supervisorwas already red from a k8s/vm env-parity regression introduced earlier in thebranch. The regression is fixed in
ac6fc34f, whose message states the correction. History was notrewritten because the claim is part of the branch's audit trail.
Follow-up issue candidates
one issue: the OpenAPI response-schema hole (renaming a metric in
docs/api/openapi.yamlaloneleaves the contract test green; pre-existing and file-wide across ~30 routes); the
docs/api/CHANGELOG.md-vs-CP_ERROR_CODESdrift check; moving theasyncStatsspread fromfirst to last in
startStatsReporterleaves 40 tests green even though the comment thereclaims the order guards the
typediscriminant (harmless today —AsyncWorkerStatshas notypekey); and the half-coveredstop()teardown above, whose honest fix is an injected reapinterval at the
armAsyncLeafWorkerseam.deploy/microvm/build-snapshot.sh, somake test-deployisgreen from a clean checkout.
Test results
On the merged tree (
e1d57b62):knative-servercontrol-planemocactlsupervisorwork-queueharnesscontext-overlay.test.ts"in a real shell, a populated revision with workspace/ links the view to it", a pre-existing macOSmvfailure unrelated to this branchdeploy/vm/tests/setup-vm.test.shanddeploy/compose/tests/compose.test.shpass.make typecheckandmake check-links(198 files, 0 broken) pass.One flake seen, in a file this branch adds:
run-leaf-route.test.ts"does not accept a sandboxselector" failed once with "Number of calls: 0" — its
runLeafspy was never reached becausethe saturation test in the same file holds admission slots. The file alone and the full suite
both pass on re-run.
Checklist
git commit -s). All 27 verified.make lintand the tests for the touched packages pass. One caveat:make lint'shadolint-dockerhook needs a Docker daemon this dev host does not have (podman only), sothe target exits non-zero locally for that reason alone; every other hook passes.
or
docs/page, with the right maturity label.make check-linkspasses.docs/specs/README.md— the spec is already registeredas P6.4; this branch only adds §9.2 to it.
Assisted-By: Claude Code