GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
v1.6: 0073 queued cancellation (by @desy0305, #51), 0074 compact before evict (#61, by @ezoushen, #62), 0075 <|assistant|> ends a reply (#60)
MiaAI-Lab585936585de4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b535706..5b80d08 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,9 +3,9 @@Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.-## v1.6 (unreleased): agent sessions keep their history beside sub-agents, the display reservation in the pool, a longer RoCE wait, SPLIT retried at start+## v1.6 (unreleased): agent sessions keep their history (beside sub-agents and under a full pool), queued requests whose client left are dropped, no raw `<|assistant|>` in replies, the display reservation in the pool, a longer RoCE wait, SPLIT retried at start-Image: not built yet (patches `23ba9d861151`, 72 patches); until it is published, `scripts/prepare.sh` builds it locally.+Image: not built yet (patches `c4cab25d2d36`, 75 patches); until it is published, `scripts/prepare.sh` builds it locally.### Fixed- **#43: a conversation lost its kept prompt whenever another conversation with the same system prompt resumed from@@ -15,6 +15,23 @@ Image: not built yet (patches `23ba9d861151`, 72 patches); until it is publishedfree rows, or `TF_GLM_MULTI_LONE=1`, it behaves as before. Placement only: the same replies. Two Sparks, v1.5 +0071, `tools/prompt_reuse.py` (new): 5% -> 99% of a ~33k-token turn resumed, 16.5 s -> 1.0 s to the first token(measured by @ezoushen and @plotarmordev); the same replies, drafted == serial.+- **#61: two long conversations taking turns at a nearly full pool evicted each other's kept prompt** (patch+ `0074-glm-compact-before-evict`, by @ezoushen, #62). A turn whose rows the pool had free, but not in one range,+ evicted kept prompts until a range opened, and compacted only after evicting them all, so two coding agents at once+ re-read 150-210K tokens of history (2-3 minutes). The pool now moves caches together first (each at most once) and+ evicts only while its free rows fall short. Placement only: the same replies. `tools/pool_pressure.py`: the other+ conversation's next turn 0% -> 100% resumed (measured by @ezoushen, two Sparks); `tools/pool_room_check.py` checks+ the moves on a CPU arena.+- **Requests waiting while every slot was busy kept waiting after their client left** (patch+ `0073-glm-queued-cancellation`, by @desy0305, #51), until a slot freed; the scheduler now drops them at once, in+ queue order. A reply whose connection fails mid-stream ends after the round instead of decoding on (the+ delivery-failure handling from @johnwhited's #48). Measured by @desy0305 on two Sparks: a queued fifth / ninth+ request cancelled with 4 / 8 slots busy was acknowledged in 0.11-0.21 s, the busy replies equal their serial ones,+ `PARALLEL=1` unchanged; `tools/test_queued_cancellation.py` checks it on the CPU.+- **#60: a raw `<|assistant|>` token reached replies** (patch `0075-glm-assistant-ends`; reported by+ @Lukas-tek-no-logic). At high reasoning effort the model sometimes wrote it inside its answer and began a second+ one; it now ends the reply, like the checkpoint's end tokens. `TF_GLM_ASSISTANT_ENDS=0` restores the old behaviour.+ Replies without the token are unchanged.- **#54: a RoCE all-gather failed on long prompts and took both Sparks down.** `TF_ROCE_WAIT_S` is now 300 s (was thepatch's 20): in the reports the failing rank's own writes had all completed, so the peer was late rather than lost.A late peer now costs a slow round; a rank that is really gone is noticed after 300 s, like the watchdog's report.diff --git a/CREDITS.md b/CREDITS.mdindex 666d321..6906352 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -98,6 +98,13 @@ checkpoint's ShapleyMcg attribution and the drafter's license).applied as contributed, with `tools/display_kv_check.py`. It applies to TensorFold's pool the display-reserve KVtechnique that [gabewillen](https://github.com/gabewillen) proposed for the vLLM kit in[MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks#234](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks/pull/234).+- `0073-glm-queued-cancellation` (requests waiting for a slot are dropped when their client leaves): by+ [desy0305](https://github.com/desy0305), [pull request #51](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/51),+ applied as contributed, with `tools/test_queued_cancellation.py`; its delivery-failure handling comes from+ [johnwhited](https://github.com/johnwhited)'s [pull request #48](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/48).+- `0074-glm-compact-before-evict` (the shared pool compacts before it evicts, issue #61): by+ [ezoushen](https://github.com/ezoushen), [pull request #62](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/62)+ (contributed as 0073), applied as contributed, with `tools/pool_pressure.py` and `tools/pool_room_check.py`.- Every patch, except the parts credited above: by MiaAI-Lab, developed with[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify orquote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; seediff --git a/README.md b/README.mdindex fbe2bcd..30527f5 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through anOpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image andvideo input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.6.0 on both Sparks (one rank on each)-in NVIDIA's PyTorch container, plus 72 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests, 2 of v1.6 by [ezoushen](https://github.com/ezoushen): a shared system prompt keeps each conversation's history, the display reservation in the pool): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,+in NVIDIA's PyTorch container, plus 75 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests, 5 of v1.6: a shared system prompt keeps each conversation's history, the display reservation in the pool and the pool compacting before it evicts, by [ezoushen](https://github.com/ezoushen); queued requests whose client left dropped at once, by [desy0305](https://github.com/desy0305); `<|assistant|>` ending a reply): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,faster prompt kernels, a one-shot RoCE all-gather between the Sparks, several requests over one shared cache pool,vision, tool calling, `/tokenize` and `/metrics`.@@ -263,7 +263,8 @@ caches from **one shared pool**:Any one request can grow to the full window, and the four together share the pool: e.g. one 1M-token conversationnext to one more of 1M, or next to three of ~640k. A request the pool cannot place yet waits until others finish (kept prompt states give way-first); `/health` shows `pool_tokens`, `pool_free_tokens` and the streams decoding, filling and paused.+first, least recently used first, and only while the free rows fall short: free rows in several ranges are gathered by+moving caches instead, patch `0074`); `/health` shows `pool_tokens`, `pool_free_tokens` and the streams decoding, filling and paused.TensorFold's budget on each Spark is `MemAvailable` at start minus a host reserve (`MEMORY_RESERVE_GIB`, 14.5 GiB here;TensorFold's own default is a tenth of RAM). The server uses about 10 GiB beyond its own estimate at its peak, so the@@ -416,6 +417,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `DENSE` | `q4` | the checkpoint's BF16 weights (attention, shared experts, dense layers, head): `q4` (4-bit groups of 64, the head in FP8, kv_b in BF16), `fp8` or `bf16`. **Non-English prompts:** `q4` can lose the end of turn on short French coding prompts (replies run to `max_tokens`, issue #18); `fp8` keeps it, at ~10% decode speed || `DRAFTER` | `dflash2` | `dflash2`: IncoAI's DFlash2 drafter, licensed [CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/), **non-commercial use only**; +5-10% decode. `mtp`: the checkpoint's own MTP head, one request at a time, which avoids that license (set it before the first `./start.sh` and DFlash2 is never downloaded) || `TF_GLM_MTP` | `auto` | the checkpoint's MTP head beside DFlash2: `auto` leaves it out while DFlash2 drafts every request; `1` (TensorFold v0.6.0's own default) loads it, 1.77 GiB a Spark, with `PARALLEL=1`. `DRAFTER=mtp` always loads it |+| `TF_GLM_ASSISTANT_ENDS` | `1` | `<\|assistant\|>` ends a reply, like `<\|user\|>` and `<\|observation\|>` (patch 0075, issue #60); `0`: only the checkpoint's own end tokens || `DRAFT_POLICY` | `fnc7:0.3` | how many DFlash2 drafts a round verifies: up to 7, until the drafts' chance under the request's own sampling noise drops below 0.3 || `COPY` / `COPY_MAX` | `1` / `15` | copy drafts: when the reply's last 8 tokens occurred before, the tokens that followed are verified ahead of DFlash2's, up to 15 a round || `COPY_CODE` | `1` | 16-row verify windows as CUDA graphs, and copies from the reply itself only after a 16-token match |@@ -533,6 +535,9 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| 3 Sparks (experimental) | `0066-glm-tp-n`, `0067-glm-tp3-split-pad`, `0068-glm-tpn-split-buffer-rows` | the engine on 2 or 3 ranks (`--tp`): heads, expert columns, vocabulary and DFlash2 KV groups split in whole units, the remainder to the lowest ranks; the row split (`SPLIT`) and its early connection to every peer; RoCE all-gathers over per-peer routes (b12x's proxy modified for more than two Sparks); prompt buffers and the memory estimate hold the split's pad row at three ranks | [3 Sparks](#3-sparks-experimental); two Sparks unchanged || Eight requests at once | `0069-glm-eight-streams` | up to 8 concurrent requests (`PARALLEL` 1 to 8): the batched verify window's segment tables (and the segmented kernels' launch grids) sized for the streams, four as before up to four; the multi-stream DFlash2 drafter, scheduler and memory estimate for 5 to 8 streams; the shared verify window's rows set by `TF_GLM_MULTI_WINDOW` (32 as before; 64 by default past 4 requests) and counted at start | 8 at once: +27% prose, +32% code over 4 on two Sparks (+36% / +28% on three); `PARALLEL` 1 to 4 unchanged ([Performance](#performance)) || Serial stop | `0070-glm-serial-stop` | at `PARALLEL=1`, a request whose client left, or that hit a stop string or a gate cut, ends on both ranks after the same round (rank 0's stop rides on the round's sample all-gather; issue #38); `--parallel` above 1 without DFlash2 refused at start with the options | same replies |+| Pool room | `0074-glm-compact-before-evict` | a request or a growing stream whose rows the pool has free, but not in one range, gets them by moving other caches (each at most once) instead of evicting kept prompts until a range opens; eviction only while the free rows fall short (by ezoushen, issue #61) | two conversations taking turns at a nearly full pool keep each other's kept state (`tools/pool_pressure.py`: the other's next turn 0% -> 100% resumed) |+| Queued cancellation | `0073-glm-queued-cancellation` | a request waiting while every slot is busy, whose client left, is dropped at once instead of when a slot frees (the scheduler polls the waiting callers; only it removes them, so rank 1 never sees them); a reply whose client connection fails mid-stream ends after the round (delivery failures, after johnwhited's #48) (by desy0305, PR #51) | a ninth request cancelled with 8 slots busy: acknowledged in ~0.1-0.2 s; the busy replies unchanged (two Sparks, by desy0305) |+| End of turn | `0075-glm-assistant-ends` | `<\|assistant\|>` ends a reply like the checkpoint's end tokens: the model sometimes started a second answer with it at high reasoning effort, and the raw token reached the reply's text (issue #60); `TF_GLM_ASSISTANT_ENDS=0` keeps the checkpoint's end tokens; the ranks check they agree at start | replies without the token unchanged || Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token@@ -582,6 +587,9 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array || `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |+| `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_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/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) || `tools/prompt_reuse.py [size]` | a ~33k-token conversation takes three more turns, each after a request of another conversation with the same system prompt (an agent and its sub-agents); exit 1 when a turn resumes less than 90% of its prompt. Needs `PARALLEL` above 1 |@@ -595,7 +603,8 @@ scripts/ config.sh (all settings), local.sh.example (this setup's WORKER),both Sparks), nodes.sh (ssh and the RoCE links), publish-image.sh (push the image to GHCR),banner.sh (start.sh's banner)patches/ patches baked into the image-tools/ checks against the running server (needle, tool calls, end of turn, prompt reuse) and patch 0072's in the image+tools/ checks against the running server (needle, tool calls, end of turn, prompt reuse, kept prompts under a+ full pool) and patches 0072's, 0073's and 0074's checksCHANGELOG.md what changed in each releaseCREDITS.md who and what this builds onLICENSE Apache License 2.0diff --git a/patches/0073-glm-queued-cancellation.patch b/patches/0073-glm-queued-cancellation.patchnew file mode 100644index 0000000..c28aab9--- /dev/null+++ b/patches/0073-glm-queued-cancellation.patch@@ -0,0 +1,113 @@+# Queued or memory-held GLM callers acknowledge disconnect before admission, even when all lanes are busy.+# The scheduler owns removal; active streams still finish through the decoder. Apache-2.0.+# By @desy0305 (PR #51).+# Each waiting caller polls with a 0.1 s queue timeout (~10 wakes/s/caller); acknowledgement also waits for a scheduler round.+# Extends 0058's client-gone poll to queued callers; preserves 0070's decoder/rank stop vote and serial path.+# Delivery-failure idea by @johnwhited (PR #48); shared-loop ownership pending author agreement.+# Proposed GLM integration: stop on callback error, then report it after decoder cleanup.+# No admission limit or HTTP status changes; the generic cuda/scheduler.py delivery fix remains separate.+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -1774,19 +1774,79 @@+ stream = Stream(list(prompt), max(1, count), sampling, draft=draft, stop_eos=stop_eos, vision=vision,+ constraint=constraint, background=background)+ stream.glm = dict(glm or {})+- cancel = [False]+- stream.emit = lambda new: (box.put(("tokens", new)), cancel[0])[1]+- stream.emit.cancelled = getattr(emit, "cancelled", None)++ # The caller polls; only the scheduler removes cancelled queued requests.++ stop, disconnected, cancel_error = [False], [False], [None]++ poll = getattr(emit, "cancelled", None)++++ def cancelled() -> bool:++ if not disconnected[0] and cancel_error[0] is None and poll is not None:++ try:++ if poll(): # sticky: an older False poll must never undo another's True++ disconnected[0] = stop[0] = True++ except Exception as exc:++ cancel_error[0], stop[0] = exc, True++ return disconnected[0] or cancel_error[0] is not None++++ stream.emit = lambda new: (box.put(("tokens", new)), stop[0])[1]++ stream.emit.cancelled = cancelled++ stream.emit.cancel_requested = lambda: disconnected[0] or cancel_error[0] is not None++ stream.emit.cancel_error = lambda: cancel_error[0]+ self.waiting.put((stream, box))+ while True:+- kind, value = box.get()++ cancelled()++ try:++ kind, value = box.get(timeout=0.1)++ except queue.Empty:++ continue+ 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++ if not stop[0]:++ try:++ if emit(value):++ stop[0] = True # a normal stop/gate cut is not cancellation++ except Exception as exc:++ cancel_error[0], stop[0] = exc, True+ elif kind == "error":+ raise value+ else:++ if cancel_error[0] is not None: # report callback failures only after active decoder cleanup++ raise cancel_error[0]++ if disconnected[0]:++ from tensorfold.server.cancellation import RequestCancelled++ raise RequestCancelled("the client left during the reply")+ return value++++ def _cancel_item(self, item) -> bool:++ """Scheduler-owned cancellation of a not-admitted request; no decoder/rank state exists yet."""++ from tensorfold.server.cancellation import RequestCancelled++++ stream, box = item++ poll = getattr(stream.emit, "cancelled", None)++ if poll is None or not poll():++ return False++ error = getattr(stream.emit, "cancel_error", lambda: None)()++ box.put(("error", error if error is not None else RequestCancelled("the client left before admission")))++ return True++++ def _cancel_waiting(self) -> None:++ """Reap waiting/held requests even when every lane is busy; retain exact queue priorities/order."""++ import heapq++++ if self.held is not None and self._cancel_item(self.held):++ self.held = None++ removed = []++ # Never call the socket callback while holding the queue lock: these are caller-latched flags.++ with self.waiting.mutex:++ kept = []++ for entry in self.waiting.queue:++ stream, _ = entry[2]++ flag = getattr(stream.emit, "cancel_requested", None)++ (removed if flag is not None and flag() else kept).append(entry)++ if removed:++ self.waiting.queue[:] = kept++ heapq.heapify(self.waiting.queue)++ self.waiting.not_full.notify_all()++ for entry in removed:++ self._cancel_item(entry[2])++ def _admit(self, first=None, until: float | None = None) -> list[Stream]:+ """Waiting requests into free slots while they fit; ``until`` (a ``time.monotonic`` deadline): an empty queue+@@ -1804,6 +1864,8 @@+ item = self.waiting.get(timeout=left) if left > 0 else self.waiting.get_nowait()+ except queue.Empty:+ break++ if self._cancel_item(item):++ continue+ stream, box = item+ if not self.decoder.fits(stream):+ self.held = item # waits, first in line, for room+@@ -1864,6 +1926,7 @@+ self._reply(s, "error", exc)++ def _iteration(self) -> None:++ self._cancel_waiting()+ self._yield()+ idle = not self.decoder.live() and self.held is None+ first = self.waiting.get() if idle else None # idle: wait for a requestdiff --git a/patches/0074-glm-compact-before-evict.patch b/patches/0074-glm-compact-before-evict.patchnew file mode 100644index 0000000..f8ac6ce--- /dev/null+++ b/patches/0074-glm-compact-before-evict.patch@@ -0,0 +1,100 @@+# With --parallel, a request or a decoding stream that needed rows the pool had free, but not in one range, evicted+# kept prompts (least recently used first) until a free range opened, and compacted only after evicting every one.+# Two long conversations taking turns (two agents at once) then evicted each other: a turn whose extent could not+# grow in place dropped the other conversation's only state, and its next turn read its whole history again (150-210K+# tokens, 2-3 minutes). Now the pool compacts as soon as its free rows cover the request (for a growing extent, the+# extents up to it slide down and the ones after it up, so the free rows follow it; each moves once at most), and+# evicts only while they fall short. A turn of one conversation may then move the other's rows: a copy on the GPU,+# against a prefill of the evicted conversation. Same replies: placement only, the moved rows are the same bytes.+# By @ezoushen (PR #62).++diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 35409ed..52a8ad3 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -1005,34 +1005,51 @@ class MultiDecoder:+ keep = set(id(x) for x in protect)+ return [c for c in self.kept if c.extent.owner is None and id(c.extent) not in keep]++- def _compact(self) -> None:+- """Rank 0: slide every extent down to the lowest free rows (MOVEs), so the free rows are one range."""++ def _compact(self, grow=None) -> None:++ """Rank 0: slide every extent down to the lowest free rows (MOVEs), so the free rows are one range; with++ ``grow``, only the extents up to it slide down and the ones after it up to the pool's end, so that range++ follows ``grow`` (each extent moves once at most)."""++ at = 0+ for x in list(self.pool.extents):++ if grow is not None and x.base > grow.base:++ break+ if x.base != at:+ self._emit(MOVE, [x.eid, at, x.size])+ self._move(x, at, x.size)+ at += x.size++ if grow is None:++ return++ top = self.pool.rows++ for x in reversed(list(self.pool.extents)):++ if x is grow:++ break++ top -= x.size++ if x.base != top:++ self._emit(MOVE, [x.eid, top, x.size])++ self._move(x, top, x.size)++ def _room(self, need: int, protect=()) -> int | None:+ """Rank 0: a base with ``need`` free rows, evicting kept prompts (least recently used first, never+- ``protect``'s extents) and compacting as needed; None if even that leaves too little."""++ ``protect``'s extents) only while the free rows fall short of ``need``, then compacting if they are not++ together: moving rows costs far less than prefilling an evicted conversation again. None if even evicting++ every other kept prompt leaves too little."""++ base = self.pool.place(need)+ while base is None:++ if self.pool.free_rows() >= need:++ self._compact()++ return self.pool.place(need)+ victims = self._victims(protect)+ if not victims:+ break+ self._evict(victims[0])+ base = self.pool.place(need)+- if base is None and self.pool.free_rows() >= need:+- self._compact()+- base = self.pool.place(need)+ return base++ def _grow(self, x, size: int, protect=()) -> bool:+- """Rank 0: extent x to at least ``size`` rows, in place or moved (evicting and compacting as needed)."""++ """Rank 0: extent x to at least ``size`` rows, in place or moved; as in ``_room``, compacting before evicting++ more than the free rows fall short."""++ size = align_up(size)+ if size <= x.size:+@@ -1048,22 +1065,13 @@ class MultiDecoder:+ self._emit(MOVE, [x.eid, base, size])+ self._move(x, base, size)+ return True++ if self.pool.free_rows() + x.size >= size:++ self._compact(grow=x) # the rows are free, just not together: gathered right after x++ continue+ victims = self._victims(protect)+ if not victims:+- break++ return False+ self._evict(victims[0])+- if self.pool.free_rows() + x.size >= size:+- self._compact()+- if self.pool.room_after(x) >= size - x.size:+- self._emit(GROW, [x.eid, size])+- self._resize(x, size)+- return True+- base = self.pool.place(size, ignore=[x])+- if base is not None:+- self._emit(MOVE, [x.eid, base, size])+- self._move(x, base, size)+- return True+- return False++ # -- iterations ---------------------------------------------------------------------------------------------------------+ @torch.no_grad()diff --git a/patches/0075-glm-assistant-ends.patch b/patches/0075-glm-assistant-ends.patchnew file mode 100644index 0000000..2230359--- /dev/null+++ b/patches/0075-glm-assistant-ends.patch@@ -0,0 +1,82 @@+# GLM's <|assistant|> role token (154828) ends a reply, like the checkpoint's end tokens <|endoftext|>, <|user|> and+# <|observation|>. At high reasoning effort the model sometimes wrote it inside its answer and started a second one+# (an English re-reasoning and the same answer again), and the reply's text carried the raw token to the client, which+# agents then fed back into the conversation (issue #60, reported by @Lukas-tek-no-logic). The token is read from the+# checkpoint's tokenizer.json and joins Config.eos, which every decode loop, the multi-stream engine, the grammar and+# the server's text use on every rank; the startup comparison checks the ranks agree. TF_GLM_ASSISTANT_ENDS=0 keeps the+# checkpoint's end tokens. Replies without the token are unchanged.++diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 4de2fb1..473c904 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -665,7 +665,7 @@ class GlmEngine:+ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING), int(self.mtp_on),+ parallel, *verify_code, int(union_cover()), MAX_ROWS, len(WIDE_GRAPHS),+ sum(WIDE_GRAPHS), max(WIDE_GRAPHS, default=0),+- KV_KINDS.index(kv)]++ KV_KINDS.index(kv), len(cfg.eos), sum(cfg.eos)]+ # other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks+ plan = self.capacity_plan+ wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)+@@ -678,7 +678,7 @@ class GlmEngine:+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "+ "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE / _PROFILE / _WINDOW, "+- "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV): "++ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV, TF_GLM_ASSISTANT_ENDS): "+ f"rank 0 {rows[0][:-1]}, " + ", ".join(f"rank {r} {rows[r][:-1]}" for r in odd) ++ "; pull the draft model on every machine (or pass --drafter none to all) and give "+ "every rank the same flags")+diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py+index b768c7d..6746779 100644+--- tensorfold/families/glm5_next/cuda/weights.py++++ tensorfold/families/glm5_next/cuda/weights.py+@@ -3,7 +3,9 @@+ from __future__ import annotations++ import json++import os+ from dataclasses import dataclass, field++from functools import lru_cache+ from pathlib import Path+ from typing import Any++@@ -19,6 +21,27 @@ from .qmm import (B16, F8, Q4, as_i32, dense_kind, draft_quantize4, kvb_kind, ma+ PREFIX = "model.language_model."++++@lru_cache(maxsize=None)++def assistant_end(model_dir: str) -> int | None:++ """The id of GLM's ``<|assistant|>`` role token when it ends a reply (TF_GLM_ASSISTANT_ENDS, default 1; 0: it++ doesn't), or None without one in the checkpoint's tokenizer. The checkpoint's end tokens are ``<|endoftext|>``,++ ``<|user|>`` and ``<|observation|>``; at high reasoning effort the model sometimes writes ``<|assistant|>``++ inside its answer and starts a second one, which reached the client with the token in its text (issue #60). A new++ assistant turn inside an assistant turn ends it: the reply stops there, as at the other role tokens."""++++ on = (os.environ.get("TF_GLM_ASSISTANT_ENDS", "") or "1").strip()++ if on not in ("0", "1"):++ raise ValueError(f"TF_GLM_ASSISTANT_ENDS: 0 or 1, not {on!r}")++ path = Path(model_dir) / "tokenizer.json"++ if on == "0" or not path.is_file():++ return None++ try:++ added = json.loads(path.read_text()).get("added_tokens", [])++ except (OSError, ValueError):++ return None++ return next((int(t["id"]) for t in added if t.get("content") == "<|assistant|>" and t.get("special")), None)+++++ @dataclass+ class Config:+ hidden: int+@@ -70,6 +93,9 @@ class Config:+ quant = raw.get("quantization") or raw.get("quantization_config") or {}+ eos = t.get("eos_token_id", raw.get("eos_token_id"))+ eos = tuple(int(e) for e in eos) if isinstance(eos, list) else (int(eos),)++ end = assistant_end(str(Path(model_dir)))++ if end is not None and end not in eos:++ eos += (end,) # issue #60: a new assistant turn ends the reply (TF_GLM_ASSISTANT_ENDS)+ n = int(t["num_hidden_layers"])+ kinds = ["kda" if k == "linear_attention" else "dsa" for k in t["layer_types"]]+ dense = int(t.get("first_k_dense_replace", 3))diff --git a/tools/pool_pressure.py b/tools/pool_pressure.pynew file mode 100755index 0000000..d4631f0--- /dev/null+++ b/tools/pool_pressure.py@@ -0,0 +1,92 @@+#!/usr/bin/env python3+"""Two conversations taking turns keep each other's prompt state when the shared pool is nearly full (two agents at+once, each with a long history): one's next turn must not evict the other's kept state while the pool's free rows+would hold it after a compaction.++Usage: tools/pool_pressure.py [size] (API_URL / PORT as in client.py). Run it on a freshly started server with+`PARALLEL` above 1 and nothing else sending requests: it places prompts by filling the pool. A smaller pool runs it+faster (e.g. CONTEXT=131072 KV_POOL_GIB=0.5). Each conversation's history is ~size tokens (default 30000, at least+24000). Exit code 1 when a turn resumes less than 90% of the conversation's previous prompt; 2 when the pool could not+be filled as the check needs (the kept-prompt cap, TF_GLM_CACHE_ENTRIES, reached first).++Conversations A and B each take a turn (B's state lands right after A's in the pool), other conversations fill the+pool until fewer free rows are left than A's next turn takes, then A takes a turn that adds ~4000 tokens (its rows+must grow into B's or move), then B takes its next turn.+"""+import json+import os+import sys+import time+import urllib.request++sys.dont_write_bytecode = True # no tools/__pycache__ from importing client+from client import API_URL, URL, open_url, prose # noqa: E402++MODEL = os.environ.get("MODEL", "GLM-5.3-Flash-EXL3")+++def health() -> dict:+ return json.load(open_url(urllib.request.Request(API_URL + "/health"), 30))+++def chat(messages: list) -> tuple[dict, int, int, float]:+ body = {"model": MODEL, "messages": messages, "max_tokens": 32, "temperature": 0, "reasoning_effort": "low"}+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})+ t0 = time.time()+ reply = json.load(open_url(req, 1800))+ usage = reply["usage"]+ cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0+ return reply["choices"][0]["message"], usage["prompt_tokens"], cached, time.time() - t0+++def turn(name: str, convo: list, before: int = 0) -> tuple[int, float]:+ """The turn's prompt tokens, and the share of ``before`` (the conversation's previous prompt) it resumed."""+ msg, prompt, cached, secs = chat(convo)+ convo.append({"role": "assistant", "content": msg.get("content") or ""})+ share = min(1.0, cached / before) if before else 1.0+ print(f"{name}: {prompt} prompt tokens, {cached} cached" + (f" ({share:.0%} of its previous prompt)" if before+ else "") + f", {secs:.1f} s")+ return prompt, share+++def main() -> None:+ size = int(sys.argv[1]) if len(sys.argv) > 1 else 30000+ if size < 24000:+ sys.exit("size: at least 24000 (the free rows left must hold A's next turn's ~4000 more)")+ h = health()+ if "pool_tokens" not in h:+ sys.exit("run it on a server started with PARALLEL above 1 (no shared pool otherwise)")+ if h.get("kept_prompts") or h.get("requests_running"):+ sys.exit(f"the server holds {h.get('kept_prompts')} kept prompts and runs {h.get('requests_running')} "+ "requests: start it again, and send nothing else while this runs")+ words = int(size / 0.82)+ a = [{"role": "user", "content": "Conversation A. Summarize this log in one line.\n" + prose(words, 1)}]+ b = [{"role": "user", "content": "Conversation B. Summarize this log in one line.\n" + prose(words, 2)}]+ a1, _ = turn("A, turn 1 (cold)", a)+ b1, _ = turn("B, turn 1 (cold)", b)+ pool = h["pool_tokens"]+ longest = min(h["context_length"] - 4096, 262144) # long cold prompts take minutes each+ now = health()+ left, kept, n = now["pool_free_tokens"], now["kept_prompts"], 0+ while left > size // 2: # fewer free rows than A's next turn takes (and size // 4 or more: it adds ~4000)+ n += 1+ fill = min(left - size // 4 - 2048, longest)+ chat([{"role": "user", "content": f"Filler {n}. Name the most common word.\n" + prose(int(fill / 0.82), 100 + n)}])+ now = health()+ if now["kept_prompts"] <= kept:+ print(f"the kept-prompt cap ({kept}) was reached before the pool filled: inconclusive (raise "+ "TF_GLM_CACHE_ENTRIES or pass a larger size)")+ sys.exit(2)+ left, kept = now["pool_free_tokens"], now["kept_prompts"]+ print(f"{n} other conversations: {left} of the pool's {pool} rows free")+ a.append({"role": "user", "content": "A tool result:\n" + prose(int(4000 / 0.82), 3)})+ _, worst = turn("A, turn 2 (adds ~4000 tokens)", a, a1)+ b.append({"role": "user", "content": "And in one word?"})+ worst = min(worst, turn("B, turn 2", b, b1)[1])+ ok = worst >= 0.9+ print("pool_pressure:", "OK" if ok else f"FAILED: a turn resumed only {worst:.0%} of its previous prompt")+ sys.exit(0 if ok else 1)+++if __name__ == "__main__":+ main()diff --git a/tools/pool_room_check.py b/tools/pool_room_check.pynew file mode 100755index 0000000..52a07e1--- /dev/null+++ b/tools/pool_room_check.py@@ -0,0 +1,159 @@+#!/usr/bin/env python3+"""Checks for patch 0074 (the shared pool compacts before it evicts), run inside the image that scripts/prepare.sh+built:++ docker run --rm --entrypoint python -v "$PWD/tools/pool_room_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py++MultiDecoder's room-making (_grow, _room) on the real Pool and a CPU arena, no GPU or model: a conversation whose+extent cannot grow in place and a new request, each while the pool's free rows cover them in several ranges (nothing+evicted, every kept prompt's rows intact, each extent moved once at most, rank 1 replaying the ops to the same+extents and rows), the same for a decoding stream's extent, too few free rows (only the least recently used state it+needs evicted), and protected extents. Exit code 1 when a check fails.+"""+from types import SimpleNamespace as NS++import torch++from tensorfold.families.glm5_next.cuda.multi import MOVE, MultiDecoder+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Arena, Plane, Pool, align_up++B = ALIGN # one block of rows+failures = []+++def check(name, ok, detail=""):+ print(("ok " if ok else "FAIL ") + name + (f" ({detail})" if detail and not ok else ""))+ if not ok:+ failures.append(name)+++def decoder(blocks):+ rows = blocks * B+ m = object.__new__(MultiDecoder)+ m.pool, m.kept, m.lanes, m.partial = Pool(rows), [], {}, None+ m.arena = Arena(rows, [Plane(torch.zeros(rows, dtype=torch.int32)), Plane(torch.zeros(rows // 4, dtype=torch.int32), 4)])+ m.ops = []+ m._emit = lambda op, p: m.ops.append((op, list(p)))+ return m+++def moves(m, x):+ """How many times rank 0 moved extent x."""+ return sum(1 for op, p in m.ops if op == MOVE and p[0] == x.eid)+++def replays(m, r):+ """Rank 1 (``r``, built like ``m`` before the call) applies rank 0's ops and ends with the same extents and rows."""+ msg = [v for op, p in m.ops for v in (op, len(p), *p)]+ r.apply(msg)+ same = [(x.eid, x.base, x.size) for x in r.pool.extents] == [(x.eid, x.base, x.size) for x in m.pool.extents]+ return same and all(bool((a.tensor == b.tensor).all()) for a, b in zip(m.arena.planes, r.arena.planes))+++def keep(m, at_block, tokens, name):+ """A kept prompt of ``tokens`` at block ``at_block``, its rows tagged with its own number; appended as the most+ recently used."""+ x = m.pool.add(at_block * B, align_up(tokens))+ tag = len(m.kept) + 1+ for p in m.arena.planes:+ p.view(x.base, x.size)[:-(-tokens // p.div)] = tag+ c = NS(ids=[0] * tokens, key=[0] * tokens, extent=x, kid=tag, shared=False, name=name, tag=tag,+ rec=0, conv=0, tail=0, head=0, drafter_rows=0)+ x.kept = [c]+ m.kept.append(c)+ return x+++def alive(m):+ return [c.name for c in m.kept]+++def rows_intact(m):+ """Every kept prompt's rows still hold its tag at its extent's current base."""+ for c in m.kept:+ for p in m.arena.planes:+ got = p.view(c.extent.base, c.extent.size)[:-(-len(c.ids) // p.div)]+ if not bool((got == c.tag).all()):+ return False+ return True+++# A conversation's next turn needs 2 more blocks; the rows right after it are another kept prompt and no free gap+# holds the grown extent, but the pool's free rows (5 blocks in 4 holes) cover it. Least recently used: "other" (the+# second agent's only state).+def fragmented():+ m = decoder(24)+ keep(m, 0, 6 * B, "other") # blocks 0-5+ keep(m, 7, 2 * B, "old1") # hole at 6+ keep(m, 10, 2 * B, "old2") # hole at 9+ a = keep(m, 13, 6 * B, "agent") # hole at 12+ keep(m, 19, 3 * B, "neighbour") # right after the agent; hole at 22-23+ m.kept = [c for c in m.kept if c.name != "agent"] + [c for c in m.kept if c.name == "agent"]+ return m, a+++m, a = fragmented()+r, _ = fragmented()+check("fragmented: the free rows cover the growth, no gap does",+ m.pool.free_rows() >= 2 * B and m.pool.room_after(a) == 0 and m.pool.place(8 * B, ignore=[a]) is None)+check("grow: succeeds", m._grow(a, 8 * B, protect=[a]))+check("grow: compacts instead of evicting (every kept prompt stays)",+ alive(m) == ["other", "old1", "old2", "neighbour", "agent"], alive(m))+check("grow: the agent's extent has its rows", a.size >= 8 * B)+check("grow: every kept prompt's rows moved intact", rows_intact(m))+check("grow: the neighbour moves once (up, out of the agent's way), not down and back up",+ moves(m, m.pool.extents[-1]) == 1, m.ops)+check("grow: rank 1 replaying the ops ends with the same extents and rows", replays(m, r))++# The same while the agent's extent is a decoding stream's (its rows up to the stream's position, rebound when moved).+m, a = fragmented()+bound = []+m.kept = [c for c in m.kept if c.name != "agent"]+a.kept, a.owner = [], 7+for p in m.arena.planes:+ p.view(a.base, a.size)[:] = 99+m.lanes = {7: NS(st=NS(pos=6 * B - 5, bind=lambda base, size: bound.append((base, size))))}+check("decoding grow: succeeds", m._grow(a, 8 * B, protect=[a]))+check("decoding grow: compacts instead of evicting", alive(m) == ["other", "old1", "old2", "neighbour"], alive(m))+check("decoding grow: the stream's rows moved intact",+ all(bool((p.view(a.base, a.size)[:-(-(6 * B - 5) // p.div)] == 99).all()) for p in m.arena.planes))+check("decoding grow: the stream is bound to where its extent is", not bound or bound[-1] == (a.base, a.size), bound)+check("decoding grow: the other kept prompts' rows moved intact", rows_intact(m))++# A new request needs 4 blocks: the free rows (4 holes) cover it, no gap does.+def holes():+ m = decoder(16)+ keep(m, 0, 3 * B, "other")+ keep(m, 4, 3 * B, "old1")+ keep(m, 8, 3 * B, "old2")+ keep(m, 12, 3 * B, "old3")+ return m+++m, r = holes(), holes()+base = m._room(4 * B)+check("room: a base for the new extent", base is not None and m.pool.place(4 * B) == base)+check("room: compacts instead of evicting", alive(m) == ["other", "old1", "old2", "old3"], alive(m))+check("room: every kept prompt's rows moved intact", rows_intact(m))+check("room: rank 1 replaying the ops ends with the same extents and rows", replays(m, r))++# Too little free rows: evict least recently used, only until the free rows cover the request, then compact. Here the+# oldest ("other", 3 blocks, not next to a hole big enough) is enough; evicting until a gap opens would also drop more.+m = decoder(16)+keep(m, 0, 3 * B, "other") # hole at 3+keep(m, 4, 5 * B, "old1") # hole at 9+keep(m, 10, 5 * B, "old2") # hole at 15+base = m._room(5 * B)+check("room short: a base", base is not None)+check("room short: evicts only the least recently used state it needs", alive(m) == ["old1", "old2"], alive(m))+check("room short: the survivors' rows moved intact", rows_intact(m))++# Protected extents are never evicted, compaction or not.+m = decoder(10)+p = keep(m, 0, 4 * B, "protected")+keep(m, 5, 4 * B, "old")+check("protect: room for 4 blocks evicts the unprotected one", m._room(4 * B, [p]) is not None and alive(m) == ["protected"],+ alive(m))++print(f"{'FAILED ' + str(len(failures)) if failures else 'all passed'}")+raise SystemExit(1 if failures else 0)diff --git a/tools/test_queued_cancellation.py b/tools/test_queued_cancellation.pynew file mode 100644index 0000000..95f5d61--- /dev/null+++ b/tools/test_queued_cancellation.py@@ -0,0 +1,452 @@+"""CPU-only GLM queue lifecycle regression using the real scheduler classes.++Run after applying the recipe patches to TensorFold v0.6.0:+ python3 -B tools/test_queued_cancellation.py --source-root /path/to/src+Use --expect-stock before patch 0073 to reproduce the original full-lanes+gap. No Torch/CUDA, sockets, package installation or source writes are needed.+"""+from __future__ import annotations++import argparse+import ast+import hashlib+import importlib.util+import itertools+import json+import queue+import sys+import threading+import time+from types import SimpleNamespace+from pathlib import Path+from typing import Any, Callable+++def module(name, path):+ spec = importlib.util.spec_from_file_location(name, path)+ obj = importlib.util.module_from_spec(spec)+ sys.modules[name] = obj+ spec.loader.exec_module(obj)+ return obj+++def classes(source, names, namespace):+ nodes = [ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0)]+ nodes += [n for n in ast.parse(source).body if isinstance(n, ast.ClassDef) and n.name in names]+ assert len(nodes) == len(names) + 1, "missing or duplicate source class"+ exec(compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])), "<scheduler>", "exec"), namespace)+++class Decoder:+ watchdog = 0++ def __init__(self):+ self.streams, self.requeue, self.admitted, self.finished, self.fits_calls = {}, [], [], [], []+ self.room = True++ def live(self):+ return len(self.streams)++ def fits(self, stream):+ self.fits_calls.append(stream)+ return self.room++ def admit(self, stream):+ self.admitted.append(stream)+ self.streams[id(stream)] = stream++ def round(self):+ return [s for s in self.streams.values() if s.done]++ def finish(self, done):+ self.finished.extend(done)+ for stream in done:+ self.streams.pop(id(stream), None)++ def stats(self, stream):+ return stream.stats()+++def wait(predicate):+ deadline = time.monotonic() + 2+ while not predicate():+ assert time.monotonic() < deadline, "caller/scheduler did not make bounded progress"+ time.sleep(0.002)+++def main():+ cli = argparse.ArgumentParser(description=__doc__)+ cli.add_argument("--source-root", type=Path, required=True, help="directory containing tensorfold/")+ cli.add_argument("--expect-stock", action="store_true")+ args = cli.parse_args()+ root = args.source_root / "tensorfold"+ Stream = module("queue_streams", root / "cuda/streams.py").Stream+ Cancelled = module("tensorfold.server.cancellation", root / "server/cancellation.py").RequestCancelled+ ns = dict(queue=queue, threading=threading, itertools=itertools, Any=Any, Callable=Callable,+ Stream=Stream, time=time, _unwatch=lambda _: None)+ source = (root / "families/glm5_next/cuda/multi.py").read_text(encoding="utf-8")+ classes(source, {"NoRoom"}, ns)+ classes((root / "cuda/scheduler.py").read_text(encoding="utf-8"), {"Waiting", "Scheduler"}, ns)+ classes(source, {"GlmScheduler"}, ns)++ def scheduler(holders=0, capacity=4):+ obj = object.__new__(ns["GlmScheduler"])+ obj.decoder, obj.max_streams = Decoder(), capacity+ obj.waiting, obj.held, obj.boxes, obj.yields, obj.gather_s = ns["Waiting"](), None, {}, 0, 0+ for _ in range(holders):+ stream = Stream([1], 100)+ obj.decoder.streams[id(stream)] = stream+ return obj++ def ask(obj, poll, background=False, emit_hook=None):+ reply = {}+ def emit(tokens):+ return False if emit_hook is None else emit_hook(tokens)+ emit.cancelled = poll+ def run():+ try:+ reply["stats"] = obj.submit([1], 100, None, False, emit, background=background)+ except Exception as exc:+ reply["error"] = exc+ thread = threading.Thread(target=run, daemon=True)+ thread.start()+ wait(lambda: obj.waiting.qsize() == 1)+ return thread, reply++ def cancelled_reply(thread, reply, error=Cancelled):+ thread.join(2)+ assert not thread.is_alive() and isinstance(reply.get("error"), error)++ checks = []+ obj, event = scheduler(4), threading.Event()+ thread, reply = ask(obj, event.is_set)+ holders = tuple(obj.decoder.streams)+ event.set()+ if args.expect_stock:+ time.sleep(0.12)+ obj._iteration()+ assert thread.is_alive() and obj.waiting.qsize() == 1 and not reply+ _, box = obj.waiting.get_nowait() # test cleanup, not stock cancellation behavior+ box.put(("error", Cancelled("test cleanup")))+ cancelled_reply(thread, reply)+ print(json.dumps({"stock_gap_reproduced": True, "device_calls": 0}))+ return+ wait(lambda: obj.waiting.queue[0][2][0].emit.cancel_requested())+ obj._iteration()+ cancelled_reply(thread, reply)+ assert obj.waiting.empty() and tuple(obj.decoder.streams) == holders+ assert not obj.decoder.admitted and not obj.decoder.fits_calls+ checks.append("full lanes: caller acknowledged without admission or touching holders")++ obj, event = scheduler(8, 8), threading.Event()+ thread, reply = ask(obj, event.is_set)+ holders = tuple(obj.decoder.streams)+ event.set()+ wait(lambda: obj.waiting.queue[0][2][0].emit.cancel_requested())+ obj._iteration()+ cancelled_reply(thread, reply)+ assert obj.waiting.empty() and tuple(obj.decoder.streams) == holders and not obj.decoder.admitted+ checks.append("eight full lanes: same pre-admission cancellation")++ obj, event = scheduler(3), threading.Event()+ thread, reply = ask(obj, event.is_set)+ obj.decoder.room = False+ obj._admit()+ assert obj.held is not None+ event.set()+ obj._iteration()+ cancelled_reply(thread, reply)+ assert obj.held is None and not obj.decoder.admitted+ checks.append("memory-held cancellation")++ obj = scheduler()+ thread, reply = ask(obj, lambda: True)+ obj._admit(obj.waiting.get_nowait())+ cancelled_reply(thread, reply)+ assert not obj.decoder.fits_calls+ checks.append("pre-cancelled idle admission")++ obj, entries = scheduler(4), []+ for n, (background, cancel) in enumerate([(False, False), (False, True), (True, False), (False, False)]):+ stream, box = Stream([n], 100, background=background), queue.Queue()+ stream.emit = lambda _: False+ stream.emit.cancelled = lambda cancel=cancel: cancel+ stream.emit.cancel_requested = stream.emit.cancelled+ obj.waiting.put((stream, box))+ entries.append((stream, box))+ obj._cancel_waiting()+ assert isinstance(entries[1][1].get_nowait()[1], Cancelled)+ assert [obj.waiting.get_nowait()[0].prompt[0] for _ in range(3)] == [0, 3, 2]+ obj._cancel_waiting()+ assert entries[1][1].empty()+ checks.append("foreground FIFO, background priority and exactly one acknowledgement")++ obj, event = scheduler(), threading.Event()+ thread, reply = ask(obj, event.is_set)+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ event.set()+ wait(stream.emit.cancel_requested)+ obj._cancel_waiting()+ assert thread.is_alive() and obj.decoder.live() == 1 and not reply+ stream.take([2])+ obj._iteration()+ cancelled_reply(thread, reply)+ assert obj.decoder.live() == 0 and obj.decoder.finished == [stream]+ checks.append("active disconnect raises only after normal decoder finish")++ for method in ("_yield", "_requeue"):+ obj, event = scheduler(), threading.Event()+ thread, reply = ask(obj, event.is_set, background=True)+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ if method == "_yield":+ obj.max_streams = 1+ obj.waiting.put((Stream([99], 100), queue.Queue()))+ else:+ obj.decoder.streams.clear() # decoder has already freed the lane before reporting requeue+ obj.decoder.requeue = [stream]+ getattr(obj, method)()+ again = next(e[2][0] for e in obj.waiting.queue if e[2][0].background)+ assert again.emit is stream.emit+ event.set()+ wait(again.emit.cancel_requested)+ obj._cancel_waiting()+ cancelled_reply(thread, reply)+ assert id(stream) not in obj.boxes+ checks.append(method + " preserves cancellation and reply ownership")++ def broken_poll():+ raise ValueError("callback failed")+ obj = scheduler(4)+ thread, reply = ask(obj, broken_poll)+ wait(lambda: obj.waiting.queue[0][2][0].emit.cancel_requested())+ obj._iteration()+ cancelled_reply(thread, reply, ValueError)+ assert obj.decoder.live() == 4+ checks.append("poll failure is isolated to its caller")++ class ObservedBox(queue.Queue):+ def __init__(self):+ super().__init__()+ self.gets, self.first_get, self.next_get = 0, threading.Event(), threading.Event()+ def get(self, *args, **kwargs):+ self.gets += 1+ (self.first_get if self.gets == 1 else self.next_get).set()+ return super().get(*args, **kwargs)++ # A caller's older False poll returns only after another poll has latched True.+ entered, release = threading.Event(), threading.Event()+ calls, calls_lock, box = [0], threading.Lock(), ObservedBox()+ def overlap_poll():+ with calls_lock:+ calls[0] += 1+ n = calls[0]+ if n == 1:+ entered.set()+ assert release.wait(2)+ return False+ return True+ obj = scheduler(4)+ ns["queue"] = SimpleNamespace(Queue=lambda: box, Empty=queue.Empty)+ thread, reply = ask(obj, overlap_poll)+ try:+ assert entered.wait(2)+ stream = obj.waiting.queue[0][2][0]+ assert stream.emit.cancelled()+ release.set()+ assert box.first_get.wait(2) # the caller has consumed its older False result+ assert stream.emit.cancel_requested(), "an older False poll unlatched disconnect"+ obj._iteration()+ cancelled_reply(thread, reply)+ finally:+ release.set()+ box.put(("error", Cancelled("test cleanup")))+ thread.join(2)+ ns["queue"] = queue+ checks.append("overlapping polls cannot undo a latched disconnect")++ # Normal emit=True stop/gate cuts are not socket disconnects, including replay.+ for method in ("_yield", "_requeue"):+ permit, emitted, box = threading.Event(), threading.Event(), ObservedBox()+ def normal_stop(tokens):+ emitted.set()+ assert permit.wait(2)+ return True+ obj = scheduler()+ ns["queue"] = SimpleNamespace(Queue=lambda: box, Empty=queue.Empty)+ thread, reply = ask(obj, lambda: False, background=True, emit_hook=normal_stop)+ try:+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ stream.take([2])+ assert emitted.wait(2)+ if method == "_yield":+ obj.max_streams = 1+ obj.waiting.put((Stream([99], 100), queue.Queue()))+ else:+ obj.decoder.streams.clear()+ obj.decoder.requeue = [stream]+ getattr(obj, method)()+ if method == "_yield":+ assert obj.waiting.get_nowait()[0].prompt == [99] # dummy foreground test owner+ permit.set()+ assert box.next_get.wait(2) # emit=True has been consumed by the caller+ obj._cancel_waiting()+ assert obj.waiting.qsize() == 1 and thread.is_alive() and not reply+ again = obj.waiting.queue[0][2][0]+ assert not again.emit.cancel_requested()+ obj._admit()+ again.take([2, 3])+ obj._iteration()+ thread.join(2)+ assert not thread.is_alive() and "stats" in reply and "error" not in reply+ assert obj.decoder.finished[-1] is again+ finally:+ permit.set()+ box.put(("error", Cancelled("test cleanup")))+ thread.join(2)+ ns["queue"] = queue+ checks.append(method + " retains normal stop/gate completion, not RequestCancelled")++ obj, fail = scheduler(), threading.Event()+ def active_poll():+ if fail.is_set():+ raise ValueError("active poll failed")+ return False+ thread, reply = ask(obj, active_poll)+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ fail.set()+ wait(stream.emit.cancel_requested)+ obj._cancel_waiting()+ assert thread.is_alive() and obj.decoder.live() == 1+ stream.take([2])+ obj._iteration()+ cancelled_reply(thread, reply, ValueError)+ assert obj.decoder.live() == 0 and obj.decoder.finished == [stream]+ checks.append("active poll failure propagates only after decoder finish")++ # Delivery failures latch an error, not a normal stop, and never let the+ # caller return before active decoder cleanup. Preserve the original error.+ failure = ValueError("delivery failed")+ deliveries = []+ def broken_emit(tokens):+ deliveries.append(tokens)+ raise failure+ obj = scheduler()+ thread, reply = ask(obj, lambda: False, emit_hook=broken_emit)+ box = obj.waiting.queue[0][2][1]+ try:+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ stream.take([2])+ wait(stream.emit.cancel_requested)+ obj._cancel_waiting()+ assert thread.is_alive() and not reply and obj.decoder.live() == 1+ assert stream.emit.cancel_error() is failure and not stream.done+ stream.take([2, 3])+ obj._iteration()+ cancelled_reply(thread, reply, ValueError)+ assert reply["error"] is failure and len(deliveries) == 1+ assert obj.decoder.finished == [stream] and obj.decoder.live() == 0 and not obj.boxes+ finally:+ box.put(("error", failure))+ thread.join(2)+ checks.append("delivery failure stops once and propagates after active decoder finish")++ # A delivery callback can be in flight while the scheduler yields/requeues+ # its stream. Test failure both before and after replay, including a+ # memory-held replay; queue removal remains owned by the scheduler.+ for method in ("_yield", "_requeue"):+ for timing in ("before", "after", "held"):+ permit, emitted, box = threading.Event(), threading.Event(), ObservedBox()+ failure = ValueError(method + " delivery " + timing)+ deliveries = []+ def delayed_failure(tokens):+ deliveries.append(tokens)+ emitted.set()+ assert permit.wait(2)+ raise failure+ obj = scheduler()+ ns["queue"] = SimpleNamespace(Queue=lambda: box, Empty=queue.Empty)+ thread, reply = ask(obj, lambda: False, background=True, emit_hook=delayed_failure)+ try:+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ stream.take([2])+ assert emitted.wait(2)+ if timing == "before":+ permit.set()+ assert box.next_get.wait(2)+ assert stream.emit.cancel_requested() and thread.is_alive() and not reply+ if method == "_yield":+ obj.max_streams = 1+ obj.waiting.put((Stream([99], 100), queue.Queue()))+ else:+ obj.decoder.streams.clear() # decoder freed the lane before reporting requeue+ obj.decoder.requeue = [stream]+ getattr(obj, method)()+ if method == "_yield":+ assert obj.waiting.get_nowait()[0].prompt == [99]+ again = obj.waiting.queue[0][2][0]+ assert again.emit is stream.emit and id(stream) not in obj.boxes+ if timing == "held":+ obj.decoder.room = False+ obj._admit()+ assert obj.held is not None and obj.held[0] is again+ if timing != "before":+ assert not again.emit.cancel_requested() and thread.is_alive() and not reply+ permit.set()+ assert box.next_get.wait(2)+ assert again.emit.cancel_requested() and again.emit.cancel_error() is failure+ assert thread.is_alive() and not reply+ obj._cancel_waiting()+ cancelled_reply(thread, reply, ValueError)+ assert reply["error"] is failure and len(deliveries) == 1+ assert obj.waiting.empty() and obj.held is None and not obj.boxes+ assert obj.decoder.admitted == [stream] and obj.decoder.live() == 0+ obj._cancel_waiting()+ assert box.empty() # one terminal reply only+ finally:+ permit.set()+ box.put(("error", failure))+ thread.join(2)+ ns["queue"] = queue+ checks.append(method + " delivery failure " + timing + " replay keeps cleanup/error ownership")++ # The decoder may already have finished while the caller is still inside+ # delivery. Its queued terminal reply must not turn that failure into stats.+ permit, emitted, box = threading.Event(), threading.Event(), ObservedBox()+ failure = ValueError("delivery failed after finish")+ def late_failure(tokens):+ emitted.set()+ assert permit.wait(2)+ raise failure+ obj = scheduler()+ ns["queue"] = SimpleNamespace(Queue=lambda: box, Empty=queue.Empty)+ thread, reply = ask(obj, lambda: False, emit_hook=late_failure)+ try:+ obj._admit()+ stream = next(iter(obj.decoder.streams.values()))+ stream.take([2])+ assert emitted.wait(2)+ stream.done = True+ obj._iteration()+ assert obj.decoder.finished == [stream] and obj.decoder.live() == 0 and not obj.boxes+ assert thread.is_alive() and not reply+ permit.set()+ cancelled_reply(thread, reply, ValueError)+ assert reply["error"] is failure and "stats" not in reply+ finally:+ permit.set()+ box.put(("error", failure))+ thread.join(2)+ ns["queue"] = queue+ checks.append("delivery failure after decoder finish is not swallowed by terminal stats")+ print(json.dumps({"status": "PASS", "tests": len(checks), "checks": checks, "device_calls": 0,+ "source_sha256": hashlib.sha256(source.replace("\r\n", "\n").encode()).hexdigest()}, indent=2))+++if __name__ == "__main__":+ main()