graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(agent): auto-reconnect + resume on stream stall/drop instead of ending the turn (#56)
Rach Pradhanb632743e1362
diff --git a/scripts/test-e2e-newer-issues.py b/scripts/test-e2e-newer-issues.pyindex 22391f3d..3e124846 100755--- a/scripts/test-e2e-newer-issues.py+++ b/scripts/test-e2e-newer-issues.py@@ -58,7 +58,7 @@ def main():# and must be saved.meaningful = run("/model codegraff deepseek-v4-pro\nhello there\n/save meaningful\n/exit\n",- {"GRAFF_FORCE_STALL_ONCE": "1"},+ {"GRAFF_FORCE_STALL_ALWAYS": "1"},)if not any(p.endswith("meaningful.session.json") for p in meaningful):failures.append("#184: a conversation with a user message was NOT saved (got %s)" % (meaningful,))diff --git a/scripts/test-stall-drop.py b/scripts/test-stall-drop.pyindex e560a7e7..79103266 100644--- a/scripts/test-stall-drop.py+++ b/scripts/test-stall-drop.py@@ -1,9 +1,10 @@#!/usr/bin/env python3-"""#134/#132 end-to-end: a forced stream stall/drop is saved as-"[response ended early: ...]" and shown as a stream notice — NEVER a user Esc-interrupt. Drives the GRAFF_FORCE_STALL_ONCE / GRAFF_FORCE_DROP_ONCE test seams,-which make the next live turn return error.StreamStalled / error.StreamDropped-before any network call, so no provider/key is needed."""+"""#134/#132/#56 end-to-end: a forced stream stall/drop first RECONNECTS on a+fresh stream (#56); only after the reconnect budget is exhausted is the turn saved+as "[response ended early: ...]" and shown as a stream notice — NEVER a user Esc+interrupt. Drives the GRAFF_FORCE_STALL_ALWAYS / GRAFF_FORCE_DROP_ALWAYS seams,+which make EVERY live attempt return error.StreamStalled / error.StreamDropped+before any network call, so the give-up path runs with no provider/key."""import json, os, shutil, subprocess, sys, tempfile_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"@@ -42,13 +43,14 @@ def check(name, env_flag, marker, notice):# the whole point of #134/#132: it must NOT be a user interruptionassert "interrupted by user" not in assistant, f"{name}: mislabeled [response interrupted by user]!"assert "interrupted (esc)" not in out, f"{name}: terminal showed 'interrupted (esc)'!"+ assert "reconnect" in out, f"{name}: no reconnect attempt shown before giving up (#56)"print(f"ok {name}: saved {marker!r}, notice shown, never a user Esc")def main():- check("stall (#134)", "GRAFF_FORCE_STALL_ONCE",+ check("stall (#134)", "GRAFF_FORCE_STALL_ALWAYS","[response ended early: stream stalled]", "stream stalled")- check("drop (#132/#133)", "GRAFF_FORCE_DROP_ONCE",+ check("drop (#132/#133)", "GRAFF_FORCE_DROP_ALWAYS","[response ended early: connection dropped]", "connection dropped")print("all clear: a forced stall/drop is [response ended early: ...], never a user Esc interrupt")diff --git a/src/agent_request.zig b/src/agent_request.zigindex 4ddeb6cc..0c1a75e8 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -301,6 +301,11 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {self.say("[tool output over this model's per-result cap — truncated {d} bytes before send (#193)]\n", .{capped}) catch {};}var context_retried = false; // #193: at most one in-turn overflow recovery per request+ // #56: bounded stream-stall / drop reconnect budget (codex's stream_max_retries+ // analog). Declared outside the rebuild loop so a WS reanchor can't reset it.+ var stall_retries: usize = 0;+ const max_stall_retries: usize = 2;+ const stall_reconnect_backoff_ms = 750; // brief pause before reconnecting on a fresh streamrebuild: while (true) {const live = !self.sub and self.out != null and !self.stream_quiet;self.streamed_text = false;@@ -329,25 +334,37 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {self.streamed_args = .none;// Esc is a deliberate stop, not a flaky network — no retry.if (err == error.Interrupted) return error.Interrupted;- // A mid-stream idle stall already streamed its partial text- // and printed the "stream stalled" notice; retrying would- // re-stream the whole answer from scratch. End the turn — but- // as error.StreamStalled, recorded with the timeout + reason,- // so it is classified as a harness stall and never as a user- // Esc interruption (#134).- if (err == error.StreamStalled) {- self.last_api_error = std.fmt.allocPrint(self.arena, "stream stalled: no data from the model for {d}s — ended the turn (raise GRAFF_STREAM_STALL_SECS if your model needs longer)", .{http.stream_stall_ms / 1000}) catch null;- if (telemetry.g_telem) |t| t.errorEvent("stream_stall", self.last_api_error orelse "stream stalled");- 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";+ // #56: a mid-stream idle stall or a connection drop (the+ // provider closed/reset before its terminal event) — NOT a+ // user Esc, which is handled above. Usually transient, so+ // reconnect on a fresh stream and re-send the full request,+ // like codex's stream_max_retries (restart the request; the+ // partial was never committed to history). Bounded; on+ // exhaustion end the turn recorded as a stall/drop, never a+ // user Esc (#134). The budget lives outside the rebuild loop+ // so a WS reanchor can't reset it.+ if (err == error.StreamStalled or err == error.StreamDropped) {+ const stalled = err == error.StreamStalled;+ const what: []const u8 = if (stalled) "stream stalled" else "stream dropped";+ if (stall_retries < max_stall_retries) {+ stall_retries += 1;+ try self.say("[{s} — reconnecting ({d}/{d})]\n", .{ what, stall_retries, max_stall_retries });+ if (self.tracer) |tr| tr.note("stream_retry", what);+ if (telemetry.g_telem) |t| t.errorEvent("stream_retry", what);+ self.partial_text.clearRetainingCapacity(); // fresh stream re-streams cleanly, no concat+ self.closeCodexWs(); // fresh transport session for the retry (no-op off codex WS)+ if (self.codex_prev_id) |old| self.gpa.free(old);+ self.codex_prev_id = null; // full re-send on a fresh stream, like a WS reanchor+ self.sleepInterruptible(stall_reconnect_backoff_ms) catch return error.Interrupted;+ continue :rebuild;+ }+ if (stalled) {+ self.last_api_error = std.fmt.allocPrint(self.arena, "stream stalled: no data from the model for {d}s — ended the turn after {d} reconnect attempts (raise GRAFF_STREAM_STALL_SECS if your model needs longer)", .{ http.stream_stall_ms / 1000, max_stall_retries }) catch null;+ if (telemetry.g_telem) |t| t.errorEvent("stream_stall", self.last_api_error orelse "stream stalled");+ if (self.tracer) |tr| tr.note("stream_stall", self.last_api_error orelse "stream stalled");+ return error.StreamStalled;+ }+ self.last_api_error = "stream dropped: the provider closed the connection before the response completed — ended the turn after reconnect attempts";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;diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 8f912931..5fb11dc1 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -72,6 +72,23 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {// #134/#132 test seam: force a one-shot stall/drop on a live turn so the// end-to-end "[response ended early: …]" path (never "[response interrupted// by user]") can be exercised without a real provider. Consumed after one use.+ // #56 test seam: a stall/drop on EVERY live attempt (not consumed), so the+ // reconnect budget in agent_request exhausts and the turn ends — exercises the+ // give-up path offline, no network/key needed.+ if (main_mod.g_force_stall_always) {+ if (!main_mod.json_mode) if (self.out) |o| {+ o.writeAll("\n⚠ stream stalled\n") catch {};+ o.flush() catch {};+ };+ return error.StreamStalled;+ }+ if (main_mod.g_force_drop_always) {+ if (!main_mod.json_mode) if (self.out) |o| {+ o.writeAll("\n⚠ connection dropped\n") catch {};+ o.flush() catch {};+ };+ return error.StreamDropped;+ }if (main_mod.g_force_stall_once) {main_mod.g_force_stall_once = false;if (!main_mod.json_mode) if (self.out) |o| {diff --git a/src/main.zig b/src/main.zigindex d2c1f058..15fcd185 100644--- a/src/main.zig+++ b/src/main.zig@@ -61,6 +61,8 @@ pub var g_codex_ws = true; // root Codex turns use the WebSocket transport (Resppub var g_clock_sleep: bool = false; // #225: root-only clock_sleep meta tool, off by default; --clock-sleep / GRAFF_CLOCK_SLEEP=1 turns it on (gates advertising in renderRootTools, mirrors g_codex_ws)pub var g_force_stall_once: bool = false; // #134 test seam (GRAFF_FORCE_STALL_ONCE=1): the next live turn returns error.StreamStalled — proves the stall path is never labeled a user Escpub var g_force_drop_once: bool = false; // #132/#133 test seam (GRAFF_FORCE_DROP_ONCE=1): the next live turn returns error.StreamDropped+pub var g_force_stall_always: bool = false; // #56 test seam (GRAFF_FORCE_STALL_ALWAYS=1): EVERY live attempt stalls, so the reconnect budget exhausts and the turn ends as a stall — exercises the give-up path offline+pub var g_force_drop_always: bool = false; // #56 test seam (GRAFF_FORCE_DROP_ALWAYS=1): EVERY live attempt dropspub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budgetpub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turnpub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposesdiff --git a/src/session_run.zig b/src/session_run.zigindex ef32c30e..7c9113e1 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -346,6 +346,8 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:main_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via envmain_mod.g_force_stall_once = environ_map.get("GRAFF_FORCE_STALL_ONCE") != null; // #134 test seammain_mod.g_force_drop_once = environ_map.get("GRAFF_FORCE_DROP_ONCE") != null; // #132/#133 test seam+ main_mod.g_force_stall_always = environ_map.get("GRAFF_FORCE_STALL_ALWAYS") != null; // #56 test seam (exhaust the reconnect budget)+ main_mod.g_force_drop_always = environ_map.get("GRAFF_FORCE_DROP_ALWAYS") != null; // #56 test seam// #134: let a provider that buffers a long reasoning phase in total silence// raise the mid-stream idle-stall cutoff (default 120s). Seconds; ignored if// unparseable or 0. A stall is never a user interrupt regardless of the value.