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

[Bug]: Standalone gateway records a client-cancelled stream as `ERROR` instead of `UNSET`

Open Sakshitapkir03 opened this issue 1 week ago • 2 comments

Affected area

Rust core runtime

Current behavior

When a client closes a streamed /v1/messages response early through the standalone gateway (nemo-relay --bind), the LLM end event is recorded as otel.status_code: ERROR with otel.status_description: "stream dropped before clean completion". The same stream read to the end is recorded as OK:

Same slow stream Relay records
Client reads to the end OK, finish reason complete
Client closes after 3 s (curl --max-time 3) ERROR, stream dropped before clean completion

Relay's documentation treats a client cancellation as neutral. docs/daemon/reference.mdx: "When a client closes a response before the HTTP body ends, Relay records daemon_worker_observation.terminal as cancelled. The LLM span keeps the OpenTelemetry status UNSET unless Relay also detects an error. Cancellation alone does not mean the provider failed." docs/integrate-into-frameworks/wrap-llm-calls.mdx: "For a neutral outcome, such as a client cancelling a response, set otel.status_code to "UNSET"."

#1586 implemented this for the daemon worker (crates/cli/src/daemon/worker/managed.rs). On the standalone gateway, a managed stream that is dropped before it completes ends through LlmStreamWrapper::finish in crates/runtime/src/stream.rs, which records ERROR for any drop, so a client cancellation is recorded the same way as a failure.

Related: #620 records cancelled Python scopes (asyncio.CancelledError) as errors, a different case; #1788 covers session accounting for cancelled non-streaming gateway calls.

Expected behavior

A stream that ends because the client closed it is recorded as UNSET, as on the daemon path, while provider and body failures remain ERROR.

Steps to reproduce

  1. Mock provider that streams a normal response, two seconds per event (repro_slow.py):
    import json
    import time
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    
    EVENTS = [
        ("message_start", {"type": "message_start", "message": {
            "id": "msg_1", "type": "message", "role": "assistant", "model": "mock",
            "content": [], "stop_reason": None, "stop_sequence": None,
            "usage": {"input_tokens": 10, "output_tokens": 1}}}),
        ("content_block_start", {"type": "content_block_start", "index": 0,
                                 "content_block": {"type": "text", "text": ""}}),
        ("content_block_delta", {"type": "content_block_delta", "index": 0,
                                 "delta": {"type": "text_delta", "text": "Hello"}}),
        ("content_block_stop", {"type": "content_block_stop", "index": 0}),
        ("message_delta", {"type": "message_delta",
                           "delta": {"stop_reason": "end_turn", "stop_sequence": None},
                           "usage": {"output_tokens": 5}}),
        ("message_stop", {"type": "message_stop"}),
    ]
    
    class H(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"
        def do_POST(self):
            self.rfile.read(int(self.headers.get("Content-Length", "0")))
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Transfer-Encoding", "chunked")
            self.end_headers()
            try:
                for name, data in EVENTS:
                    time.sleep(2)
                    frame = f"event: {name}\ndata: {json.dumps(data)}\n\n".encode()
                    self.wfile.write(f"{len(frame):x}\r\n".encode() + frame + b"\r\n")
                    self.wfile.flush()
                self.wfile.write(b"0\r\n\r\n")
            except (BrokenPipeError, ConnectionResetError):
                pass
            self.close_connection = True
    
    ThreadingHTTPServer(("127.0.0.1", 8090), H).serve_forever()
    
  2. Configure the gateway as in #1781: anthropic_base_url = "http://127.0.0.1:8090", and the observability component with an ATOF file sink writing to logs/events.jsonl.
  3. In a directory containing an empty logs/ folder, run python3 repro_slow.py, start nemo-relay --bind 127.0.0.1:4040, and cancel a streamed request after 3 seconds:
    curl -sN --max-time 3 http://127.0.0.1:4040/v1/messages \
      -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -H 'x-api-key: test' \
      -d '{"model":"mock","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}'
    
  4. After about 12 seconds, the anthropic.messages end event has otel.status_code: ERROR and otel.status_description: "stream dropped before clean completion". The same request without --max-time is recorded as OK.

Environment

  • NeMo Relay version or commit: main at 26c3f998e, debug build
  • OS and architecture: macOS 27.2.1, Apple Silicon (arm64)
  • Rust version: 1.96.1 (pinned by rust-toolchain.toml)
  • Python version: 3.15.0 (for the mock provider)
  • Node.js version: N/A
  • Go version: N/A
  • Install/build command: cargo build -p nemo-relay-cli

Impact

Every streamed call that a client stops early through the standalone gateway (for example a user cancelling a response in a coding agent, or an SDK timeout) is counted as a failed LLM call, which inflates error rates and can trigger alerts although the provider did not fail. Not checked: the status of cancelled non-streaming calls, and the daemon worker path, whose behavior I take from #1586 and the docs above.

Approach for discussion: distinguish a downstream cancellation from other drops on the gateway's managed stream, for example by having the gateway mark the call as cancelled when the client disconnects, as the daemon worker does, and keep ERROR for provider and body failures. Which direction would you prefer?

I'd like to work on this and will open a PR once we agree on the approach.

Sakshitapkir03 avatar Nov 23 '26 15:11 Sakshitapkir03

@Sakshitapkir03 , thanks for filing! we have some time constraints today, so I'll handle this one.

greysonlalonde avatar Nov 23 '26 17:11 greysonlalonde

@greysonlalonde Thank you for the quick fix!

Sakshitapkir03 avatar Nov 23 '26 20:11 Sakshitapkir03