Skip to content

feat(server): bound an owner's running async leaves cluster-wide (#391) - #933

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
cwiklik:feat/391-owner-fairness
Nov 20, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
cwiklik:feat/391-owner-fairness

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

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_SUBJECT lives in one worker's SubjectCounter map, and a worker runs one queued leaf
at 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 one
owner occupies all N drains.

How

  • TurnStore.reserveRunningSlot / releaseRunningSlot over a per-owner zset
    sh:cp:owner:<subjectHash>:running. ZADD-then-ZCARD, write-first for reserveOpenSlot's measured
    reason: N simultaneous readers of an under-limit ZCARD would all pass.
  • MOCA_ASYNC_RUNNING_PER_OWNER gates it. Unset = off, with no default derived from S: the
    value is deployment-wide so S cannot imply it, and a cap appearing on upgrade would start pacing
    a 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 how
    many may run.
  • Both caps answer through the one existing admitOwner hook, so an entry over the cap takes the
    already-shipped hand-back path: XCLAIM … JUSTID RETRYCOUNT <before> (unrun and unpenalised,
    invisible to maxAttempts), counted as async_deferred_subject, with the same 10-minute
    DEFER_CEILING_MS fairness 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 admitOwner before the claim
handshake — so a paced turn mints no credential, never flips to running, and writes no audit entry
— and released in the runner's finally on every path, redelivered and lost included. That
makes the count self-healing: no staleness horizon, no reaper dependency. toTerminal and
deleteSessionTurns ZREM 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
cancelRequested does — 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 that
caveat 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.costUsd is
refused at submission.

Tests

  • turn-store-contract.ts: two cases over both backings (fake and real Redis) — owner-scoped
    counting, 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 back
    deferred while worker 1 holds the owner's only cluster-wide slot, the paced record stays queued
    with attempts: 0, and worker 2 completes once worker 1's leaf ends. Plus one asserting every
    entry is admitted when the knob is unset. Both drive the exported ownerAdmission from production
    code. Mutation-checked: raising runningCap: 1 to 9 fails the deferral assertion.
  • subject-quota.test.ts: the parser is off unless set and derives nothing from S.

make typecheck and make check-links pass; make lint is clean except hadolint-docker, which
needs a Docker daemon. packages/control-plane 2011 passed. Two pre-existing environmental failures,
both unrelated and not in files this PR touches: workload-runs.test.ts hit a local VPN agent on its
ephemeral port (passes in isolation) and context-overlay.test.ts fails on a macOS mv into a
chmod a-w temp dir.

Docs

docs/reference/configuration.md (new row plus a cross-reference on SH_TURNS_PER_SUBJECT), the
four open on #391 pointers (sizing-and-scaling.md, single-vm.md, kubernetes.md,
api/CHANGELOG.md), the three deploy targets (deploy/vm env example, compose, k8s optional
ConfigMap 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

  • Set the same value on every worker. Each enforces it independently against the Redis count, so
    differing values leave the effective bound to whichever worker claimed first.
  • A deferred entry waits out the full 90 s reclaim window per deferral. Size the cap for that
    latency, not only for the share.
  • Only meaningful with SH_ASYNC_DRAIN.

Not covered: an end-to-end run on deploy/compose with the knob set — the cluster-wide path is
proven by the two-queue integration test against real Redis.

Assisted-By: Claude Code

…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 ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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:

  • reserveRunningSlot is 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; releaseRunningSlot is a plain ZREM, so releasing twice or never-held is safe.
  • The deferral path gives back both counters before returning null, leaves the record queued with attempts 0, and mints no credential — the test asserts all three.
  • runningPerOwnerCap is 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 local SubjectCounter is 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.

Comment thread packages/server/src/async-worker.ts Outdated
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());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: this 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.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: the comment'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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

cwiklik commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

All three addressed in 0f85ad0 — replies on each thread.

  • must-fix (leaked local slot): the reserve is in a try that calls local() before rethrowing. The second path you flagged no longer exists: with the cap inside the script, a refusal has no member to give back, so there is no releaseRunningSlot on that branch. Two unit tests on the real ownerAdmission.
  • add-then-count (suggestion, taken): RESERVE_RUNNING_LUA does ZADD, ZCARD and the conditional ZREM in one script, so two workers can no longer both lose. cap is now a parameter of reserveRunningSlot. New contract case over both backings, mutation-checked against real Redis.
  • k8s moca-settings (suggestion, taken as the sentence): the operate page and the manifest comment both say to roll deployment/moca-supervisor, with the reason. I did not plumb it through setup.sh — that turns an off-by-default knob into an operator-facing input plus hash and test changes.

make typecheck, make fmt and make check-links clean; packages/control-plane 2013 passed, packages/server 608 passed, both suites fully green this run.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 try that calls local() before rethrowing, and a new unit test asserts subjects.inFlight(OWNER) === 0 after 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 that releaseRunningSlot is 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-2 over a cap of 1 comes back 2 and leaves only t-1 holding the slot; t-3 the same), and the fake Redis interprets the script by identity, as it does for CAS_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-hash and give the kubectl rollout restart to 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.

@pdettori
pdettori merged commit f7263ff into rossoctl:main Nov 20, 2026
18 checks passed
@pdettori pdettori added this to the v0.11.0 milestone Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants