Repository navigation
feat(server): bound an owner's running async leaves cluster-wide (#391) - #933
Conversation
…soctl#391) `SH_TURNS_PER_SUBJECT` lives in one worker's memory, and a worker runs one queued leaf at a time, so an owner's async-only fan-out never reaches the cap and one owner can occupy every worker's drain. Add the cluster-wide half: - `TurnStore.reserveRunningSlot` / `releaseRunningSlot` over a per-owner zset (`sh:cp:owner:<hash>:running`), ZADD-then-ZCARD so N simultaneous readers of an under-limit count cannot all pass. - `MOCA_ASYNC_RUNNING_PER_OWNER` gates it. Unset = off, with no default derived from S: the value is deployment-wide, and a cap appearing on upgrade would pace a single-owner deployment's own fan-out. - Both caps answer through the existing `admitOwner` hook, so an entry over the cap takes the same unrun, unpenalised hand-back (`async_deferred_subject`) and the same 10-minute `DEFER_CEILING_MS` fairness yield. A slot is one DELIVERY's claim, taken before the claim handshake (so a paced turn mints no credential and writes no audit entry) and released in the runner's `finally` on every path, `redelivered` and `lost` included. The count is therefore self-healing and needs no staleness horizon; `toTerminal` and `deleteSessionTurns` ZREM as well, covering a SIGKILLed worker. Enforced in the worker rather than behind a new control-plane route for the same reason `cancelRequested` is: in M1 the records and the queue share one Redis. A deployment that split the keyspaces would need the route. Tests: two contract cases over both TurnStore backings, and a two-queue integration test that defers an owner already at their cap on another worker and completes once that worker's leaf ends. Per-session spend attribution stays open on rossoctl#391. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Review — feat(server): bound an owner's running async leaves cluster-wide (#391)
The shape is right: one admitOwner hook for both caps, the deferred path unchanged and unpenalised, and the release story is the part I expected to be hard and isn't — a member per delivery, released in processOne's finally on every path (redelivered and lost included), with toTerminal and deleteSessionTurns covering the two cases the worker cannot. The two-drain integration test is the right test, and driving the real ownerAdmission rather than a copy of it is the right call.
What I checked:
reserveRunningSlotis ZADD-then-ZCARD, separate from the open set, idempotent per turn (a redelivery re-adds the same member), and owner-scoped by the same tag;releaseRunningSlotis a plain ZREM, so releasing twice or never-held is safe.- The deferral path gives back both counters before returning
null, leaves the recordqueuedwithattempts0, and mints no credential — the test asserts all three. runningPerOwnerCapis off unless set, derives nothing from S, and reads 0/malformed as unset with the reasons spelled out; the wiring reaches every worker through the supervisor's env, and the compose/VM/k8s manifests, config table, three operate pages, spec and CHANGELOG all agree.- The A cap stays shared with sync
/turn: the localSubjectCounteris still the first check, so an owner at their per-worker cap costs no Redis write.
One must-fix inline: the local slot can leak if the cluster-wide reserve throws. Two suggestions: the add-then-count window at the turn store (safe but can under-admit), and the k8s instruction to add the key to moca-settings (the pods do not roll for a key setup.sh does not own).
Author: cwiklik (MEMBER — maintainer). One commit, signed off. CI 18/18.
| const local = subjectCap === undefined ? noop : subjects.acquire(owner, subjectCap); | ||
| if (!local) return null; | ||
| if (runningCap === undefined) return local; | ||
| const running = await turns.reserveRunningSlot(owner, turnId, now()); |
There was a problem hiding this comment.
must-fix: this await sits between subjects.acquire and the returned release, so a throw here leaks the per-worker slot for the life of the process — and TurnStore.guard turns every Redis failure into a throw (CpError('redis_unavailable')), which the drain loop then catches and logs as a failed claim. With SH_TURNS_PER_WORKER required, subjectCap is essentially always set, so the leak lands in production: each blip permanently costs that owner one of their max(1, ⌊S/2⌋) slots on that worker, and if enough accumulate the owner is refused on it until restart, sync /turn included (the counter is shared). The same applies one line down if releaseRunningSlot throws on the refusal path: local() is then never called. Fix: take the local slot inside a try and give it back on any throw — e.g. let running; try { running = await turns.reserveRunningSlot(...) } catch (err) { local(); throw err }, and in the over-cap branch try { await releaseRunningSlot(...) } catch {} finally { local() }. (The cluster member is not the problem: if the ZADD landed, it is this turn's own member — idempotent on redelivery, and cleared by toTerminal.)
There was a problem hiding this comment.
@/tmp/kagenti/tdd/moca/reply1.md
| * The caller MUST `releaseRunningSlot` on every way out, including the ones that leave the record | ||
| * `running` for another worker to reclaim: the member describes a delivery in flight, not a turn. | ||
| */ | ||
| async reserveRunningSlot(owner: string, turnId: string, now: number): Promise<number> { |
There was a problem hiding this comment.
suggestion: the comment's claim holds one way only: N workers reading an under-limit count cannot all PASS, but with add-then-count they can all FAIL. Worker A ZADDs (count 1), worker B ZADDs (count 2), then each ZCARDs — at cap 1 both see 2 and both hand their entry back, though neither is running anything. With replicas > 1 and one owner's fan-out, that is exactly the contended case this knob exists for, and each collision costs the entries a reclaim window. A Lua script (ZADD, ZCARD, and a conditional ZREM when over) makes it exact: at most the cap admitted, and the rest deferred only when the cap is genuinely reached. Not a correctness bug — the count can never exceed the cap — so I would not block on it, but it is worth a sentence in the comment either way.
There was a problem hiding this comment.
@/tmp/kagenti/tdd/moca/reply2.md
| backlog never reaches it and is drained FIFO -- one owner's deep queue ahead of another's single | ||
| turn. At `replicas` > 1 that is what `MOCA_ASYNC_RUNNING_PER_OWNER` is for (#391): it caps an owner's | ||
| RUNNING leaves across every pod, counted in Redis, and is the only one of the two caps a pod-local | ||
| counter cannot provide. Unset by default; add it to `moca-settings` to turn it on, and give every pod |
There was a problem hiding this comment.
suggestion: "add it to moca-settings to turn it on" is not enough on its own: the supervisor pods read it as env at start, and their moca.dev/settings-hash annotation covers only the keys setup.sh writes (write_settings's fixed set). A key added by hand does not change the hash, so the pods keep the old environment until something else rolls them. Say so (roll the supervisor after adding it), or carry the setting through setup.sh as an input so it joins the hash and a re-run rolls the pods for you.
There was a problem hiding this comment.
@/tmp/kagenti/tdd/moca/reply3.md
…cap (rossoctl#391) Review on rossoctl#933. must-fix: `ownerAdmission` awaited `reserveRunningSlot` between taking the per-worker slot and returning its release, so a throw leaked that slot for the life of the process -- and `TurnStore.guard` turns every Redis blip into one, which the drain loop catches and logs as a failed claim. The counter is shared with sync `/turn`, so enough blips would refuse that owner's interactive turns too. The reserve now runs in a try that gives the local slot back before rethrowing. The cap moves into Redis as `RESERVE_RUNNING_LUA` (ZADD, ZCARD, and ZREM the member again when over), so the two halves are atomic. Separately each is exact in one direction only: counting first lets N simultaneous readers of an under-limit count all pass, which is why the write came first -- but writing first has N simultaneous writers all see the full total and all hand their entry back with none of them running, exactly the contended case this cap exists for, at a reclaim window each. One script also removes the second throw path: over the cap the member is already gone, so the refusal owes nothing but the local slot. k8s: `setup.sh` does not write the key, so adding it to `moca-settings` by hand leaves `moca.dev/settings-hash` unchanged and the pods keep their old environment. Both the manifest comment and the operate page now say to roll the supervisor. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
All three addressed in 0f85ad0 — replies on each thread.
|
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Review — fix(server): no leaked slot on a reserve throw, and an exact running cap (#391)
All three items are addressed, and the second one is better than what I asked for.
- The leak is closed. The reserve runs inside a
trythat callslocal()before rethrowing, and a new unit test assertssubjects.inFlight(OWNER) === 0after the throw. The over-cap branch no longer releases anything — correct, because the script has already removed this turn's member — and the test pins thatreleaseRunningSlotis not called, so the two refusers can no longer remove each other's member. - The cap is exact.
RESERVE_RUNNING_LUA(ZADD, ZCARD, ZREM when over) makes the two halves atomic: no all-pass and no all-defer, which is the contended case the cap exists for. The contract suite grew the case that shows it (t-2over a cap of 1 comes back 2 and leaves onlyt-1holding the slot;t-3the same), and the fake Redis interprets the script by identity, as it does forCAS_STATE_LUA. The spec's paragraph now explains both failure modes rather than only the one the old ordering fixed. - The k8s instruction is fixed in both places: the manifest comment and the operate page say the key does not change
moca.dev/settings-hashand give thekubectl rollout restartto run; "a rise after the restart" is the observable.
CI 18/18. This clears the CHANGES_REQUESTED from 2d63917.
Author: cwiklik (MEMBER — maintainer). Two commits, both signed off.
What
Closes the fourth acceptance criterion of #391 — "one subject can't take every slot" — on the async
drain, by adding the cluster-wide half of per-owner bounding.
SH_TURNS_PER_SUBJECTlives in one worker'sSubjectCountermap, and a worker runs one queued leafat a time, so the cap that shipped earlier bounds an owner's mixed load on one worker: an
async-only fan-out never reaches
max(1, ⌊S/2⌋), nothing is ever deferred, and with N workers oneowner occupies all N drains.
How
TurnStore.reserveRunningSlot/releaseRunningSlotover a per-owner zsetsh:cp:owner:<subjectHash>:running. ZADD-then-ZCARD, write-first forreserveOpenSlot's measuredreason: N simultaneous readers of an under-limit ZCARD would all pass.
MOCA_ASYNC_RUNNING_PER_OWNERgates it. Unset = off, with no default derived fromS: thevalue is deployment-wide so
Scannot imply it, and a cap appearing on upgrade would start pacinga single-owner deployment's own fan-out, which is the common case. It is the pair of the control
plane's
MOCA_ASYNC_QUEUED_PER_OWNER— that one bounds how many turns may wait, this one howmany may run.
admitOwnerhook, so an entry over the cap takes thealready-shipped hand-back path:
XCLAIM … JUSTID RETRYCOUNT <before>(unrun and unpenalised,invisible to
maxAttempts), counted asasync_deferred_subject, with the same 10-minuteDEFER_CEILING_MSfairness yield. No new metric, no new route, no change to the queue's shape.A slot is one DELIVERY's claim, not the turn's. It is taken in
admitOwnerbefore the claimhandshake — so a paced turn mints no credential, never flips to
running, and writes no audit entry— and released in the runner's
finallyon every path,redeliveredandlostincluded. Thatmakes the count self-healing: no staleness horizon, no reaper dependency.
toTerminalanddeleteSessionTurnsZREM as well, covering a SIGKILLed worker whose entry is later dead-lettered.Why the worker enforces it rather than a new control-plane route: the same reason
cancelRequesteddoes — in M1 the turn records and the queue share one Redis(
async-worker.ts:300-303). A deployment that split the keyspaces would need the route, and thatcaveat is in the spec amendment.
Scope
Per-session spend attribution stays open on #391 and moves to its own issue: it wants the
per-model price table the repo does not have (#359), which is the same reason
caps.costUsdisrefused at submission.
Tests
turn-store-contract.ts: two cases over both backings (fake and real Redis) — owner-scopedcounting, idempotent re-reserve, the open set left untouched, release/re-reserve, release of an
unheld member as a no-op, and freeing at the terminal transition and with the session.
async-drain.integration.test.ts: a new two-queue test — worker 2's claim comes backdeferredwhile worker 1 holds the owner's only cluster-wide slot, the paced record staysqueuedwith
attempts: 0, and worker 2 completes once worker 1's leaf ends. Plus one asserting everyentry is admitted when the knob is unset. Both drive the exported
ownerAdmissionfrom productioncode. Mutation-checked: raising
runningCap: 1to9fails the deferral assertion.subject-quota.test.ts: the parser is off unless set and derives nothing fromS.make typecheckandmake check-linkspass;make lintis clean excepthadolint-docker, whichneeds a Docker daemon.
packages/control-plane2011 passed. Two pre-existing environmental failures,both unrelated and not in files this PR touches:
workload-runs.test.tshit a local VPN agent on itsephemeral port (passes in isolation) and
context-overlay.test.tsfails on a macOSmvinto achmod a-wtemp dir.Docs
docs/reference/configuration.md(new row plus a cross-reference onSH_TURNS_PER_SUBJECT), thefour
open on #391pointers (sizing-and-scaling.md,single-vm.md,kubernetes.md,api/CHANGELOG.md), the three deploy targets (deploy/vmenv example, compose, k8s optionalConfigMap key — matching
MOCA_ASYNC_QUEUED_PER_OWNER's precedent), and spec §12's owed item,amended to "done in #391, except for the queue's shape".
Operator notes
differing values leave the effective bound to whichever worker claimed first.
latency, not only for the share.
SH_ASYNC_DRAIN.Not covered: an end-to-end run on
deploy/composewith the knob set — the cluster-wide path isproven by the two-queue integration test against real Redis.
Assisted-By: Claude Code