NeMo-Relay icon indicating copy to clipboard operation
NeMo-Relay copied to clipboard

[Bug]: managed streaming turns a mid-stream upstream failure into a clean, successful-looking response

Open ptimizeroracle opened this issue 1 month ago • 1 comments

Affected area

Rust core runtime

Current behavior

when the provider drops the connection after the first events, a client talking to the gateway gets http 200 and a cleanly terminated body with the text so far. openai-python and the anthropic sdk raise nothing: finish_reason=None / stop_reason=None, partial text. the same client talking to the provider directly gets APIConnectionError / RemoteProtocolError. the gateway logs upstream_failed, so relay knows, the caller doesn't.

path openai-python anthropic sdk raw httpx
direct APIConnectionError RemoteProtocolError RemoteProtocolError (incomplete chunked read)
relay no exception, partial text, finish_reason None no exception, partial text, stop_reason None 200, clean end, no [DONE]

with a complete stream both paths return the full text with stop / end_turn.

cause: client_sse_body (crates/cli/src/gateway/mod.rs) returns on Err, so the body ends with a valid terminator. #1536 made this deliberate to keep a body failure from triggering worker recovery, and raw passthrough_streaming still propagates the error. #1050 is the same symptom in the field (truncated body, finish_reason: null, looked flaky to pi) from a different cause.

Expected behavior

the caller can tell the response failed. one way that keeps #1536's goal: before ending the body, emit the protocol's in-band error (event: error for anthropic messages, data: {"error": ...} for chat completions, error for responses). both sdks raise on those (_streaming.py in each), and the stream still ends cleanly on the wire. happy to send a pr if that direction works for you.

Steps to reproduce

  1. PORT=18080 MODE=cut python mock_provider.py (sends 3 events, then aborts the tcp connection; MODE=complete is the control)
  2. NEMO_RELAY_OPENAI_BASE_URL=http://127.0.0.1:18080/v1 NEMO_RELAY_ANTHROPIC_BASE_URL=http://127.0.0.1:18080 nemo-relay gateway start
  3. python client.py http://127.0.0.1:4040/v1 http://127.0.0.1:4040 (through relay) and python client.py http://127.0.0.1:18080/v1 http://127.0.0.1:18080 (direct)
mock_provider.py
"""Loopback mock provider that streams a few SSE events, then drops the connection.

MODE env var:
  cut      -> send 3 content events, then close the socket mid-body (no chunked terminator,
              no [DONE] / message_stop). This is what a provider crash or LB reset looks like.
  complete -> send the full stream, properly terminated (control).
Serves POST /v1/chat/completions (OpenAI chat) and POST /v1/messages (Anthropic).
"""

import asyncio
import json
import os
import sys

PORT = int(os.environ.get("PORT", "18080"))
MODE = os.environ.get("MODE", "cut")


def chunk(data: bytes) -> bytes:
    return f"{len(data):x}\r\n".encode() + data + b"\r\n"


def sse(obj, event=None) -> bytes:
    head = f"event: {event}\n" if event else ""
    return (head + "data: " + json.dumps(obj) + "\n\n").encode()


def openai_events():
    base = {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": "mock"}
    yield sse({**base, "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}}]})
    for word in ["one ", "two ", "three "]:
        yield sse({**base, "choices": [{"index": 0, "delta": {"content": word}}]})
    yield "CUT"
    yield sse({**base, "choices": [{"index": 0, "delta": {"content": "four"}, "finish_reason": None}]})
    yield sse({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]})
    yield b"data: [DONE]\n\n"


def anthropic_events():
    yield sse({"type": "message_start", "message": {"id": "m1", "type": "message", "role": "assistant",
               "model": "mock", "content": [], "stop_reason": None, "stop_sequence": None,
               "usage": {"input_tokens": 5, "output_tokens": 1}}}, "message_start")
    yield sse({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
              "content_block_start")
    for word in ["one ", "two ", "three "]:
        yield sse({"type": "content_block_delta", "index": 0,
                   "delta": {"type": "text_delta", "text": word}}, "content_block_delta")
    yield "CUT"
    yield sse({"type": "content_block_delta", "index": 0,
               "delta": {"type": "text_delta", "text": "four"}}, "content_block_delta")
    yield sse({"type": "content_block_stop", "index": 0}, "content_block_stop")
    yield sse({"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None},
               "usage": {"output_tokens": 4}}, "message_delta")
    yield sse({"type": "message_stop"}, "message_stop")


async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    try:
        request_line = (await reader.readline()).decode()
        headers = {}
        while True:
            line = (await reader.readline()).decode()
            if line in ("\r\n", "\n", ""):
                break
            k, _, v = line.partition(":")
            headers[k.strip().lower()] = v.strip()
        length = int(headers.get("content-length", "0"))
        body = await reader.readexactly(length) if length else b""
        path = request_line.split()[1] if len(request_line.split()) > 1 else "?"
        print(f"[mock] {request_line.strip()} body={len(body)}B", file=sys.stderr, flush=True)
        events = anthropic_events() if path.endswith("/messages") else openai_events()
        writer.write(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n"
                     b"transfer-encoding: chunked\r\nconnection: close\r\n\r\n")
        await writer.drain()
        for ev in events:
            if ev == "CUT":
                if MODE == "cut":
                    await asyncio.sleep(0.05)
                    print("[mock] cutting connection mid-stream", file=sys.stderr, flush=True)
                    writer.transport.abort()  # RST-like close, no terminating chunk
                    return
                continue
            writer.write(chunk(ev))
            await writer.drain()
            await asyncio.sleep(0.02)
        writer.write(b"0\r\n\r\n")
        await writer.drain()
        writer.close()
    except Exception as e:  # noqa: BLE001
        print(f"[mock] error {e!r}", file=sys.stderr, flush=True)


async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", PORT)
    print(f"[mock] listening on 127.0.0.1:{PORT} mode={MODE}", file=sys.stderr, flush=True)
    async with server:
        await server.serve_forever()


asyncio.run(main())
client.py
"""Stream one chat completion and one Anthropic message; report what the client sees.

Usage: client.py OPENAI_BASE ANTHROPIC_BASE
Prints, per SDK: text received, finish/stop reason, and whether an exception was raised.
"""

import sys

import anthropic
import httpx
import openai

openai_base, anthropic_base = sys.argv[1], sys.argv[2]


def run_openai():
    client = openai.OpenAI(base_url=openai_base, api_key="sk-mock", max_retries=0)
    text, finish = "", None
    try:
        stream = client.chat.completions.create(
            model="mock", messages=[{"role": "user", "content": "count"}], stream=True)
        for c in stream:
            if c.choices:
                text += c.choices[0].delta.content or ""
                finish = c.choices[0].finish_reason or finish
        print(f"openai    : NO EXCEPTION text={text!r} finish_reason={finish!r}")
    except Exception as e:  # noqa: BLE001
        print(f"openai    : EXCEPTION {type(e).__name__}: {str(e)[:120]} (text so far {text!r})")


def run_anthropic():
    client = anthropic.Anthropic(base_url=anthropic_base, api_key="sk-ant-mock", max_retries=0)
    text = ""
    try:
        with client.messages.stream(model="mock", max_tokens=16,
                                    messages=[{"role": "user", "content": "count"}]) as s:
            for t in s.text_stream:
                text += t
            msg = s.get_final_message()
        print(f"anthropic : NO EXCEPTION text={text!r} stop_reason={msg.stop_reason!r}")
    except Exception as e:  # noqa: BLE001
        print(f"anthropic : EXCEPTION {type(e).__name__}: {str(e)[:120]} (text so far {text!r})")


def run_raw():
    try:
        with httpx.stream("POST", openai_base.rstrip("/") + "/chat/completions",
                          json={"model": "mock", "stream": True,
                                "messages": [{"role": "user", "content": "x"}]},
                          headers={"authorization": "Bearer sk-mock"}, timeout=10) as r:
            body = b"".join(r.iter_bytes())
        print(f"raw httpx : status={r.status_code} body_ok bytes={len(body)} has_DONE={b'[DONE]' in body}")
    except Exception as e:  # noqa: BLE001
        print(f"raw httpx : EXCEPTION {type(e).__name__}: {str(e)[:120]}")


run_openai()
run_anthropic()
run_raw()

Environment

  • NeMo Relay version or commit: main be8845b, cargo build -p nemo-relay-cli --bin nemo-relay (debug)
  • OS and architecture: macOS, arm64
  • Rust version: 1.96.1
  • Python version: 3.12 (openai 3.45.0, anthropic 2.5.0)
  • Install/build command: as above, no plugins configured

Impact

agents keep a truncated answer or tool call as if it were complete, or retry turns that look "terminated" for no visible reason (#1050). the gateway's own logs show the failure, the agent never sees it.

(ai-assisted, checked by me)

ptimizeroracle avatar Nov 04 '26 21:11 ptimizeroracle

Closed by #1652

willkill07 avatar Nov 05 '26 03:11 willkill07