Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(stream): distinguish an API stream drop from a clean end / user Esc (#133)

justrachbe1ce0afc938
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 46357f17..91682e89 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -93,6 +93,17 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
if (self.tracer) |tr| tr.note("stream_stall", self.last_api_error orelse "stream stalled");
return error.StreamStalled;
}
+ // A mid-stream connection drop (#133): the provider closed or
+ // reset before its terminal event, but bytes already streamed —
+ // retrying would re-stream from scratch. End the turn as
+ // error.StreamDropped so it is recorded as a provider drop and
+ // never a user Esc.
+ if (err == error.StreamDropped) {
+ self.last_api_error = "stream dropped: the provider closed the connection before the response completed — ended the turn";
+ if (telemetry.g_telem) |t| t.errorEvent("stream_dropped", self.last_api_error.?);
+ if (self.tracer) |tr| tr.note("stream_dropped", self.last_api_error.?);
+ return error.StreamDropped;
+ }
// 429/5xx: the server asked us to back off — wait
// (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few
// more attempts than a plain transport flake gets.
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 360dac7a..76011d3a 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -330,6 +330,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
errdefer full.deinit();
var line: Io.Writer.Allocating = .init(gpa);
var got_body = false; // #134: true once response bytes have been received (gates the post-completion read-error handling)
+ var saw_done = false; // #133: true only once the provider's terminal event landed — a close before this is a drop, not a clean end
defer line.deinit();
stream: while (true) {
@@ -342,7 +343,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer }) catch {
_ = reader.streamDelimiterEnding(&line.writer, '\n') catch |e| {
- if (got_body and readErrIsClose(e)) break :stream; // #134: body already delivered — not a retryable flake
+ if (saw_done and readErrIsClose(e)) break :stream; // #134/#135: terminal event already seen — a post-completion close/reset is clean
+ if (got_body and readErrIsClose(e)) { noteDropped(self); return error.StreamDropped; } // #133: closed before [DONE]/finish_reason — a drop, not a clean end
return e;
}; // no spare concurrency
break :read;
@@ -354,7 +356,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
};
rsel.cancelDiscard();
_ = r.line catch |e| {
- if (got_body and readErrIsClose(e)) break :stream;
+ if (saw_done and readErrIsClose(e)) break :stream;
+ if (got_body and readErrIsClose(e)) { noteDropped(self); return error.StreamDropped; } // #133
return e;
};
break :read;
@@ -366,7 +369,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
rsel.cancelDiscard();
switch (first) {
.line => |r| _ = r catch |e| {
- if (got_body and readErrIsClose(e)) break :stream; // #134: post-completion close/reset is success, not a retryable flake
+ if (saw_done and readErrIsClose(e)) break :stream; // #134/#135: post-completion close/reset is success, not a retryable flake
+ if (got_body and readErrIsClose(e)) { noteDropped(self); return error.StreamDropped; } // #133: closed before the terminal event
return e;
},
.stall => |w| {
@@ -402,7 +406,12 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// close. Some gateways hold the connection open (or reset it) after the
// last event, which otherwise trips the 120s idle-stall watchdog or a
// spurious retry on an already-complete response (#134/#135).
+ // #133: a finish_reason chunk means the response is complete even if the
+ // provider never sends [DONE] — record it so a subsequent close counts
+ // as a clean end, but keep reading so a trailing usage chunk still lands.
+ if (self.provider.kind == .openai and openaiComplete(line.writer.buffered())) saw_done = true;
if (isStreamEnd(self.arena, self.provider.kind, line.writer.buffered())) {
+ saw_done = true; // #133: the provider's terminal event landed — a later close is clean
if (req.connection) |conn| conn.closing = true;
break :stream;
}
@@ -435,6 +444,28 @@ fn readErrIsClose(e: anyerror) bool {
return e == error.ReadFailed or e == error.EndOfStream;
}
+/// #133: a non-null string finish_reason marks an OpenAI-compatible response
+/// semantically complete, even when the provider omits the [DONE] sentinel.
+/// Content deltas escape their quotes, so this raw substring can only match the
+/// real key, never text. Used to set saw_done WITHOUT stopping the read (so a
+/// trailing usage-only chunk and [DONE] are still consumed).
+fn openaiComplete(raw_line: []const u8) bool {
+ const payload = ssePayload(raw_line) orelse return false;
+ return std.mem.indexOf(u8, payload, "\"finish_reason\":\"") != null;
+}
+
+/// The provider closed/reset the stream before its terminal event landed — the
+/// harness is ending the turn, not the user (#133). Flush the partial and tell
+/// the user (TTY/plain), so a Moonshot-style mid-reasoning drop can never pass
+/// silently as a completed answer.
+fn noteDropped(self: *Agent) void {
+ self.flushStreamTail();
+ if (!main_mod.json_mode) if (self.out) |o| {
+ o.writeAll("\n⚠ connection dropped — response ended early\n") catch {};
+ o.flush() catch {};
+ };
+}
+
/// True if this SSE line is the provider's terminal event — after it no more
/// content comes, so postStream can stop instead of waiting for the socket to
/// close (#134/#135). Precise: matches the `[DONE]` sentinel, a structural
@@ -489,6 +520,24 @@ test "isStreamEnd (#134): terminal events detected, content deltas never false-m
try std.testing.expect(isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.completed\"}"));
try std.testing.expect(isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.incomplete\"}"));
try std.testing.expect(!isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}"));
+ // #133 (openai/kimi): a non-null string finish_reason chunk is terminal (some
+ // gateways omit [DONE]); a null finish_reason or a bare reasoning/content
+ // delta is NOT — a connection drop after one of those is a StreamDropped, not
+ // a clean end.
+ try std.testing.expect(!isStreamEnd(a, Kind.openai, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
+ try std.testing.expect(!isStreamEnd(a, Kind.openai, "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
+}
+
+test "openaiComplete (#133): finish_reason marks completion, deltas do not" {
+ // non-null finish_reason => complete (even without [DONE]).
+ try std.testing.expect(openaiComplete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}"));
+ try std.testing.expect(openaiComplete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"length\"}]}"));
+ // mid-stream: null finish_reason or a bare reasoning delta is NOT complete —
+ // a connection drop after one of these is the #133 StreamDropped case.
+ try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
+ try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
+ // the substring must not false-match a finish_reason that appears in escaped content.
+ try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"content\":\"\\\"finish_reason\\\":\\\"x\"}}]}"));
}
/// Print the user-visible text from one SSE line, if any. Best-effort:
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 4a4237aa..febef660 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -475,6 +475,7 @@ pub fn run(ctx: *Ctx) !void {
const fail_detail: []const u8 = if (turn_result) |_| "" else |e| switch (e) {
error.ApiError => ctx.root.last_api_error orelse "api error",
error.StreamStalled => ctx.root.last_api_error orelse "stream stalled — ended turn",
+ error.StreamDropped => ctx.root.last_api_error orelse "stream dropped — ended turn",
else => @errorName(e),
};
tj.node(.{ .kind = "turn_error", .parent = turn_id, .t = tj.elapsedMs(), .detail = fail_detail });
@@ -521,6 +522,27 @@ pub fn run(ctx: *Ctx) !void {
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
continue;
},
+ error.StreamDropped => {
+ // The provider closed/reset the connection before its terminal
+ // event ([DONE]/finish_reason) — the harness ended the turn, NOT
+ // the user (#133). Keep the partial, tag it a drop (never
+ // "[response interrupted by user]"), and emit the --json error.
+ const partial = std.mem.trim(u8, ctx.root.partial_text.items, " \t\r\n");
+ const marker: []const u8 = if (partial.len > 0)
+ try std.fmt.allocPrint(ctx.arena, "{s}\n\n[response ended early: connection dropped]", .{partial})
+ else
+ "[response ended early: connection dropped]";
+ try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", marker));
+ if (main_mod.json_mode) {
+ ctx.root.emit(.{ .type = "error", .message = ctx.root.last_api_error orelse "stream dropped — ending turn" });
+ if (partial.len > 0) {
+ ctx.root.emit(.{ .type = "finalizing" });
+ ctx.root.emit(.{ .type = "turn", .text = partial, .context_tokens = ctx.root.last_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = false, .metadata_complete = ctx.root.last_context_tokens > 0 });
+ }
+ }
+ session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
+ continue;
+ },
error.ApiError => {
if (telemetry.g_telem) |t| t.errorEvent("api", ctx.root.last_api_error orelse "api error");
if (main_mod.json_mode) {
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 10e4896f..88d01b35 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -242,6 +242,16 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
else
gpa.dupe(u8, "[response ended early: stream stalled]") catch null;
},
+ error.StreamDropped => {
+ // A mid-stream provider drop (#133), same handling as a stall: keep
+ // the streamed partial + an honest marker, never a null that the
+ // pane would render as "model call failed".
+ const partial = std.mem.trim(u8, agent.partial_text.items, " \t\r\n");
+ return if (partial.len > 0)
+ std.fmt.allocPrint(gpa, "{s}\n\n[response ended early: connection dropped]", .{partial}) catch null
+ else
+ gpa.dupe(u8, "[response ended early: connection dropped]") catch null;
+ },
error.FallbackConsentRequired => return gpa.dupe(u8, "Saved model unavailable. Allow this provider with /fallback in the standard REPL, or choose another model.") catch null,
else => return null,
};