GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
rework per review: split status fix (0074), opt-in admission (0075), base-scheduler delivery abort (0076)
johnwhited9d2fd5e32e2f
diff --git a/README.md b/README.mdindex 412a542..984a9b2 100644--- a/README.md+++ b/README.md@@ -418,6 +418,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_ROCE_WAIT_S` | `20` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it || `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size || `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |+| `MAX_QUEUED` (`TF_GLM_MAX_QUEUED`) | unset | past the lanes plus N, a foreground request is refused with 429 + `Retry-After: 5` instead of queueing (patch 0075); unset queues as always, `0` refuses anything past the lanes — the load-shed a single-instance deployment with no load balancer needs; the refusal costs ~1.6 ms and clients that honor `Retry-After` re-enter cleanly. Background streams never count against it (they yield and queue by design) || `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start || `TF_GLM_MULTI_WATCHDOG_S` / `TF_GLM_MULTI_WATCHDOG_EXIT` | `300` / `0` | a rank stuck this many seconds in one step prints every thread's stack to its log (`/health`'s `iteration_s` shows how long the current step has run); `EXIT=1`: the server then exits (code 1) instead of waiting, so a supervisor can restart it. Both ranks also check that they received the same message each step, and stop with an error naming it if not || `TF_GLM_CLEAR_THINKING` | `0` | `1`: drop earlier turns' reasoning from the prompt, as the checkpoint's template does (agents then prefill the previous turn's tool loop again); a request's `chat_template_kwargs.clear_thinking` wins |diff --git a/docs/tfcap-upstream.md b/docs/tfcap-upstream.mddeleted file mode 100644index bbd1d95..0000000--- a/docs/tfcap-upstream.md+++ /dev/null@@ -1,165 +0,0 @@-# 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/0074-tfcap-capacity-status.patchsimilarity index 50%rename from patches/0099-tfcap-reject-at-admission.patchrename to patches/0074-tfcap-capacity-status.patchindex f6b5998..d0d65a7 100644--- a/patches/0099-tfcap-reject-at-admission.patch+++ b/patches/0074-tfcap-capacity-status.patch@@ -1,6 +1,57 @@+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py+index faec521..59d55e3 100644+--- tensorfold/cuda/http.py++++ tensorfold/cuda/http.py+@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any+ 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 make_handler(app: App):+ 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-0074++ 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 @@ def make_handler(app: App):+ 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) # TFCAP-0074++ 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 @@ def make_handler(app: App):+ 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) # TFCAP-0074++ return self._json(code, {"error": error_body(exc, field)}, headers=_hd)+ except Exception as exc:+ _log_error(exc)+ try:+diff --git tensorfold/server/errors.py tensorfold/server/errors.py+index b4a47dd..4b0a5df 100644--- tensorfold/server/errors.py+++ tensorfold/server/errors.py-@@ -3,7 +3,7 @@+@@ -3,7 +3,7 @@ class RequestError(ValueError):class CapacityError(RequestError):@@ -9,78 +60,26 @@class RoundError(RuntimeError):-@@ -23,6 +23,10 @@+@@ -23,6 +23,14 @@ class ContextLengthError(RequestError):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.++ # TFCAP-0074: how every API layer renders a capacity refusal: a real 429 with a retry hint++ # (not a bare 503), so the same client backs off instead of stacking invisibly. Deliberate++ # deviation from vLLM, whose refusals are 503 for a load balancer to route to another++ # instance: a single-instance LAN deployment has no other instance to route to.+ 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,+diff --git tensorfold/server/http.py tensorfold/server/http.py+index 98ac60d..c8ab8d6 100644--- tensorfold/server/http.py+++ tensorfold/server/http.py-@@ -14,7 +14,7 @@+@@ -14,7 +14,7 @@ from tensorfold.engine import grammarfrom tensorfold.server import responsesfrom tensorfold.server.tools import (active_tool_specs, parse_tool_calls_from_content, stream_tool_call_deltas,tool_choice_requires_call)@@ -89,7 +88,7 @@from tensorfold.server.request_options import parse_numbers, thinking_fieldsfrom tensorfold.server.probabilities import probability_optionsfrom tensorfold.server.messages import normalize_messages, validate_modalities-@@ -87,9 +87,12 @@+@@ -87,9 +87,12 @@ def make_handler(app: Any) -> type[BaseHTTPRequestHandler]:def log_message(self, format: str, *args: Any) -> None:print(f"[tensorfold] {self.address_string()} {format % args}")@@ -98,100 +97,28 @@+ 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++ for _k, _v in (headers or {}).items(): # TFCAP-0074+ 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 @@+@@ -237,8 +240,8 @@ def make_handler(app: Any) -> type[BaseHTTPRequestHandler]: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)++ status, _hd = admission_response(exc) # TFCAP-0074+ self._send_json({"error": error_body(exc)}, status=status, headers=_hd)returnexcept Exception as exc:self._send_json({"error": {"message": str(exc)}}, status=400)-@@ -486,6 +489,8 @@+@@ -486,6 +489,8 @@ def make_handler(app: Any) -> type[BaseHTTPRequestHandler]:)except (BrokenPipeError, ConnectionResetError, RequestCancelled):pass-+ except CapacityError as exc: # TFCAP-REJECT-v1 (order: before RequestError)++ except CapacityError as exc: # TFCAP-0074 (order: before RequestError — a CapacityError is one)+ 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/0075-tfcap-admission-cap.patch b/patches/0075-tfcap-admission-cap.patchnew file mode 100644index 0000000..d8c6303--- /dev/null+++ b/patches/0075-tfcap-admission-cap.patch@@ -0,0 +1,95 @@+diff --git tensorfold/cuda/scheduler.py tensorfold/cuda/scheduler.py+index 4e9421b..767a86c 100644+--- tensorfold/cuda/scheduler.py++++ tensorfold/cuda/scheduler.py+@@ -10,6 +10,7 @@ from typing import Any, Callable++ from .memory_gate import NoRoom+ from .streams import Stream++from tensorfold.server.errors import CapacityError # TFCAP-0075+++ class Waiting(queue.PriorityQueue):+@@ -25,6 +26,12 @@ class Waiting(queue.PriorityQueue):+ def get(self, block: bool = True, timeout: float | None = None):+ return super().get(block, timeout)[2]+++ def foreground_count(self) -> int:++ # TFCAP-0075: queued background streams never consume admission slots; scheduling prefers++ # foreground, so only foreground waiters 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,9 +40,16 @@ class Waiting(queue.PriorityQueue):+++ 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-0075: the mechanism is unconditional; the limit is configuration, as in vLLM — its++ # check_admission runs on every request while max_num_queued_reqs/max_num_queued_tokens++ # default to None ("bounds vLLM's otherwise unbounded request queue", "a coarse capacity++ # valve"). None queues, as every scheduler always has; a cap turns saturation into a++ # refusal with a retry hint instead of 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] = {}+@@ -43,10 +57,18 @@ class Scheduler:+ self.thread = threading.Thread(target=self._loop, daemon=True)+ self.thread.start()+++ def _check_admission(self, background: bool) -> None:++ # TFCAP-0075: refusal at saturation. Background requests bypass: they yield and queue by design.++ 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,+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 24d3e6f..e3261c7 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -46,6 +46,7 @@ import numpy as np+ import torch++ from tensorfold.cuda.scheduler import Scheduler++from tensorfold.server.errors import CapacityError # TFCAP-0075+ from tensorfold.cuda.streams import Stream, next_fill++ from . import multi_prefill, sliced_fill+@@ -1765,11 +1766,19 @@ class GlmScheduler(Scheduler):+ # 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)++ # TFCAP-0075: the cap is operator configuration (TF_GLM_MAX_QUEUED, exported by scripts/config.sh):++ # unset queues as every scheduler always has; N refuses past the lanes plus N. vLLM's default is++ # likewise no limit — its own words, the cap "bounds vLLM's otherwise unbounded request queue".++ # A single-instance LAN deployment has no load balancer to shed load ahead of the server, so an++ # exposed one should set a small cap (ours: 0 — nothing waits past the lanes).++ queued = os.environ.get("TF_GLM_MAX_QUEUED")++ super().__init__(decoder, max_streams=max_streams,++ max_in_system=max_streams + int(queued) if queued else None)++ 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)diff --git a/patches/0100-tfcap-stall-release.patch b/patches/0076-tfcap-delivery-abort.patchsimilarity index 58%rename from patches/0100-tfcap-stall-release.patchrename to patches/0076-tfcap-delivery-abort.patchindex cf43b58..05bfcc7 100644--- a/patches/0100-tfcap-stall-release.patch+++ b/patches/0076-tfcap-delivery-abort.patch@@ -1,14 +1,17 @@+diff --git tensorfold/cuda/scheduler.py tensorfold/cuda/scheduler.py+index 767a86c..a15ab62 100644--- tensorfold/cuda/scheduler.py+++ tensorfold/cuda/scheduler.py-@@ -61,6 +61,20 @@- return+@@ -64,6 +64,22 @@ class Scheduler: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.++ # TFCAP-0076: 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 — minutes of decode into a queue nobody reads. Fires at most once per++ # stream: cancel latches and later tokens skip the emit. The GLM submit loop's equivalent,++ # with cleanup-before-error for its rank coordination, is patch 0073 (PR #51).+ stop = False+ if not cancel[0]:+ try:@@ -18,10 +21,11 @@+ 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 @@+@@ -79,8 +95,7 @@ class Scheduler:while True:kind, value = box.get()if kind == "tokens":@@ -31,15 +35,3 @@elif kind == "error":raise valueelse:---- 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:diff --git a/scripts/config.sh b/scripts/config.shindex 98f977e..4f4d904 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -192,6 +192,12 @@ export TF_GLM_CACHE_ENTRIES="${TF_GLM_CACHE_ENTRIES:-32}"# Earlier turns keep their reasoning in the prompt (patch 0060), as in zai-org's current template. 1: drop it, as the# checkpoint's template does; agents then prefill the previous turn's tool loop again at each new user message.export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"+# Admission at saturation (patch 0075): past the lanes plus MAX_QUEUED a foreground request is refused with+# 429 + Retry-After (529 overloaded_error through the Anthropic bridge) instead of queueing invisibly. Unset+# queues as every scheduler always has; 0 refuses anything past the lanes. A single-instance deployment with+# no load balancer in front of it should set a small value (ours: 0, in scripts/local.sh).+MAX_QUEUED="${MAX_QUEUED:-}"+export TF_GLM_MAX_QUEUED="$MAX_QUEUED"# Waiting prompts filled together in one forward (patch 0049): shared work (expert weights, glue, projections) runs once# for every waiting prompt, attention per prompt on its own state, so each gets the bits it gets alone. sparkDash, prose at# 4 at once: 103.4 -> 108.8 tok/s, time to first token 590 -> 340 ms; structured at 3 / 4 at once: 175.2 -> 196.3 and