Skip to content

fix: terminate SSE stream so clients stop hanging (Cline stuck on 'thinking') - #2

Open
y83906467 wants to merge 1 commit into
baimocn:mainfrom
y83906467:fix/sse-stream-never-terminates
Open

y83906467 wants to merge 1 commit into
baimocn:mainfrom
y83906467:fix/sse-stream-never-terminates

Conversation

@y83906467

Copy link
Copy Markdown

Problem

The proxy's streaming path never signals end-of-stream. Any OpenAI-compatible
client (Cline, the openai SDK, Cursor, …) blocks forever and shows a permanent
"thinking" state, even though the request completes on the upstream side and
is logged with HTTP 200.

This affects every client using stream: true — it is not client-specific.

Root cause

Three independent defects in the streaming path:

1. server.py — SSE events are not delimited

for line in gateway.chat_completions_stream(body):
    self.wfile.write(line + b"\n")   # single \n

SSE requires a blank line to terminate an event. Without it, clients never
dispatch a chunk — the SDK iterator yields zero events.

2. gateway.py — read loop never terminates

while True:
    chunk = resp.read(4096)
    if not chunk:
        break

The upstream gateway sends data: [DONE] but does not close the connection,
so read() blocks indefinitely and the generator never finishes.

3. server.py — keep-alive on an unframed response

self.send_header("Connection", "keep-alive")

The response has neither Content-Length nor chunked framing, so the client's
only end-of-body signal is connection close — yet keep-alive tells it to keep
waiting.

Reproduction (clean checkout of d894097, unmodified)

import urllib.request, json, time
body = json.dumps({"model": "deepseek-ai/DeepSeek-V4-Flash",
                   "messages": [{"role": "user", "content": "hi"}],
                   "stream": True}).encode()
req = urllib.request.Request("http://127.0.0.1:8899/v1/chat/completions",
                             data=body, headers={"Content-Type": "application/json"})
r = urllib.request.urlopen(req, timeout=25)
while True:
    c = r.read(4096)
    if not c:
        break

Observed on the original code:

[raw] READ BLOCKED/TIMEOUT after 26.3s -> TimeoutError
[raw] Connection header='keep-alive'
[raw] has SSE blank-line separator (\n\n)?  False

Fix

# server.py — delimit each event with a blank line
for line in gateway.chat_completions_stream(body):
    self.wfile.write(line + b"\n\n")
    self.wfile.flush()
# server.py — do not advertise keep-alive for an unframed stream
self.send_header("Connection", "close")
self.close_connection = True
# gateway.py — stop as soon as [DONE] is seen
done = False
while not done:
    chunk = resp.read(4096)
    if not chunk:
        break
    buffer += chunk
    while b"\n" in buffer:
        line, buffer = buffer.split(b"\n", 1)
        line = line.strip()
        if line:
            yield line
            if b"[DONE]" in line:
                done = True
                break
if not done and buffer.strip():
    yield buffer.strip()

Verification (after the fix)

[raw] EOF at 1.74s   (previously: blocked >26s)
openai SDK: chunks=27  content='Hi!'  reason_len=84  elapsed=2.37s

Both raw-stream read and the openai SDK streaming iterator now terminate
correctly and deliver content.

The proxy's streaming path never signalled end-of-stream, so any
OpenAI-compatible client (Cline, openai SDK, Cline/Cursor) blocked
forever and showed a permanent "thinking" state.

Three defects in the original code:

1. server.py wrote each SSE line with a single "\n". SSE requires a
   blank line to delimit an event, so clients dispatched zero chunks.
2. gateway.py looped on read() until EOF, but the upstream gateway does
   not close the connection after sending `data: [DONE]`, so the read
   blocked indefinitely.
3. server.py advertised `Connection: keep-alive` for a response that has
   neither Content-Length nor chunked framing, leaving clients no way to
   detect the end of the body.

Fixes:

- Write `line + "\n\n"` so events are properly delimited.
- Stop forwarding and close the generator as soon as `[DONE]` is seen.
- Send `Connection: close` and set close_connection = True.

Verified against a clean checkout of d894097:

  before: read blocked / timed out after 26.3s, header keep-alive,
          no blank-line separator
  after:  EOF in ~1.7s; openai SDK yields 27 chunks, content "Hi!"

Co-Authored-By: AtomCode (deepseek-flash) <noreply@atomgit.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant