Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python

tfcap: admission control at saturation + delivery-failure abort

john2eaf32413add
diff --git a/docs/tfcap-upstream.md b/docs/tfcap-upstream.md
new file mode 100644
index 0000000..bbd1d95
--- /dev/null
+++ b/docs/tfcap-upstream.md
@@ -0,0 +1,165 @@
+# tfcap: admission control and delivery-abort patches
+
+Two patches for the TensorFold serving stack. `0099` adds admission control to
+`Scheduler`; `0100` makes the scheduler relay abort a stream when its delivery
+callback fails. Both are measured against vLLM v1 behavior and are verified live
+on a 3-rank TP3 deployment.
+
+## Problem
+
+**No admission control.** `Scheduler.submit` enqueues unconditionally. Under
+saturation the waiting queue grows without signal: clients hold open connections
+until their own timeouts, then retry and stack. Measured on this deployment:
+`requests_waiting=3` with a 5th request served `HTTP 200` while four lanes ran
+dead requests, followed by 13 client retries of ~360 s each.
+
+**Delivery failures leak lanes.** The relay loop calls `emit(value)` — the
+request's own delivery callback — as
+
+```python
+if not cancel[0] and emit(value):
+ cancel[0] = True
+```
+
+An exception from `emit` (broken pipe, reset, timeout) escapes the relay thread,
+escapes `submit`, and the stream remains admitted until generation ends —
+minutes of decode into a queue nobody reads.
+
+**Capacity refusals render inconsistently.** `CapacityError` is rendered as a
+bare `503` with no `Retry-After` at two sites and as `400` at a third
+(`CapacityError` is a `RequestError` subclass caught by a later branch).
+
+## Reference behavior (vLLM v1)
+
+- `AsyncLLM.check_admission`: every request passes an admission check; the limit
+ is configuration (`max_num_queued_reqs`, `max_num_queued_tokens` default
+ unlimited); refusals return a retryable status with a retry hint "so that load
+ balancers and client SDKs retry".
+- `AsyncLLM.generate`: `except (asyncio.CancelledError, GeneratorExit):
+ await self.abort(request_id, internal=True)` reaches "OutputProcessor and
+ EngineCore" — a request is aborted on every error path.
+- `RequestOutputCollector.put` is non-blocking and merges outputs when the
+ producer outruns the consumer: a connected-but-slow reader never blocks the
+ engine and never frees its lane. No timeout is involved.
+
+## Change
+
+### `server/errors.py`
+
+- `CapacityError` docstring: states the rendered status (429 + Retry-After).
+- New `admission_response(exc) -> tuple[int, dict[str, str] | None]` — the
+ status/headers pair for a capacity refusal, defined once:
+
+ ```python
+ return (429, {"Retry-After": "5"}) if isinstance(exc, CapacityError) else (400, None)
+ ```
+
+ Deviation from vLLM: 429 rather than 503. The deployment is a single instance
+ on a LAN; 429 pressures the same client to back off. Both integrated clients
+ were verified against it (opencode retries 429/≥500 honoring `Retry-After`;
+ the Anthropic bridge maps 429 → 529 `overloaded_error` + `Retry-After`).
+
+### `cuda/scheduler.py`
+
+- `Waiting.foreground_count() -> int` — queued background streams under
+ `self.mutex`; they are scheduled last and never take a lane from a foreground
+ request, so only foreground waiters count against the cap. The existing
+ `foreground()` (`-> bool`) is unchanged; its callers are unchanged.
+- `Scheduler.__init__(..., max_in_system: int | None = None)` — the in-system
+ cap (lanes + foreground-queued). `None`, the default, is the pre-patch
+ behavior: every scheduler queues, as before. The mechanism is unconditional;
+ the limit is configuration, matching vLLM where `check_admission` always runs
+ and the caps default to unlimited.
+- `Scheduler._check_admission(background)`:
+
+ ```python
+ if background or self.max_in_system is None:
+ return
+ if self.decoder.live() + self.waiting.foreground_count() >= self.max_in_system:
+ raise CapacityError("all serving lanes are busy; retry shortly")
+ ```
+
+- `Scheduler._relay_token(emit, value, cancel)` — the delivery policy:
+
+ ```python
+ stop = False
+ if not cancel[0]:
+ try:
+ stop = emit(value)
+ except Exception as exc:
+ print(f"[tensorfold] stream aborted: emit failed: {exc!r}", flush=True)
+ stop = True
+ if stop:
+ cancel[0] = True
+ ```
+
+ Broad `except Exception` is deliberate: `emit` is a delivery callback; any
+ exception means the token was not delivered. The abort fires at most once per
+ stream (`cancel` latches; later tokens skip `emit`), so the log line cannot
+ flood. `scheduler.py` previously printed nothing — this is its first line,
+ and an aborted delivery is otherwise unobservable.
+- `submit` calls `self._check_admission(background)`; the relay calls
+ `self._relay_token(emit, value, cancel)`.
+
+### `families/glm5_next/cuda/multi.py`
+
+- `GlmScheduler.__init__` passes `max_in_system=max_streams` — the GLM
+ multi-lane policy: no stacking beyond the lanes. This constructor argument is
+ the entire family-scoped surface; the policy logic is inherited.
+- `GlmScheduler.submit` calls `self._check_admission(background)`; the GLM
+ relay calls `self._relay_token(emit, value, cancel)` (the class re-implements
+ both, so each is a one-line call into the shared definitions).
+
+### `server/http.py` and `cuda/http.py`
+
+- `_send_json` / `_json` gain an optional `headers` kwarg (additive; existing
+ call sites unchanged).
+- The three `isinstance(exc, CapacityError)` render sites route through
+ `admission_response(exc)`; `server/http.py`'s generate path adds
+ `except CapacityError` before `except RequestError` (a `CapacityError` is a
+ `RequestError` subclass; without the earlier branch it renders as 400).
+
+## What is intentionally absent
+
+- No timeout: a connected-but-stalled reader holds its lane exactly as in vLLM
+ (coalescing on their side; the request thread blocks here while the scheduler
+ keeps decoding). `timeout=0` in the patched tree.
+- No submit lock: a burst arriving entirely inside the lane-fill window can
+ admit one request past the cap (observed once; served normally, queue
+ drained). vLLM does not race here because asyncio serializes
+ `check_admission`. A lock is not worth the contention for a bounded,
+ self-draining effect.
+- No consolidation of the two HTTP layers — `server/http.py` and
+ `cuda/http.py` duplicate their render paths. The policy lives in
+ `errors.py` so the layers cannot drift; consolidation is a separate refactor.
+
+## Measured results (3-rank TP3, `--parallel 8`, final build)
+
+| Probe | Result |
+|---|---|
+| 9th request, 8 lanes busy — direct OpenAI wire | HTTP 429 in 1.6 ms, `Retry-After: 5` |
+| 9th request — Anthropic bridge (non-streaming) | HTTP 529, `retry-after: 5`, `type: overloaded_error` |
+| 12-request burst at idle | 8 lanes + 3×429 + 1 admitted inside the lane-fill window; queue drained to 0 |
+| Post-burst drain | `requests_running 0, requests_waiting 0` |
+| Dead client mid-decode | lane freed within one 15 s window (guard fires at the next token write) |
+| Stalled reader | lane held to completion, as vLLM; `timeout=0` in the patched tree |
+
+## Complexity and duplication impact
+
+| Function | CC before | CC after |
+|---|---|---|
+| `Scheduler.submit` | 6 | 4 |
+| `GlmScheduler.submit` | 7 | 5 |
+| `do_POST` (cuda layer) | 42 | 40 |
+| `make_handler` (server layer) | 93 | 95 |
+| new `_check_admission` / `_relay_token` / `admission_response` | — | 4 / 4 / 2 |
+
+Hardcoded capacity statuses: 3 sites → 0. `429` literals: 3, all in
+`errors.py`. One definition per policy; call sites are single lines.
+
+## Test
+
+Static: both patches dry-apply on a pristine tree; `TFCAP-REJECT-v1` markers in
+5 files, `TFCAP-0100` in 1; import graph passes.
+
+Rollback: remove the two patch files, rebuild.
diff --git a/patches/0099-tfcap-reject-at-admission.patch b/patches/0099-tfcap-reject-at-admission.patch
new file mode 100644
index 0000000..f6b5998
--- /dev/null
+++ b/patches/0099-tfcap-reject-at-admission.patch
@@ -0,0 +1,197 @@
+--- tensorfold/server/errors.py
++++ tensorfold/server/errors.py
+@@ -3,7 +3,7 @@
+
+
+ class CapacityError(RequestError):
+- """A transient capacity refusal: HTTP 503, retry shortly."""
++ """A transient capacity refusal: HTTP 429 + Retry-After (see admission_response)."""
+
+
+ class RoundError(RuntimeError):
+@@ -23,6 +23,10 @@
+ CONTEXT_LIMIT = "This server's maximum context length is" # OpenAI's wording, which clients match to compact
+
+
++def admission_response(exc: Exception) -> tuple[int, dict[str, str] | None]:
++ # TFCAP-REJECT-v1: how every API layer renders a capacity refusal. A real 429 with a
++ # retry hint (not a bare 503) so clients back off instead of stacking invisibly.
++ return (429, {"Retry-After": "5"}) if isinstance(exc, CapacityError) else (400, None)
+ def refusal(problem: str) -> RequestError:
+ """A refusal string as its error: a context-window one carries OpenAI's code."""
+
+--- tensorfold/cuda/scheduler.py
++++ tensorfold/cuda/scheduler.py
+@@ -10,6 +10,7 @@
+
+ from .memory_gate import NoRoom
+ from .streams import Stream
++from tensorfold.server.errors import CapacityError # TFCAP-REJECT-v1
+
+
+ class Waiting(queue.PriorityQueue):
+@@ -24,6 +25,11 @@
+
+ def get(self, block: bool = True, timeout: float | None = None):
+ return super().get(block, timeout)[2]
++ def foreground_count(self) -> int:
++ # TFCAP-REJECT-v1: queued background streams never consume admission slots;
++ # scheduling prefers foreground, so only they count against the cap.
++ with self.mutex:
++ return sum(1 for _p, _o, (s, _b) in self.queue if not s.background)
+
+ def foreground(self) -> bool:
+ """Whether a foreground request waits."""
+@@ -33,20 +39,33 @@
+
+
+ class Scheduler:
+- def __init__(self, decoder: Any, *, max_streams: int = 4) -> None:
++ def __init__(self, decoder: Any, *, max_streams: int = 4,
++ max_in_system: int | None = None) -> None:
+ self.decoder = decoder
+ self.max_streams = max_streams
++ # TFCAP-REJECT-v1: the mechanism is unconditional; the limit is configuration, as
++ # in vLLM (max_num_queued_reqs defaults to unlimited). None = queue, as every
++ # scheduler always has; a cap turns saturation into a refusal, not invisible stacking.
++ self.max_in_system = max_in_system
+ self.waiting = Waiting()
+ self.held: tuple | None = None # a request waiting for memory, admitted before any other
+ self.boxes: dict[int, queue.Queue] = {}
+ self.yields = 0 # background streams that gave up their lane
+ self.thread = threading.Thread(target=self._loop, daemon=True)
+ self.thread.start()
+-
++ def _check_admission(self, background: bool) -> None:
++ # TFCAP-REJECT-v1: refusal at saturation, mirroring vLLM's check_admission
++ # (queued + running against the cap). A refusal is a real error the API layer
++ # renders with a retry hint, so clients back off instead of stacking invisibly.
++ if background or self.max_in_system is None:
++ return
++ if self.decoder.live() + self.waiting.foreground_count() >= self.max_in_system:
++ raise CapacityError("all serving lanes are busy; retry shortly")
+ def submit(self, prompt: list[int], count: int, sampling: Any, draft: bool,
+ emit: Callable[[list[int]], bool | None], stop_eos: bool = True, *, vision: Any = None,
+ constraint: Any = None, background: bool = False, probabilities: Any = None) -> dict:
+ """Decode one request; ``emit`` runs on the calling thread and returns True to stop. Returns its stats."""
++ self._check_admission(background)
+
+ box: queue.Queue = queue.Queue()
+ stream = Stream(list(prompt), max(1, count), sampling, draft=draft, stop_eos=stop_eos, vision=vision,
+--- tensorfold/server/http.py
++++ tensorfold/server/http.py
+@@ -14,7 +14,7 @@
+ from tensorfold.server import responses
+ from tensorfold.server.tools import (active_tool_specs, parse_tool_calls_from_content, stream_tool_call_deltas,
+ tool_choice_requires_call)
+-from tensorfold.server.errors import CapacityError, RequestError, error_body
++from tensorfold.server.errors import CapacityError, RequestError, admission_response, error_body
+ from tensorfold.server.request_options import parse_numbers, thinking_fields
+ from tensorfold.server.probabilities import probability_options
+ from tensorfold.server.messages import normalize_messages, validate_modalities
+@@ -87,9 +87,12 @@
+ def log_message(self, format: str, *args: Any) -> None:
+ print(f"[tensorfold] {self.address_string()} {format % args}")
+
+- def _send_json(self, payload: dict[str, Any], status: int = 200) -> None:
++ def _send_json(self, payload: dict[str, Any], status: int = 200,
++ headers: dict[str, str] | None = None) -> None:
+ body = json.dumps(payload).encode("utf-8")
+ self.send_response(status)
++ for _k, _v in (headers or {}).items(): # TFCAP-REJECT-v1
++ self.send_header(_k, _v)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ if self.close_connection: # so a pooling client does not reuse the socket
+@@ -237,8 +240,8 @@
+ stream = bool(body.get("stream", False))
+ tool_policy = ToolCallPolicy(body)
+ except RequestError as exc:
+- self._send_json({"error": error_body(exc)},
+- status=503 if isinstance(exc, CapacityError) else 400)
++ status, _hd = admission_response(exc)
++ self._send_json({"error": error_body(exc)}, status=status, headers=_hd)
+ return
+ except Exception as exc:
+ self._send_json({"error": {"message": str(exc)}}, status=400)
+@@ -486,6 +489,8 @@
+ )
+ except (BrokenPipeError, ConnectionResetError, RequestCancelled):
+ pass
++ except CapacityError as exc: # TFCAP-REJECT-v1 (order: before RequestError)
++ self._send_json({"error": error_body(exc)}, *admission_response(exc))
+ except RequestError as exc:
+ self._send_json({"error": error_body(exc)}, status=400)
+ except Exception as exc: # surface runner errors to the client
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -46,6 +46,7 @@
+ import torch
+
+ from tensorfold.cuda.scheduler import Scheduler
++from tensorfold.server.errors import CapacityError # TFCAP-REJECT-v1
+ from tensorfold.cuda.streams import Stream, next_fill
+
+ from . import multi_prefill, sliced_fill
+@@ -1765,11 +1766,13 @@
+ # TF_GLM_MULTI_PREFILL_WAIT_MS: an idle server's wait for requests arriving with the first (their prompts then
+ # share its first chunk); only with TF_GLM_MULTI_PREFILL=1
+ self.gather_s = multi_prefill.wait_ms() / 1000.0 if getattr(decoder, "group", False) else 0.0
+- super().__init__(decoder, max_streams=max_streams)
++ super().__init__(decoder, max_streams=max_streams,
++ max_in_system=max_streams) # TFCAP-REJECT-v1: no stacking beyond the lanes
+
+ def submit(self, prompt: list[int], count: int, sampling: Any, draft: bool,
+ emit: Callable[[list[int]], bool | None], stop_eos: bool = True, *, vision: Any = None,
+ constraint: Any = None, background: bool = False, glm: dict | None = None) -> dict:
++ self._check_admission(background)
+ box: queue.Queue = queue.Queue()
+ stream = Stream(list(prompt), max(1, count), sampling, draft=draft, stop_eos=stop_eos, vision=vision,
+ constraint=constraint, background=background)
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -10,7 +10,7 @@
+ from tensorfold.cuda import health
+ from tensorfold.server import metrics, responses
+ from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
+-from tensorfold.server.errors import CapacityError, RequestError, error_body
++from tensorfold.server.errors import CapacityError, RequestError, admission_response, error_body
+ from tensorfold.server.http import Server
+ from tensorfold.server.stacks import Rearming
+
+@@ -46,10 +46,12 @@
+ def log_message(self, fmt, *args): # quiet
+ pass
+
+- def _json(self, code: int, payload: dict[str, Any]) -> None:
++ def _json(self, code: int, payload: dict[str, Any], headers: dict[str, str] | None = None) -> None:
+ data = json.dumps(payload).encode()
+ try:
+ self.send_response(code)
++ for _k, _v in (headers or {}).items(): # TFCAP-REJECT-v1
++ self.send_header(_k, _v)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ if self.close_connection: # so a pooling client does not reuse the socket
+@@ -129,8 +131,8 @@
+ try:
+ prepared = app.prepare(body, chat)
+ except RequestError as exc:
+- return self._json(503 if isinstance(exc, CapacityError) else 400,
+- {"error": error_body(exc, field)})
++ code, _hd = admission_response(exc)
++ return self._json(code, {"error": error_body(exc, field)}, headers=_hd)
+ except Exception as exc: # any other failure to read the request is refused too, as on MLX
+ _log_error(exc)
+ return self._json(400, {"error": {"message": _error_message(exc)}})
+@@ -203,8 +205,8 @@
+ self.close_connection = True
+ return
+ except RequestError as exc:
+- return self._json(503 if isinstance(exc, CapacityError) else 400,
+- {"error": error_body(exc, field)})
++ code, _hd = admission_response(exc)
++ return self._json(code, {"error": error_body(exc, field)}, headers=_hd)
+ except Exception as exc:
+ _log_error(exc)
+ try:
diff --git a/patches/0100-tfcap-stall-release.patch b/patches/0100-tfcap-stall-release.patch
new file mode 100644
index 0000000..cf43b58
--- /dev/null
+++ b/patches/0100-tfcap-stall-release.patch
@@ -0,0 +1,45 @@
+--- tensorfold/cuda/scheduler.py
++++ tensorfold/cuda/scheduler.py
+@@ -61,6 +61,20 @@
+ return
+ if self.decoder.live() + self.waiting.foreground_count() >= self.max_in_system:
+ raise CapacityError("all serving lanes are busy; retry shortly")
++ def _relay_token(self, emit: Callable[[list[int]], bool | None], value: list[int], cancel: list[bool]) -> None:
++ # TFCAP-0100: a True return (the client left, or a stop string) or a delivery
++ # failure ends the stream. The old code let an exception escape the relay and the
++ # lane leaked until generation ended; vLLM aborts on every error path likewise.
++ # Fires at most once per stream: cancel latches and later tokens skip the emit.
++ stop = False
++ if not cancel[0]:
++ try:
++ stop = emit(value)
++ except Exception as exc:
++ print(f"[tensorfold] stream aborted: emit failed: {exc!r}", flush=True)
++ stop = True
++ if stop:
++ cancel[0] = True
+ def submit(self, prompt: list[int], count: int, sampling: Any, draft: bool,
+ emit: Callable[[list[int]], bool | None], stop_eos: bool = True, *, vision: Any = None,
+ constraint: Any = None, background: bool = False, probabilities: Any = None) -> dict:
+@@ -76,8 +90,7 @@
+ while True:
+ kind, value = box.get()
+ if kind == "tokens":
+- if not cancel[0] and emit(value):
+- cancel[0] = True # the client left: the stream ends after its next round
++ self._relay_token(emit, value, cancel)
+ elif kind == "error":
+ raise value
+ else:
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -1784,8 +1784,7 @@
+ while True:
+ kind, value = box.get()
+ if kind == "tokens":
+- if not cancel[0] and emit(value):
+- cancel[0] = True # the client left or a stop string: the stream ends next round
++ self._relay_token(emit, value, cancel)
+ elif kind == "error":
+ raise value
+ else: