Skip to content

feat(knative-server): per-subject admission quota on /turn - #542

Merged
pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:fix/360-subject-admission-quota
Oct 15, 2026
Merged

pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:fix/360-subject-admission-quota

Conversation

@pdettori

Copy link
Copy Markdown
Member

Closes #360

What

A per-subject in-flight turn cap on /turn, enforced in the worker after resolveTurnAuth — the
only place the subject is known before the turn runs. A subject over the cap is refused with
429 {"error":"subject_quota_exceeded"} plus Retry-After, a code distinct from the supervisor's
pool-wide overloaded, so a client can tell "you are over your share" from "the host is full".

Why here, and the scope trade

MI1 §13 assigns the final home of this quota to S2's grants (supervisor-side, host-wide). What
this ships is the interim the issue itself names: the harness after resolveTurnAuth. The count is
per-worker, in-process — deliberately not shared state on the turn hot path, per this tier's
own rule that a Redis that cannot answer must not gate a caller. The bound it buys: a subject holds
at most cap of each worker's S slots, i.e. cap/S of the host, so one user can no longer take
every slot. S2 moves enforcement to the supervisor for exactness; §13 now records both facts.

Config

SH_TURNS_PER_SUBJECT — default max(1, ⌊S/2⌋) from SH_TURNS_PER_WORKER (the supervisor's fork
passes S through to the workers), so a single subject can never hold more than half the pool.
Neither variable set (the deprecated standalone Knative tier) ⇒ no quota. Unauthenticated turns
have no subject and are untouched; /runs is out of scope (not a turn slot).

How

  • packages/knative-server/src/subject-quota.ts — turnsPerSubjectCap (env parsing, malformed
    values fall back to the derived default) and SubjectCounter (refcounted in-flight map,
    idempotent release, entries deleted at zero).
  • turn-slot.ts generalized from one end-callback to a list: the worker's turn count and the
    subject's quota slot share one lifecycle — released on response close, or on adoption for a
    detachable turn. Attaching outside a worker now creates the slot, so a standalone detachable
    turn cannot leak its subject slot at response close.
  • handleTurn acquires after auth, before the detach/stream dispatch, so sync, streaming and
    detachable turns are all gated.

Tests

  • subject-quota.test.ts — cap parsing (operator override, derived default, S=1, off) and counter
    semantics (boundary, release, idempotent release, independence, no map growth).
  • turn-slot.test.ts — multi-end lifecycle: all ends once on close, adoption defers them, the
    create-if-absent path, the no-slot no-op.
  • subject-quota-route.test.ts — the issue's acceptance test verbatim: subject A at its cap is
    refused while subject B is admitted; the SSE branch refuses before any frame; no-config means no
    quota; an unauthenticated caller takes no slot.

Docs: MI1 §13 marks #360 closed in-product; the knob is documented in
deploy/vm/env/supervisor.env.example, set on deploy/k8s (env parity) and passed through by
deploy/compose; /turn's 429 is in harness-openapi.yaml; one sentence each in
sizing-and-scaling.md and security-model.md.

🤖 Generated with Claude Code

The supervisor's admission gate bounds the worker pool as a whole, so one
subject could take every turn slot on a host and starve every other user
(rossoctl#360). The subject is known only after resolveTurnAuth, so the cap is
enforced there: SH_TURNS_PER_SUBJECT (default half the per-worker slots,
max(1, floor(S/2))) in-flight turns per worker, refused with a distinct
429 subject_quota_exceeded + Retry-After so a client can tell "over your
share" from the supervisor's pool-wide "overloaded". The count is
per-worker -- no shared state joins the turn hot path -- and the slot
rides the turn's own lifecycle via a generalized turn-slot (response
close or adoption). Unauthenticated callers and /runs are unchanged.

Closes rossoctl#360

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori requested a review from cwiklik as a code owner October 15, 2026 15:14
…losure

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 15, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Per-subject quota design looks right (post-auth, per-worker, distinct subject_quota_exceeded code, shared slot lifecycle), and the tests are thorough. There is one blocking issue: a subject slot leaks permanently if the client disconnects while resolveTurnAuth is awaiting the control-plane exchange (inline #1/#2).

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (knative-server), YAML (compose/k8s), env template, Docs/OpenAPI/spec, Tests
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing

Also (files outside the diff):

  • suggestion: docs/reference/configuration.md has no row for SH_TURNS_PER_SUBJECT next to SH_TURNS_PER_WORKER.
  • nit: packages/supervisor/src/admin.ts ENV_ALLOWLIST doesn't include SH_TURNS_PER_SUBJECT. An operator debugging a 429 would want to see it in the env view.
  • FYI: because the supervisor always requires S and forks workers with its env, the quota is on by default in every P6 deployment (S → ⌊S/2⌋ per subject per worker). That may be worth a release note.

);
return;
}
attachTurnSlot(res, release);

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 — the subject slot leaks if the client disconnects during resolveTurnAuth.

resolveTurnAuth awaits the control-plane exchange (turn-auth.ts:254). A client that leaves during that await makes res emit 'close' first (the comment in handleDetachableTurn describes the same case). Then:

  • worker path: the worker's slot already ran end() and has ended = true. acquire() increments the subject's count, and attachTurnSlot pushes release onto a list that never runs again.
  • standalone path: ensureSlot adds res.on('close') after 'close' was already emitted, so it never fires.

The subject's count stays incremented for the life of the process. With S ≤ 3 (cap 1), one Ctrl-C or client timeout during the exchange locks that user out of the worker with subject_quota_exceeded until restart. Routing won't steer around it, because the worker's own load counter was released. The detachable branch is affected too: it returns early on res.destroyed after this acquire.

Suggest returning before the acquire when res.destroyed, plus making attachTurnSlot safe (next comment). Please add a route test: the scripted control plane delays its reply, the client aborts, then a fresh turn for the same subject with SH_TURNS_PER_SUBJECT=1 gets 200.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed on both paths before fixing: the worker's slot ends on the close during the await (so the late push never runs), and standalone, ensureSlot registers the 'close' listener after the event fired — an EventEmitter never replays it. Fixed with both halves you suggested: handleTurn returns before the acquire when res.destroyed (same signal the detachable branch already returns early on), and attachTurnSlot no longer drops a late end (next thread). The requested route test is in — CP gate holds the exchange, the client aborts, the gate opens, and a fresh turn for the same subject at cap 1 gets 200 with executeTurn never called for the departed request.

* too, rather than letting it fire at response close while the turn itself runs on.
*/
export function attachTurnSlot(res: ServerResponse, end: () => void): void {
ensureSlot(res).ends.push(end);

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 (same root cause as the server.ts comment) — attachTurnSlot silently drops end when the slot has already ended, or when the response closed before the slot existed. Suggest:

export function attachTurnSlot(res: ServerResponse, end: () => void): void {
  const slot = ensureSlot(res);
  if (slot.ended || (res.destroyed && !slot.adopted)) { end(); return; }
  slot.ends.push(end);
}

Please add a unit test here too: emit 'close', then attach, and the end must have been called.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Implemented as suggested, including the adopted exception — a detachable turn's slot outlives its destroyed response, so a late end attached there still belongs to the adopted release. Unit tests: close-then-attach runs the end at once (the worker half, with the worker's own end already on the slot), destroyed-unadopted runs it at once, destroyed-but-adopted defers to the release.

Comment thread deploy/k8s/base/supervisor.yaml Outdated
- { name: SH_TURNS_PER_WORKER, value: '4' }
# Half of S, spelled out: the per-subject quota's default, made explicit so the two
# knobs move together (#360; MI1 §13).
- { name: SH_TURNS_PER_SUBJECT, value: '2' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit — "made explicit so the two knobs move together": a literal '2' does the opposite. Bumping SH_TURNS_PER_WORKER to 8 leaves the cap at 2 (a quarter of the pool, not half). Either drop this line and rely on the derived default, or reword it to "pinned; update alongside SH_TURNS_PER_WORKER".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Dropped the line rather than reworded: the derived default (half of S) is exactly the coupling a pinned literal breaks, so the manifest now leaves it unset and NOT_ENV_ON_K8S records why — its doc comment is widened from "credential transport" to also cover values one tier deliberately derives.

…during the exchange

Review round 1 on rossoctl#542, blocking: resolveTurnAuth awaits the control-plane
exchange, and a client that leaves during that await made the acquire that
follows leak its slot for the life of the process -- on the worker path the
response's slot had already ended (a late push onto its list never runs), and
on the standalone path the 'close' listener was registered after the event had
fired, so it never ran either. With cap 1, one abandoned request locked that
subject out of the worker until restart, and routing could not steer around it
because the worker's own load counter HAD been released.

Two halves, as the review suggested: handleTurn returns before the acquire
when res.destroyed (the detachable branch already returned early on the same
signal), and attachTurnSlot runs a late end at once when the slot has ended or
the response is destroyed without adoption -- an adopted slot keeps deferring
to its release, since a detachable turn outlives its response.

Also from the review: drop the pinned SH_TURNS_PER_SUBJECT from deploy/k8s
(the derived default is half of S; a pinned literal drifts when S changes) with
a NOT_ENV_ON_K8S reason, add the configuration.md row, and include the knob in
the supervisor's ENV_ALLOWLIST so /metrics shows it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

Round 1 addressed in 50bc38c — all three inline threads have replies; the shape of it:

  • Blocking leak (exchange-abort): confirmed on both paths, fixed with both halves — handleTurn returns before the acquire when res.destroyed, and attachTurnSlot runs a late end at once instead of dropping it (an adopted slot still defers to its release). New route test: CP gate holds the exchange, client aborts, gate opens, fresh turn for the same subject at cap 1 → 200, executeTurn never called for the departed request. Three turn-slot unit tests cover the late-attach guard's cases.
  • k8s pin: dropped rather than reworded — the derived default is half of S, so a pinned '2' is the drift; NOT_ENV_ON_K8S carries the reason.
  • configuration.md: SH_TURNS_PER_SUBJECT row added beside SH_TURNS_PER_WORKER.
  • ENV_ALLOWLIST: the knob is in, so /metrics's env view shows it (admin-allowlist.test.ts reads the literal from source and only rejects secret-shaped names, so no test change was needed).

On the release note: agreed that the on-by-default quota (every P6 deployment: S → ⌊S/2⌋ per subject per worker) is a changed default under change-policy rule 5, so it belongs in the next release's Upgrade notes — flagged here for whenever that cut happens, since v0.6.1 predates this.

knative-server (578) and supervisor (217) suites, compose, lint/typecheck/fmt: green.

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

Round 1 is addressed in 50bc38c, and I verified each fix against the diff:

  • Exchange-abort leak: handleTurn returns on res.destroyed before the acquire (acquire → attach is synchronous, so there's no window), and attachTurnSlot now runs a late end at once unless the slot is adopted. The route test and three unit tests cover both halves and the adopted exception.
  • k8s pin dropped, and NOT_ENV_ON_K8S documents why. The configuration.md row and the ENV_ALLOWLIST entry are in.
  • Thanks for queueing the on-by-default quota for the next release's Upgrade notes.

@pdettori
pdettori merged commit 4c93f24 into rossoctl:main Oct 15, 2026
15 checks passed
@pdettori
pdettori deleted the fix/360-subject-admission-quota branch October 15, 2026 19:17
pdettori added a commit that referenced this pull request Oct 20, 2026
…'s 429

k8s-kind-e2e failed intermittently at claim 12 with "first '', then
'moca-sandbox-N'": the run's artifact shows the turn's whole SSE body was
{"error":"subject_quota_exceeded"}, and the supervisor log shows why --
over_admission up to an actual 3 in flight on one worker. The where1
burst is four turns of ONE subject on a pool whose trial size fits them
exactly (W=2, S=4, so the per-subject cap is 2 per worker), and
leastInFlight's optimistic estimate can be lowered by a worker's stale
load report after the next hand-off -- over-admission that section 3.9
accepts by design and counts -- so a burst can hand one worker a third
turn, which the quota refuses.

The quota's own contract (spec section 13, #542) is that
subject_quota_exceeded is a distinct code sent with Retry-After so a
client can tell "you are over your share" from "the host is full" and
back off: the smoke now retries that code alone, twice with a 2 s
backoff (a lease frees in 2 s). Any other failure, or a third refusal,
fails the claim as before. The same signature also failed on main at
983dae6 and 12536a6, so this is not this branch's doing.

Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Supervisor: per-subject admission quota

2 participants