Anthropic clients never see a failed turn: anthropic_stop_reason maps finish=="error" to end_turn
Summary
anthropic_stop_reason maps every finish state except tool_calls and length to end_turn — including "error". A turn that failed server-side is therefore indistinguishable from a normal completion on the Anthropic API, and the error text is not surfaced anywhere in the response body or stream.
Current upstream code (ds4_server.c @ 0aaea5a):
static const char *anthropic_stop_reason(const char *finish) { // :9038
if (finish && !strcmp(finish, "tool_calls")) return "tool_use";
if (finish && !strcmp(finish, "length")) return "max_tokens";
return "end_turn";
}
Both Anthropic surfaces route through it: the non-streaming final message (anthropic_final_response, :9113, stop_reason at :9123) and the streaming terminator (anthropic_sse_finish_live → message_delta's stop_reason at :9828).
The other two APIs are honest about the same event:
- OpenAI-compatible:
finish_reason: "error"on the 200 body (the value is passed through verbatim). - Responses:
finish == "error"→status: "failed"witherror.code = "server_error"(:8636, :8676).
And the SSE error event the server already has (sse_error_event, :7005, which emits a proper type: "error" / api_error) is called from exactly one place — send_prefill_failure_response (:12759). A failure raised after decoding (engine fault during generation, failed session append, unterminated tool call, stream-write failure) never reaches it on the Anthropic path.
Observed in production
While investigating the case that became #1163: the model opened a tool envelope and never closed it, the generator set finish = "error", and the Anthropic client received the raw truncated markup as ordinary assistant text with stop_reason: "end_turn". Nothing in the response indicated anything had gone wrong; the only trace is in the server log. (#1163 removes that specific trigger by deferring to the parse-failure recovery, but the collapse itself stays for every other error class.)
Why this is not a one-line mapping fix
Anthropic's stop_reason vocabulary (end_turn | max_tokens | stop_sequence | tool_use | pause_turn) has no error member, so the choices are shaped by what clients tolerate:
- Out-of-band surfacing (probably the smallest honest change): keep
stop_reason: "end_turn", but deliver the failure alongside it — e.g. anerrorfield on the message object, or amessage_delta-adjacenterrorevent reusing the existingsse_error_eventmachinery. Clients that ignore unknown fields keep working; clients that look can tell. - HTTP-level errors for genuine server faults (5xx, or a terminal error event mid-stream), while model-output shapes (unclosed envelope, parse failures) stay completions — which is the same distinction #1163 draws one layer down.
- Document the collapse so an operator debugging a silent Anthropic failure knows to check the server log rather than the response.
Option 2 changes failure semantics clients can actually branch on, but risks breaking agent loops that today silently receive end_turn and treat the truncated markup as a real answer (a working failure mode, in a sense). I don't have a strong claim on which the project prefers — hence the issue rather than a PR; happy to implement whichever shape you pick, with the Anthropic unit cases pinned against the current anthropic_final_response/anthropic_sse_finish_live pair.
Reproduction notes (per CONTRIBUTING.md)
Machine/backend/model: Apple M5 Max 128 GB, Metal, Qwen3.8 Flash Next Q4_K + vision, production server (--thinking enabled, Anthropic /v1/messages via REQ_ANTHROPIC). The error-finish trigger (unclosed envelope) is model-output-shaped and rare by construction (1 of 149 tool turns in a multi-day soak), so a deterministic local repro is easier through the parse layer than the model: generate/hold a result with finish == "error" and observe anthropic_final_response emits stop_reason: "end_turn" with the content verbatim.
ds4_test --server is green on current main at these line references; this issue reports behavior, it is not a crash.
Still true at current main (5379c1c). anthropic_stop_reason() (ds4_server.c:9038) has not changed since the initial release (d997b56) and has no case for "error". generate_job_inner() passes final_finish straight to anthropic_sse_finish_live() (14619) and anthropic_final_response() (14651). finish is set to "error" for real generation faults, for example "decode returned no tokens" (14029), eval/rewind failures, "shutdown requested" (14284) and "invalid tool call recovery failed" (14366, 14470). For the same turn the OpenAI writers pass finish_reason:"error" through and Responses reports failed / response.failed.
I called the two Anthropic writers with finish="error" at 5379c1c from a small harness that includes ds4_server.c with DS4_SERVER_TEST (CPU build, no model). This is what they emit:
non-stream: HTTP/1.1 200 OK ... "content":[{"type":"text","text":"partial text"}],"stop_reason":"end_turn",...
stream: event: message_start ... event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn",...}} ... event: message_stop
The Messages API has no stop_reason for a failed turn. An error is an HTTP error with body {"type":"error","error":{"type":"api_error","message":...}} (500 = api_error). After a stream has started, it is an event: error SSE event (https://platform.claude.com/docs/en/api/errors, https://platform.claude.com/docs/en/build-with-claude/streaming#error-events). ds4 already does this for prefill failures: send_prefill_failure_response() calls sse_error_event(), whose Anthropic branch (7005) emits exactly that shape. So option 2 from the issue can be done in the two writers, and the change stays small. It uses the same fixed "generation failed" message as the Responses path, and the detailed err is still in the server log:
--- a/ds4_server.c
+++ b/ds4_server.c
@@ -9114,6 +9114,12 @@ static bool anthropic_final_response(int fd, bool enable_cors,
const request *r, const char *id, const char *text,
const char *reasoning, const tool_calls *calls, const char *finish,
int prompt_tokens, int completion_tokens) {
+ /* A failed turn has no Anthropic stop_reason: report it as an error. */
+ if (finish && !strcmp(finish, "error")) {
+ return http_response(fd, enable_cors, 500, "application/json",
+ "{\"type\":\"error\",\"error\":{\"type\":\"api_error\","
+ "\"message\":\"generation failed\"}}\n");
+ }
buf b = {0};
buf_printf(&b, "{\"id\":\"%s\",\"type\":\"message\",\"role\":\"assistant\",\"model\":", id);
json_escape(&b, r->model);
@@ -9838,6 +9844,7 @@ static bool anthropic_sse_finish_live(int fd, server *s, const request *r, const
anthropic_stream *st, const char *raw,
size_t raw_len, const tool_calls *calls,
const char *finish, int completion_tokens) {
+ if (finish && !strcmp(finish, "error")) return sse_error_event(fd, r, "generation failed");
if (!anthropic_sse_stream_update(fd, s, r, id, st, raw, raw_len, true)) return false;
if (st->sent_thinking && !st->sent_text && (!calls || calls->len == 0)) {
With the patch the same harness gets HTTP/1.1 500 Internal Server Error + {"type":"error","error":{"type":"api_error","message":"generation failed"}} (non-stream), and message_start followed by event: error with the same body and no message_delta/message_stop (stream).
Tests: I added the server unit test below. ./ds4_test --server (CPU-only build: tests/ds4_test.c built with -DDS4_NO_GPU, linked against the CPU core objects) gives:
- 5379c1c + test only: 6 assertion failures (200 instead of 500,
end_turninstead of an error event) - 5379c1c + test + fix:
server: OK make ds4_server_cpu.owith the fix: no warnings
This is independent of #1163 (which reclassifies the unterminated-envelope case so it no longer produces "error") and #1161 (adds stop_sequence). Neither changes what an Anthropic client gets when finish is "error", and no other open PR does.
unit test
static void test_anthropic_error_finish_is_reported_as_error(void) {
request r;
request_init(&r, REQ_CHAT, 128);
r.api = API_ANTHROPIC;
int sv[2];
TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
if (sv[0] < 0 || sv[1] < 0) {
request_free(&r);
return;
}
TEST_ASSERT(anthropic_final_response(sv[0], false, &r, "msg_err", "partial", NULL, NULL,
"error", 10, 2));
shutdown(sv[0], SHUT_WR);
char *out = read_socket_text(sv[1]);
TEST_ASSERT(strstr(out, "HTTP/1.1 500") != NULL);
TEST_ASSERT(strstr(out, "{\"type\":\"error\",\"error\":{\"type\":\"api_error\"") != NULL);
TEST_ASSERT(strstr(out, "end_turn") == NULL);
free(out);
close(sv[0]);
close(sv[1]);
r.stream = true;
TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
if (sv[0] < 0 || sv[1] < 0) {
request_free(&r);
return;
}
anthropic_stream st;
TEST_ASSERT(anthropic_sse_start_live(sv[0], &r, "msg_err_stream", 10, &st));
const char *raw = "partial";
TEST_ASSERT(anthropic_sse_finish_live(sv[0], NULL, &r, "msg_err_stream", &st,
raw, strlen(raw), NULL, "error", 2));
shutdown(sv[0], SHUT_WR);
out = read_socket_text(sv[1]);
TEST_ASSERT(strstr(out, "event: error") != NULL);
TEST_ASSERT(strstr(out, "\"type\":\"api_error\"") != NULL);
TEST_ASSERT(strstr(out, "end_turn") == NULL);
free(out);
anthropic_stream_free(&st);
close(sv[0]);
close(sv[1]);
request_free(&r);
}
/* registered after test_anthropic_usage_reports_cache_details(); */
Disclosure: written by an AI agent (Claude) operating this account with its owner's permission; the checks above were actually run.