Skip to content

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

Python

Patch 0118: a broken GLM engine shows in /health and /metrics, with an opt-in process exit (TF_GLM_EXIT_ON_BROKEN)

bblicke11a24d84e15a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cfa900b..38488f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -220,6 +220,7 @@ Every change to this recipe, newest first. Each release names the image it serve
Both now read the body through `0059`'s `_discard_body` (`read_body`: Content-Length or chunked; a refusal closes the
connection) before answering; a request without one reads nothing. CPU test: `tools/test_get_bodies.py` (fails on
the unpatched source).
+- **Broken concurrent GLM engine is visible** (patch `0118-glm-broken-health-exit`): `/health` reports `ok: false` and its first error in `broken`; `/metrics` exposes `tensorfold_health:ok`. Opt-in `TF_GLM_EXIT_ON_BROKEN=1` logs the cause and exits with code 1 as soon as the broken state latches. The existing stall watchdog is unchanged. The cause shown in `/health` is cut at 200 characters. CPU check: `tools/test_broken_health_exit.py`.
## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second rail
diff --git a/README.md b/README.md
index 6528af2..295d3d2 100644
--- a/README.md
+++ b/README.md
@@ -558,6 +558,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_KEPT_BYTES_GIB` | `0` (no cap) | a byte budget for the kept states together (patch `0089`, by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65): the device memory they own outside the pool (recurrent state, DFlash2 window copies: hundreds of MB each with long contexts); past it states are dropped in the entry cap's order (not written to the spill tier) and freed blocks go back to the driver. The author runs `4`; `kept_bytes` / `kept_bytes_cap` in `/health` |
| `TF_GLM_KEEP_PER_CHAT` | `0` (no limit) | at most this many of one conversation's own turn-boundary kept states (patch `0089`, PR #65); shared-prefix and mid-prefill states do not count, the older turns are dropped without a spill. The author runs `2`; `kept_mix` in `/health` shows each conversation's count |
| `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_EXIT_ON_BROKEN` | `0` | `1`: when the concurrent GLM decoder latches an error that leaves the ranks out of step, log its first cause and exit the process with code 1 immediately, so a supervisor can restart both ranks. Independent of the stall watchdog. With `0`, requests still fail, but `/health` reports `ok: false` and `broken` (exception type and reason); `/metrics` exposes `tensorfold_health:ok` as 0. A GPU fault may still require host recovery; use supervisor restart backoff. |
| `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 |
| `TF_GLM_EFFORT_TAIL` | `0` | `1` (patch `0096`, issue #93, reported by [jdecker76](https://github.com/jdecker76)): render the reasoning-effort line just before `<\|assistant\|><think>` instead of at token 3, so switching effort or thinking on/off keeps the conversation's kept prompt (the reporter measured 0% cached becoming 98%); the model was trained with the line first, so check that Low and High still change the answers before you rely on it (`tools/toolcheck.py`, `tools/end_of_turn.py`). The previous turn's last tokens prefill again |
| `TF_GLM_LITERAL_TOKENS` | `1` | added-token text a request quotes stays text (patch `0116`); `0`: every match of an added token's text in the rendered prompt is that token, as before |
@@ -708,6 +709,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Kept-state count | `0097-glm-kept-entries-share` | `TF_GLM_CACHE_SHARE_PCT` (the kept-state count as a share of the pool's memory; a ceiling at three quarters of it, so the reservation stays inside the estimate) and the kept states' key arrays built once, not at every admission (issue #84, @jdecker76) |
| Kept-state limits | `0089-glm-kept-state` | `TF_GLM_KEPT_BYTES_GIB` (a byte budget for the kept states, with the freed blocks handed back to the driver) and `TF_GLM_KEEP_PER_CHAT` (a per-conversation quota of turn-boundary states), both off by default; `/health` `kept_bytes`, `kept_mix` (authored by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), #65) | with both at 0, nothing changes |
| Responses `include` | `0093-responses-include` | `/v1/responses` accepts OpenAI's `include` values and ignores them (reasoning already comes as text, nothing is encrypted); an unknown value or a non-list is still a 400 (issue #73) | the AI SDK's `include: ["reasoning.encrypted_content"]` no longer fails every request |
+| Broken engine | `0118-glm-broken-health-exit` | `/health` reports `ok: false` with its first broken cause, `/metrics` exposes `tensorfold_health:ok`, and opt-in `TF_GLM_EXIT_ON_BROKEN=1` exits non-zero on the latch | broken state is visible; default process lifetime unchanged |
| Chunked request bodies | `0094-chunked-request-bodies` | a `Transfer-Encoding: chunked` request body (AI SDK clients, Chatbox, proxies) is read like a `Content-Length` one on the chat, completions, tokenizer and Responses routes and the MLX-style server, each route keeping its own size limit (96 MiB for chat); a refused request's body is consumed so it cannot reach the next one. The reader is `request_body.read_body` from TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus), which `0084` adds; this patch uses it at the remaining sites (issues #67, #74) | no dechunking proxy; a validation 400 no longer leaves HTML after the JSON on a keep-alive connection |
| GET and DELETE bodies | `0113-http-get-delete-body-discard` | `do_GET` and `do_DELETE` read a request's body (Content-Length or chunked, through `0059`'s `_discard_body`) before answering; they read none, so a GET with a body (scanners send them) left its bytes on the keep-alive connection, parsed as the next request on it: a stdlib "Bad request syntax" 400 for whatever came next, behind a pooling proxy often another client's (by [cawilliamson](https://github.com/cawilliamson)) | the next request on the connection is answered as sent |
| Streamed admission | `0095-stream-admission` | with `TF_GLM_MAX_QUEUED` set, a streamed request to a full server is answered 429 + `Retry-After: 5` before the stream opens; `0082` checked inside `submit`, after the 200 and the headers had gone out, so a streaming client (opencode, Claude Code) got a 200 with the error as an event and never saw a retryable status (issue #50) | the same refusal for streamed and plain requests |
@@ -768,6 +770,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| `tools/qmm_noclusters_check.py [--time]` | patch 0103's checks: the installed 4-bit matmul against a build of the same sources with the old cluster rule, bit for bit at every decode shape of TP=4, TP=3 and TP=2 and at the 28 Mi edge, the path each call takes (and with `TF_GLM_QMM_CLUSTERS=1`), and a CUDA graph on side streams; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times |
| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) |
| `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops |
+| `tools/test_broken_health_exit.py --source-root DIR` | CPU-only broken-state checks against patched TensorFold: settings, first cause, request refusal, round/load/drop errors, health and metrics, subprocess exit (no Torch/GPU) |
| `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait |
| `tools/test_sse_keepalive.py --source-root DIR` | patch 0111's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): every streaming route of the real handler, over a stub that stays silent for 3 s, gets `: keepalive` about once a second with `TENSORFOLD_SSE_KEEPALIVE_S=1` and none after its last event; without its comment lines each stream is byte-identical to the stream with `0`; non-streamed replies unchanged; no thread outlives its request; `--expect-stock` before 0111 shows the silence |
| `tools/end_of_turn.py [label] [max_cut]` | 8 short French coding prompts, thinking off: counts the replies that run to `max_tokens` (48 requests) and measures P(end of turn) right after each reply's closing code fence; exit 1 above `max_cut` cut replies (default 4) |
diff --git a/patches/0118-glm-broken-health-exit.patch b/patches/0118-glm-broken-health-exit.patch
new file mode 100644
index 0000000..db6f535
--- /dev/null
+++ b/patches/0118-glm-broken-health-exit.patch
@@ -0,0 +1,116 @@
+# Patch 0118: broken GLM health and opt-in process exit (TensorFold v0.6.0 + recipe patches).
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -74,6 +74,14 @@
+ if s < 0:
+ raise ValueError(f"TF_GLM_MULTI_WATCHDOG_S: seconds (0: off), not {value!r}")
+ return s
++
++
++def exit_on_broken(value: str | None = None) -> bool:
++ """Opt-in process exit when the ranks can no longer be trusted to agree."""
++ raw = (os.environ.get("TF_GLM_EXIT_ON_BROKEN", "") if value is None else value).strip() or "0"
++ if raw not in ("0", "1"):
++ raise ValueError(f"TF_GLM_EXIT_ON_BROKEN: 0 or 1, not {raw!r}")
++ return raw == "1"
+
+
+ def watchdog_exits(value: str | None = None) -> bool:
+@@ -564,6 +572,7 @@
+ self.next_chat = 0
+ self.outbox: list[int] = []
+ self.idle = True
++ self.exit_on_broken = exit_on_broken()
+ self.broken: Exception | None = None
+ self.requeue: list[Stream] = [] # rank 0: streams given back to the scheduler's queue
+ self.eos = tuple(self.w.cfg.eos)
+@@ -611,6 +620,22 @@
+ # how long rank 0's current iteration has run (0 between iterations): a stalled server keeps growing it
+ "iteration_s": round(time.monotonic() - since, 1)
+ if (since := getattr(self, "iteration_since", None)) is not None else 0.0}
++
++ def _break(self, exc: Exception) -> None:
++ # Every error path latches its first cause before any cleanup that might itself fail or hang.
++ if self.broken is None:
++ self.broken = exc
++ if self.exit_on_broken:
++ import sys
++ import traceback
++
++ try:
++ print("[tensorfold] engine broken; TF_GLM_EXIT_ON_BROKEN=1: exiting with code 1",
++ file=sys.stderr, flush=True)
++ traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
++ sys.stderr.flush()
++ finally:
++ os._exit(1) # SystemExit in the scheduler thread would leave the HTTP process alive.
+
+ def _check(self) -> None:
+ if self.broken is not None:
+@@ -892,7 +917,7 @@
+ try:
+ self._admitted(self._parse_admit(payload), s, feed, s.constraint, info.get("spec", ""))
+ except Exception as exc: # rank 1 applies the same ADMIT: the ranks may no longer agree
+- self.broken = exc
++ self._break(exc)
+ raise
+ self.lanes[sid].key = key
+
+@@ -1474,7 +1499,7 @@
+ try:
+ return self._finish_load(h.lid)
+ except Exception as exc: # a failed all-gather: the ranks may no longer agree
+- self.broken = exc
++ self._break(exc)
+ raise
+
+ def _finish_load(self, lid: int) -> bool:
+@@ -1672,7 +1697,7 @@
+ self.disk.stats.behind_s += time.perf_counter() - t0
+ return self._iterate()
+ except Exception as exc:
+- self.broken = exc
++ self._break(exc)
+ raise
+
+ def _fill_turn(self) -> Lane | None:
+@@ -2290,13 +2315,13 @@
+ def drop(self) -> list[Stream]:
+ """After an error in an iteration: forget every stream (the ranks can no longer be trusted to agree)."""
+
++ if self.broken is None:
++ self._break(RuntimeError("an iteration failed"))
+ live = [l.s for l in self.lanes.values()]
+ if self.partial is not None:
+ self.partial.close()
+ self.partial = None
+ self.lanes = {}
+- if self.broken is None:
+- self.broken = RuntimeError("an iteration failed")
+ return live
+
+ def stats(self, s: Stream) -> dict:
+--- tensorfold/cuda/health.py
++++ tensorfold/cuda/health.py
+@@ -91,6 +91,11 @@
+ extra = {}
+ body["streams"].update(extra.pop("streams", {}))
+ body.update(extra)
++ # Read the latch independently of mutable counters: a failed counters read must not hide a broken engine.
++ broken = getattr(decoder, "broken", None)
++ if broken is not None:
++ body["ok"] = False
++ body["broken"] = f"{type(broken).__name__}: {str(broken)[:200]}" # /health is unauthenticated: bounded
+ window = getattr(app, "effective_context_window", None)
+ if window:
+ body["context_length"] = int(window)
+--- tensorfold/server/metrics.py
++++ tensorfold/server/metrics.py
+@@ -186,6 +186,7 @@
+ )
+ _SPILL_GAUGES = {"entries", "pending", "stored_bytes", "disk_free_bytes", "highwater", "writers"}
+ _HEALTH_GAUGES = (
++ ("ok", "Engine health: 1 healthy, 0 broken (see /health for the reason)."),
+ ("context_length", "Tokens a request's prompt and reply may hold (the server's effective window)."),
+ ("streams_max", "Streams the concurrent engine decodes at most (--parallel)."),
+ ("pool_tokens", "Token rows in the concurrent engine's shared cache pool."),
diff --git a/tools/test_broken_health_exit.py b/tools/test_broken_health_exit.py
new file mode 100644
index 0000000..d593eb1
--- /dev/null
+++ b/tools/test_broken_health_exit.py
@@ -0,0 +1,123 @@
+"""CPU-only patch 0118 broken latch, health/metrics and process-exit checks; no torch or GPU.
+
+python3 -B tools/test_broken_health_exit.py --source-root /path/to/patched/src
+Extracts the real decoder's control methods with AST, leaving GPU imports/decorators out.
+"""
+from __future__ import annotations
+
+import argparse
+import ast
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+from types import SimpleNamespace
+
+
+def decoder_type(root):
+ tree = ast.parse((Path(root) / 'tensorfold/families/glm5_next/cuda/multi.py').read_text())
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'MultiDecoder')
+ # Audit the full class too: upstream must not add a latch that bypasses the exit helper.
+ writes = []
+ calls = []
+ for method in cls.body:
+ if not isinstance(method, ast.FunctionDef):
+ continue
+ for node in ast.walk(method):
+ if isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Store) and node.attr == 'broken':
+ writes.append(method.name)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == '_break':
+ calls.append(method.name)
+ assert sorted(writes) == ['__init__', '_break'], writes
+ assert sorted(calls) == ['admit', 'complete_load', 'drop', 'round'], calls
+ names = {'_break', '_check', 'round', 'drop', 'complete_load'}
+ methods = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in names]
+ assert len(methods) == len(names)
+ for n in methods:
+ n.decorator_list = []
+ nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'exit_on_broken']
+ nodes += [ast.ClassDef(name='Decoder', bases=[], keywords=[], body=methods, decorator_list=[])]
+ module = ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[]))
+ ns = {'os': os, 'time': time, '_watch': lambda *a: None, 'LOADED': 1}
+ exec(compile(module, str(root), 'exec'), ns)
+ return ns['Decoder'], ns['exit_on_broken']
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('--source-root', required=True)
+ ap.add_argument('--child', action='store_true')
+ args = ap.parse_args()
+ Decoder, setting = decoder_type(args.source_root)
+ d = Decoder()
+ d.broken = None
+ d.exit_on_broken = args.child
+ if args.child:
+ d._break(RuntimeError('synthetic GPU failure'))
+ raise AssertionError('process did not exit')
+ for value, expected in (('', False), ('0', False), ('1', True), (' 1 ', True)):
+ assert setting(value) is expected
+ try:
+ setting('yes')
+ except ValueError:
+ pass
+ else:
+ raise AssertionError('invalid setting accepted')
+ os.environ.pop('TF_GLM_EXIT_ON_BROKEN', None)
+ os.environ['TF_GLM_MULTI_WATCHDOG_EXIT'] = '1'
+ assert setting() is False, 'stall exit must not enable broken exit'
+ cause = RuntimeError('synthetic GPU failure')
+ d._break(cause)
+ d._break(ValueError('secondary failure'))
+ assert d.broken is cause
+ try:
+ d._check()
+ except RuntimeError as exc:
+ assert exc.__cause__ is cause and 'out of step' in str(exc)
+ else:
+ raise AssertionError('broken decoder accepted work')
+ def fail(*a):
+ raise cause
+ for path in ('round', 'complete_load', 'drop'):
+ d.broken = None
+ d.watchdog = 0
+ d.disk = None
+ d._iterate = fail
+ d._finish_load = fail
+ d._emit = lambda *a: None
+ d._flush = lambda: None
+ d.lanes = {}
+ d.partial = None
+ try:
+ getattr(d, path)(SimpleNamespace(lid=1, done=False)) if path == 'complete_load' else getattr(d, path)()
+ except RuntimeError:
+ pass
+ assert d.broken is not None, path
+ sys.path.insert(0, args.source_root)
+ from tensorfold.cuda.health import Health
+ from tensorfold.server import metrics
+ d.streams = {}
+ d.filling = []
+ d.health = fail # a failing optional counters read cannot hide the latch
+ app = SimpleNamespace(engine=SimpleNamespace(scheduler=SimpleNamespace(decoder=d, max_streams=4)))
+ h = Health()
+ d.broken = None
+ assert h.snapshot(app)['ok'] is True
+ assert 'tensorfold_health:ok 1' in metrics.render(app)
+ d.broken = cause
+ body = h.snapshot(app)
+ assert body['ok'] is False and body['broken'] == 'RuntimeError: synthetic GPU failure'
+ assert 'tensorfold_health:ok 0' in metrics.render(app)
+ d.broken = RuntimeError('x' * 5000) # an unauthenticated route: a long cause is cut, its type kept
+ assert h.snapshot(app)['broken'] == 'RuntimeError: ' + 'x' * 200, len(h.snapshot(app)['broken'])
+ d.broken = cause
+ p = subprocess.run([sys.executable, '-B', __file__, '--source-root', args.source_root, '--child'],
+ capture_output=True, text=True, timeout=10)
+ assert p.returncode == 1, p
+ assert 'exiting with code 1' in p.stderr and 'synthetic GPU failure' in p.stderr, p.stderr
+ print('OK: settings, first-cause latch, request refusal, round/load/drop, health, metrics, non-zero process exit')
+
+
+if __name__ == '__main__':
+ main()