Repository navigation
feat(knative-server): per-subject admission quota on /turn - #542
Conversation
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]>
…losure Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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.mdhas no row forSH_TURNS_PER_SUBJECTnext toSH_TURNS_PER_WORKER. - nit:
packages/supervisor/src/admin.tsENV_ALLOWLISTdoesn't includeSH_TURNS_PER_SUBJECT. An operator debugging a 429 would want to see it in theenvview. - 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); |
There was a problem hiding this comment.
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 hasended = true.acquire()increments the subject's count, andattachTurnSlotpushesreleaseonto a list that never runs again. - standalone path:
ensureSlotaddsres.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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| - { 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' } |
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
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]>
|
Round 1 addressed in 50bc38c — all three inline threads have replies; the shape of it:
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
left a comment
There was a problem hiding this comment.
Round 1 is addressed in 50bc38c, and I verified each fix against the diff:
- Exchange-abort leak:
handleTurnreturns onres.destroyedbefore the acquire (acquire → attach is synchronous, so there's no window), andattachTurnSlotnow 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_K8Sdocuments why. The configuration.md row and theENV_ALLOWLISTentry are in. - Thanks for queueing the on-by-default quota for the next release's Upgrade notes.
…'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]>
Closes #360
What
A per-subject in-flight turn cap on
/turn, enforced in the worker afterresolveTurnAuth— theonly place the subject is known before the turn runs. A subject over the cap is refused with
429 {"error":"subject_quota_exceeded"}plusRetry-After, a code distinct from the supervisor'spool-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 isper-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
capof each worker's S slots, i.e.cap/Sof the host, so one user can no longer takeevery slot. S2 moves enforcement to the supervisor for exactness; §13 now records both facts.
Config
SH_TURNS_PER_SUBJECT— defaultmax(1, ⌊S/2⌋)fromSH_TURNS_PER_WORKER(the supervisor's forkpasses 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;
/runsis out of scope (not a turn slot).How
packages/knative-server/src/subject-quota.ts—turnsPerSubjectCap(env parsing, malformedvalues fall back to the derived default) and
SubjectCounter(refcounted in-flight map,idempotent release, entries deleted at zero).
turn-slot.tsgeneralized from one end-callback to a list: the worker's turn count and thesubject'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.
handleTurnacquires after auth, before the detach/stream dispatch, so sync, streaming anddetachable turns are all gated.
Tests
subject-quota.test.ts— cap parsing (operator override, derived default, S=1, off) and countersemantics (boundary, release, idempotent release, independence, no map growth).
turn-slot.test.ts— multi-end lifecycle: all ends once on close, adoption defers them, thecreate-if-absent path, the no-slot no-op.
subject-quota-route.test.ts— the issue's acceptance test verbatim: subject A at its cap isrefused 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 ondeploy/k8s(env parity) and passed through bydeploy/compose;/turn's 429 is inharness-openapi.yaml; one sentence each insizing-and-scaling.mdandsecurity-model.md.🤖 Generated with Claude Code