Repository navigation
Description
Summary
Disconnecting a streaming /v1/chat/completions client does not cancel its inference job. Jobs that are already running continue generating, and jobs whose clients disconnected while queued are still admitted later.
This became visible when a coding client timed out before the first SSE payload and retried: abandoned requests continued occupying the single inference lane after the conversation was stopped.
I reproduced the lifecycle defect using the repository's FakeEngine, with the real HTTP handler, ChatApp, and scheduler. No model weights are loaded by the reproduction, so the cancellation failure does not depend on a particular model's reasoning or output.
Environment and version scope
- Reproduced twice on TensorFold 0.3.3, commit
b08e0141cecd06408cfe16be56cecd9b65342dac, using an editable installation. - Apple M5 Max, 64 GB unified memory; macOS 27.2 (26B5091g).
- Python 3.12.11, MLX 0.31.2, mlx-lm 0.31.3.
- Original live setup:
orcarouter/Qwen3.8-27B-Uncensored-MLX,z-lab/Qwen3.8-27B-DFlash2, one lane, context 131072, output limit 32768, thinking budget 8192. - Client: Qoder CN, with a 60-second timeout before the first stream payload.
Later versions were inspected, not reproduced: the cancellation path is unchanged in 0.3.4. I also checked current main, 0.3.4.1 at bb4b4a35863af562fc4ccb2586300d8f94b5d6de: the blocking chunk wait, callback path without job cleanup, and HTTP BrokenPipeError handling still appear unchanged. I have not run this reproduction on 0.3.4 or 0.3.4.1.
Expected behavior
- A disconnected client cancels its queued job, which should never start inference.
- A disconnected client cancels active generation and releases its resources at the next safe engine boundary.
- Cancellation during a long prefill is checked between chunks, without requiring interruption of an in-flight GPU kernel.
Actual behavior and reproduction results
| Case | Observed result |
|---|---|
| Control with a live consumer | 40 tokens generated and the chat request completed normally. |
Streaming callback raises BrokenPipeError |
The caller exits while one job is active; the scheduler still generates all 40 tokens. The chat completion counter stays at 0. |
| Three real HTTP clients disconnect during a blocked prefill | One job remains in prefill and two remain queued. After releasing the artificial prefill barrier, the two abandoned queued jobs still start; all three jobs generate 40 tokens each. The chat completion counter stays at 0. |
The prefill barrier only makes the ordering deterministic. It does not replace or patch HTTP, chat, or scheduler cancellation behavior.
Minimal reproduction
Use a checkout of the reproduced commit with TensorFold installed in its normal virtual environment. Save the script below as repro_cancel.py in the repository root, activate that environment, and run:
python repro_cancel.pyIt binds only to a random localhost port and uses a harmless greeting prompt. It creates its own local HTTP server; an existing model service is not needed.
Reproduction script
"""Audit cancellation using the real HTTP/chat/scheduler and the repo's list-only fake engine."""
from __future__ import annotations
from http.server import ThreadingHTTPServer
from pathlib import Path
import json
import socket
import sys
import threading
import time
ROOT = Path.cwd() # Run from the TensorFold repository root.
sys.path.insert(0, str(ROOT))
from tensorfold.server.app import ChatApp
from tensorfold.server.http import make_handler
from tests.lane_fakes import FakeEngine
class Tokenizer:
eos_token_ids = {-1}
def encode(self, text):
return [ord(c) - 0x4E00 if 0x4E00 <= ord(c) < 0x4F00 else 2 + ord(c) % 40 for c in text]
def decode(self, ids):
return ''.join(chr(0x4E00 + int(t)) for t in ids)
def apply_chat_template(self, messages, **kwargs):
ids = []
for m in messages:
ids.extend(self.encode(str(m.get('content', ''))))
ids.append(1)
if kwargs.get('add_generation_prompt', True):
ids.extend([3, 4])
return ids
class AuditEngine(FakeEngine):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.entered = threading.Event()
self.release = threading.Event()
self.release.set()
self.audit_streams = []
def add_stream(self, stream, **kwargs):
self.audit_streams.append(stream)
return super().add_stream(stream, **kwargs)
def prefill(self, stream, **kwargs):
self.entered.set()
if not self.release.wait(5):
raise RuntimeError('audit prefill barrier expired')
return super().prefill(stream, **kwargs)
def step(self):
time.sleep(0.004)
return super().step()
def app():
return ChatApp(None, Tokenizer(), served_name='cancellation-audit', lanes=1,
engine_factory=AuditEngine, use_proposer=False, checkpoint_slots=0,
default_max_tokens=40, enable_thinking=False)
def until(predicate, timeout=5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.005)
raise AssertionError('audit condition did not complete')
messages = [{'role': 'user', 'content': 'Write a hello-world greeting.'}]
results = {}
# Control: exercise the exact fake engine/chat path with a live consumer.
a = app()
try:
reply = a.chat(messages, max_tokens=40, temperature=0, on_delta=lambda delta: None)
results['control'] = {'completion_tokens': reply['completion_tokens'],
'scheduler_completed': a.scheduler.completed}
assert reply['completion_tokens'] == 40
finally:
a.close()
# The real chat callback fails as it does when the HTTP socket reports BrokenPipe.
a = app()
try:
def disconnected(delta):
raise BrokenPipeError('controlled local client disconnect')
raised = False
try:
a.chat(messages, max_tokens=40, temperature=0, on_delta=disconnected)
except BrokenPipeError:
raised = True
active_when_consumer_exited = a.scheduler.active
until(lambda: a.scheduler.completed == 1)
committed = len(a.engine.audit_streams[0].emitted)
results['callback_disconnect'] = {
'callback_raised_broken_pipe': raised,
'active_jobs_when_consumer_exited': active_when_consumer_exited,
'backend_completed_after_disconnect': a.scheduler.completed,
'committed_tokens': committed,
'http_chat_requests_completed': a.requests_completed,
}
assert raised and active_when_consumer_exited == 1 and committed == 40
assert a.requests_completed == 0
finally:
a.close()
# Real local sockets disconnect during blocked prefill, including queued retries.
a = app()
a.engine.release.clear()
server = ThreadingHTTPServer(('127.0.0.1', 0), make_handler(a))
server.daemon_threads = True
t = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': 0.01}, daemon=True)
t.start()
clients = []
headers = []
try:
for i in range(3):
body = json.dumps({'model': 'cancellation-audit', 'messages': messages,
'max_tokens': 40, 'temperature': 0, 'stream': True,
'tools': [{'type': 'function', 'function': {'name': 'echo',
'parameters': {'type': 'object', 'properties': {}}}}]}).encode()
s = socket.create_connection(server.server_address, timeout=2)
clients.append(s)
request = (f'POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\n'
f'Content-Type: application/json\r\nContent-Length: {len(body)}\r\n'
'Connection: close\r\n\r\n').encode() + body
s.sendall(request)
data = b''
while b'\r\n\r\n' not in data:
data += s.recv(4096)
headers.append(data.split(b'\r\n', 1)[0].decode())
assert a.engine.entered.wait(2)
until(lambda: a.scheduler._queue.qsize() == 2)
for s in clients:
s.shutdown(socket.SHUT_RDWR)
s.close()
time.sleep(0.05)
queued_after_disconnect = a.scheduler._queue.qsize()
starting_after_disconnect = a.scheduler._starting is not None
starts_at_disconnect = a.scheduler.starts
a.engine.release.set()
until(lambda: a.scheduler.completed == 3)
committed = [len(s.emitted) for s in a.engine.audit_streams]
results['http_disconnect_during_prefill'] = {
'http_status_lines': headers,
'queued_jobs_after_all_clients_disconnected': queued_after_disconnect,
'prefill_still_starting_after_disconnect': starting_after_disconnect,
'backend_jobs_started_total': a.scheduler.starts,
'queued_jobs_started_after_disconnect': a.scheduler.starts - starts_at_disconnect,
'backend_jobs_completed': a.scheduler.completed,
'committed_tokens_per_job': committed,
'http_chat_requests_completed': a.requests_completed,
}
assert queued_after_disconnect == 2 and starting_after_disconnect
assert committed == [40, 40, 40] and a.requests_completed == 0
finally:
a.engine.release.set()
for s in clients:
s.close()
server.shutdown()
server.server_close()
a.close()
t.join(timeout=1)
output = Path(__file__).with_name('reproduction-results.json')
output.write_text(json.dumps(results, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(results, ensure_ascii=False, indent=2))Recorded output
{
"control": {
"completion_tokens": 40,
"scheduler_completed": 1
},
"callback_disconnect": {
"callback_raised_broken_pipe": true,
"active_jobs_when_consumer_exited": 1,
"backend_completed_after_disconnect": 1,
"committed_tokens": 40,
"http_chat_requests_completed": 0
},
"http_disconnect_during_prefill": {
"http_status_lines": [
"HTTP/1.1 200 OK",
"HTTP/1.1 200 OK",
"HTTP/1.1 200 OK"
],
"queued_jobs_after_all_clients_disconnected": 2,
"prefill_still_starting_after_disconnect": true,
"backend_jobs_started_total": 3,
"queued_jobs_started_after_disconnect": 2,
"backend_jobs_completed": 3,
"committed_tokens_per_job": [
40,
40,
40
],
"http_chat_requests_completed": 0
}
}Code paths involved
Pointers below are pinned to the reproduced 0.3.3 commit:
ChatApp.chatcleanup: thefinallyblock releases the preparing counter, without canceling the submitted job.- Streaming consumer:
job.chunks.get()blocks without a disconnect/cancellation check; anon_deltaexception exits without terminating the inference job. - HTTP exception handler:
BrokenPipeErroris swallowed, with no scheduler cancellation. - Queue admission: jobs are admitted without checking whether their client has disconnected.
- Existing
finish_job: it only marks an existing stream finished; a queued job has no stream yet, so calling this alone would not cancel queued work. - Prefill loop: there is no cancellation/stop check between chunks.
Sanitized live observations and limits
In the original incident, response headers arrived with HTTP 200 within a few milliseconds, but the client received no SSE data events. It logged nine consecutive first-payload timeouts across ten request attempts, then the user canceled the turn. A later attempt was also canceled with zero SSE events. The inference process kept working after the conversation had stopped.
A thread snapshot showed six request handlers blocked in job.chunks.get() while the inference thread was in _lane_prefill_tokens -> tree_forward. Several closed client sockets were still retained by the server process. Health/model listing endpoints continued to respond.
The evidence confirms cancellation is missing and client retries can accumulate abandoned work. It does not establish why the first live request exceeded 60 seconds, nor prove a GPU deadlock. The logs lack per-job start times and client/server request correlation. The reproduction above isolates cancellation from those unknowns.
Would a per-job cancellation signal, disconnect monitoring while waiting for chunks, skipping canceled queue entries, and cancellation checks between prefill chunks be an appropriate fix? Heartbeats alone would not stop jobs after a manual client disconnect.
Activity
ashhart commentedon Sep 27, 2026
Thanks @samwang0041-star for the reproduction. This is fixed for 0.3.5, which ships tonight: the Mac server cancels a request when its client disconnects, whether the request is queued, prefilling or decoding. This issue closes when the release is published.