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

[Bug]: Anthropic mid-stream `error` events are recorded as successful (`OK`) LLM calls

Open Sakshitapkir03 opened this issue 2 weeks ago • 2 comments

Affected area

Rust core runtime

Current behavior

When an Anthropic Messages stream sends an error event after streaming begins, the gateway forwards the event to the client, but the LLM end event is recorded as otel.status_code: OK, with no status description and the partial text as the message. Anthropic documents these events: during high usage, a stream may carry overloaded_error, the in-stream equivalent of HTTP 529.

The other failure paths I tried are recorded as ERROR:

Failure Client receives Relay records
Overload, non-streaming: HTTP 529 HTTP 529, overloaded_error ERROR
Provider drops the connection after partial streamed output partial text, then Relay's event: error (#1652) ERROR
Overload, streaming: provider sends event: error (overloaded_error) after partial output partial text, then the provider's event: error OK, no description

AnthropicMessagesStreamingState::observe in crates/codecs/src/anthropic.rs treats error as an unknown event type ("Unknown types are ignored rather than erroring so a future Anthropic event addition does not break observability"), and the call is not marked failed elsewhere on this path. The OpenAI Responses codec, by contrast, reports a stream that ends without its terminal event (missing_terminal_response).

#1652 surfaces connection failures to clients, and #1586 keeps ERROR for provider HTTP failures and body-read failures; neither covers a provider-reported in-stream error.

Expected behavior

A stream that ends with an Anthropic error event is recorded as ERROR, with the provider's error type and message available, while the provider's error event still reaches the client unchanged so SDKs see overloaded_error for their retry handling. Unknown event types remain ignored.

Steps to reproduce

  1. Mock provider that streams three events, then an error event (repro_mock.py):
    import json
    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": "Partial"}}),
        ("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}),
    ]
    
    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()
            for name, data in EVENTS:
                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.write(b"0\r\n\r\n")
            self.close_connection = True
    
    ThreadingHTTPServer(("127.0.0.1", 8090), H).serve_forever()
    
  2. Configure the gateway ($XDG_CONFIG_HOME/nemo-relay/):
    # config.toml
    [upstream]
    anthropic_base_url = "http://127.0.0.1:8090"
    
    # plugins.toml
    version = 1
    
    [[components]]
    kind = "observability"
    enabled = true
    
    [components.config]
    version = 4
    
    [components.config.atof]
    enabled = true
    
    [[components.config.atof.sinks]]
    type = "file"
    output_directory = "logs"
    filename = "events.jsonl"
    mode = "overwrite"
    
  3. In a directory containing an empty logs/ folder, run python3 repro_mock.py, start nemo-relay --bind 127.0.0.1:4040, and send a streamed request:
    curl -sN 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. The client receives the error event. In logs/events.jsonl, the anthropic.messages end event has otel.status_code: OK, no otel.status_description, and annotated_response.message: "Partial".

Environment

  • NeMo Relay version or commit: main at 23f05206, 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
  • Node.js version: N/A
  • Go version: N/A
  • Install/build command: cargo build -p nemo-relay-cli

Impact

Telemetry counts Anthropic streams that fail mid-response as successful calls with partial output, so error rates and alerts miss overloads and other in-stream failures, which Anthropic notes occur during periods of high usage. Not checked: whether other providers' in-stream error formats (for example Chat Completions data: {"error": ...}) behave the same way.

Approach for discussion: recognize error in the Anthropic streaming state, and record the failure at finalization. From the module docs in crates/runtime/src/stream.rs ("raw chunk (Json) -> collector(chunk) -> Ok(()) -> yield chunk"), returning an error from the collector would end the stream before the provider's error event is yielded, replacing overloaded_error with Relay's generic error for the client. Which mechanism would you prefer for a codec to mark a completed-but-failed stream?

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

Sakshitapkir03 avatar Nov 20 '26 16:11 Sakshitapkir03

@Sakshitapkir03 go for it! please target release/0.11.

greysonlalonde avatar Nov 20 '26 16:11 greysonlalonde

Thanks @greysonlalonde! Opened #1782 against release/0.11.

Sakshitapkir03 avatar Nov 20 '26 21:11 Sakshitapkir03