Interleave two streams and cancel one cleanly
Drive two independent token streams through one manager, acknowledge a token, cancel a session, and check that cleanup releases it.
Streaming is a per-request state machine, not a property of a generator. Each request needs its own token queue, its own buffer accounting, and its own cancellation state. A manager that mixes them produces interleaved text from two users, or keeps generating after the client has gone.
This example creates two sessions, takes the first token from each, cancels the first, and cleans it up. The output shows that each stream produced its own first token, the cancelled session was removed, and one active session remains. The buffer limit is two, so the demo also exercises the backpressure check without filling it. The page does not claim HTTP streaming or server-sent events; it tests the in-process contract that such a transport would use.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch27/streaming.py --jsonPython 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.
Implementation
StreamManager keys sessions by a UUID, returns one token at a time, and refuses
to return another when the per-session buffer is full. ack decrements the
buffer, cancel marks the session, and cleanup removes it.
class StreamManager:
def __init__(self, max_buffer: int = 4) -> None:
if max_buffer < 1:
raise ValueError("max_buffer must be positive")
self.max_buffer = max_buffer
self.sessions: Dict[str, StreamSession] = {}
def create(self, tokens: List[str]) -> str:
rid = str(uuid.uuid4())
self.sessions[rid] = StreamSession(request_id=rid, tokens=list(tokens))
return rid
def next_token(self, rid: str) -> Optional[str]:
session = self.sessions.get(rid)
if session is None or session.cancelled:
return None
if not session.tokens:
return None
if session.buffer_size >= self.max_buffer:
return None # backpressure
token = session.tokens.pop(0)
session.buffer_size += 1
return token
def ack(self, rid: str) -> None:
session = self.sessions.get(rid)
if session is not None and session.buffer_size > 0:
session.buffer_size -= 1
def cancel(self, rid: str) -> bool:
session = self.sessions.get(rid)
if session is None:
return False
session.cancelled = True
return True
def cleanup(self, rid: str) -> bool:
return self.sessions.pop(rid, None) is not None
def active_count(self) -> int:
return sum(1 for s in self.sessions.values() if not s.cancelled)Expected outcome
Observed with the command above (exit 0):
{
"rid1_first": "a",
"rid2_first": "x",
"cancelled": true,
"cleaned": true,
"active_count": 1
}The first stream returned a from ["a", "b", "c"]; the second returned x from
["x", "y"]. The first session was cancelled and then removed, so
cancelled: true here means the session is absent, not merely flagged. One
session remained active. The request ids are UUIDs and are not quoted because
they change on every run.
Mechanism and limitations
Documented: the manager rejects a non-positive buffer, keeps sessions
separate, returns None for an unknown, cancelled or exhausted session, and
returns None when the buffer is full. ack releases one buffered token;
cancel marks the session; cleanup removes it; active_count counts
non-cancelled sessions. The tests check create/next, backpressure, ack, cancel,
cleanup, the demo and JSON serialisation.
Observed: the command exited 0 with the two first tokens and the cleanup
state above. The targeted tests.test_ch27_streaming is part of the canonical
suite; no independent test count is claimed here.
Not shown: HTTP streaming, SSE framing, client disconnect detection, ordering across threads, fair scheduling between sessions, or a real tokeniser. The demo takes one token from each stream in a fixed order; it does not prove that two concurrent transports would interleave correctly. The UUID is an identifier, not a security token.
Challenge this result
Create one session with max_buffer=1, take a token, and try to take another
before acknowledging. The second call should return None. Then acknowledge and
verify the next token is available. Finally, cancel a session and call
next_token before cleanup; it should return None while the session still
exists. Explain why cancellation and cleanup must be separate operations, and
what a server must do if the client disappears before either is called.
Source and verification
Canonical source:
examples/ch27/streaming.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch27_streaming.py
.
Chapter: Concurrent Requests and Streaming
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15; it
uses an in-process manager, not an HTTP server.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.