graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(stream): widen the between-lines stall budget on each reconnect (#680)
justracha249efcdc328
diff --git a/src/agent.zig b/src/agent.zigindex 75928435..0c7e8489 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -211,6 +211,7 @@ pub const Agent = struct {ws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)ws_transport_failures: u8 = 0, // consecutive WS failures; retry once before latching persistent SSEstreamed_text: bool = false, // the last request printed its text live+ stall: @import("http_stall.zig").State = .{}, // #680: reconnects made this request (each widens the between-lines budget) + the budget that last trippedrequest_started: ?Io.Timestamp = null, // operational TTFT origin for the active model call (#602)first_token_traced: bool = false,thinking_open: bool = false, // a live "Thinking" reasoning block is currently streaming (/thinking)diff --git a/src/agent_request.zig b/src/agent_request.zigindex faa41664..c3a8155b 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -208,8 +208,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {}}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.+ // #56: bounded stream-stall / drop reconnect budget (codex's stream_max_retries analog), outside the rebuild loop so a WS reanchor can't reset it.+ self.stall = .{}; // #680: a fresh widen ladder + tripped budget per requestvar stall_retries: usize = 0;const max_stall_retries: usize = 2;const stall_reconnect_backoff_ms = 750; // brief pause before reconnecting on a fresh stream@@ -285,7 +285,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {if (stall_retries > 1) self.ws_off = true;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+ @import("agent_stream.zig").noteStallRetry(self, stall_retries); // #680: clears the partial (fresh stream, no concat) + widens the between-lines budgetself.closeCodexWs(); // tear down the dead WS + null codex_prev_id for a full re-send (no-op off codex WS)self.sleepInterruptible(stall_reconnect_backoff_ms) catch return error.Interrupted;continue :rebuild;@@ -293,7 +293,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// Budget gone: the turn is ending. Mid-turn cuts stayed silent.@import("engine_sink.zig").forAgent(self).emit(self.io, .{ .transport_aborted = .{ .reason = if (stalled) .stalled else .dropped, .turn_ending = true } });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;+ self.last_api_error = @import("agent_stream.zig").stallGiveUpMessage(self, max_stall_retries); // #680: reports the wait that tripped, not the configured totalif (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;diff --git a/src/agent_stream.zig b/src/agent_stream.zigindex 7335450c..8e7f3605 100644--- a/src/agent_stream.zig+++ b/src/agent_stream.zig@@ -227,6 +227,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []consconst ReadDone = union(enum) { line: anyerror!usize, stall: WatchdogFired };var rd_buf: [2]ReadDone = undefined;var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);+ // #680: widened by each stall reconnect this request has already made.+ const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, self.partial_text.items.len != 0, self.stall.widen);rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer }) catch {// #56 Fix-B: pool exhausted — no idle-stall watchdog for this read.// A bare blocking streamDelimiterEnding here is the last forever-hang:@@ -236,11 +238,11 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons// flush the partial, poison, and end the turn as StreamStalled (never a// hang, never a mislabeled StreamDropped or user Esc).if (saw_done) break :stream;+ self.stall.tripped_ms = stall_budget;sink.emit(self.io, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } });if (req.connection) |conn| conn.closing = true;return error.StreamStalled;};- const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, self.partial_text.items.len != 0);rsel.concurrent(.stall, deadlineStallTask, .{ self.io, orig_tio != null, stall_budget }) catch {const r = rsel.await() catch |e| {rsel.cancelDiscard();@@ -276,6 +278,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons// idle stream (silent past this read's budget) — end the turn as// error.StreamStalled so it is never recorded as "[response// interrupted by user]" (#134). Only the deadline gets a notice.+ if (w == .deadline) self.stall.tripped_ms = stall_budget; // #680: the turn-ending message reports THIS waitif (w == .deadline) sink.emit(self.io, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } }) else sink.emit(self.io, .{ .stream_aborted = .interrupted });if (req.connection) |conn| conn.closing = true;return watchdogError(w, error.StreamStalled);@@ -386,6 +389,33 @@ test "openaiComplete (#133): finish_reason marks completion, deltas do not" {try stream_tests.openaiCompletion(openaiComplete);}+test {+ _ = @import("agent_stream_stall_test.zig"); // #680: the loopback SSE stall ladder+}++/// #680: what request() does before each stall reconnect. The partial is+/// cleared so the fresh stream re-streams cleanly (no concat), and the+/// between-lines budget widens (http_stall.budgetMsWidened) so the retry can+/// outlast the pause that killed the last attempt, instead of re-paying the+/// whole generation into the identical wait.+pub fn noteStallRetry(self: *Agent, retries: usize) void {+ self.partial_text.clearRetainingCapacity();+ self.stall.widen = @intCast(@min(retries, 255));+ if (self.tracer) |tr| {+ const widened = http_stall.budgetMsWidened(http.stream_stall_ms, true, self.stall.widen);+ tr.note("stall_budget", std.fmt.allocPrint(self.arena, "reconnect {d}: between-lines budget {d}s", .{ retries, widened / 1000 }) catch "widened");+ }+}++/// #680: the turn-ending stall message, from the budget that actually tripped+/// rather than the configured total (the between-lines wait is a fraction of+/// it, so "120s" was never what a mid-response stall had waited).+pub fn stallGiveUpMessage(self: *Agent, retries: usize) ?[]const u8 {+ const base = http.stream_stall_ms;+ const waited = if (self.stall.tripped_ms != 0) self.stall.tripped_ms else base;+ return std.fmt.allocPrint(self.arena, "stream stalled: no data from the model for {d}s — ended the turn after {d} reconnect attempts, each waiting longer, up to GRAFF_STREAM_STALL_SECS={d}s between lines (raise it if your model pauses longer mid-response)", .{ waited / 1000, retries, base / 1000 }) catch null;+}+/// Extract the user-visible content from one SSE line and dispatch it as/// typed events through the sink. Best-effort: parse failures are ignored/// (the buffered body is parsed afterwards).diff --git a/src/agent_stream_stall_test.zig b/src/agent_stream_stall_test.zignew file mode 100644index 00000000..511832fb--- /dev/null+++ b/src/agent_stream_stall_test.zig@@ -0,0 +1,120 @@+//! (#680) The SSE reader's stall ladder, end to end against a loopback HTTP+//! server: one chat-completions prose delta, then silence. Drives the REAL+//! production entry point (agent_stream.postStreamWithClient) three times the+//! way request() does across its two stall reconnects, and asserts each+//! attempt waited ITS OWN budget — a quarter, a half, then all of the+//! configured total — rather than the same tightened wait three times.+//!+//! Same spirit as agent_ws_mock.zig: `provider.url` points at 127.0.0.1, and+//! no network, key or provider is used.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++const http = @import("http.zig");+const http_stall = @import("http_stall.zig");+const agent_stream = @import("agent_stream.zig");+const Agent = @import("agent.zig").Agent;+const nowMs = @import("agent_ws_mock.zig").nowMs;++/// One chat-completions delta with visible prose: the reader grows+/// partial_text on it, which is the tokens-flowing signal that tightens the+/// between-lines budget. After it, the socket stays open and silent.+const prose_line = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n";++const Srv = struct {+ /// Answer `conns` requests in turn: drain the request head, send the SSE+ /// head plus one prose delta, then hold the socket open without another+ /// byte until the test is over. Every accepted socket is kept, so a+ /// client that gave up sees silence (a stall), never EOF (a drop).+ fn run(io: Io, server: *std.Io.net.Server, conns: usize, done: *std.atomic.Value(bool)) void {+ var held: [3]?std.Io.net.Stream = @splat(null);+ defer for (held) |h| if (h) |c| c.close(io);+ var i: usize = 0;+ while (i < conns) : (i += 1) {+ const c = server.accept(io) catch return;+ held[i] = c;+ var rbuf: [8192]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);+ while (true) {+ const l = (sr.interface.takeDelimiter('\n') catch return) orelse return;+ if (l.len == 0 or (l.len == 1 and l[0] == '\r')) break; // end of headers+ }+ var wbuf: [1024]u8 = undefined;+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);+ sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++ prose_line) catch return;+ sw.interface.flush() catch return;+ }+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch return;+ }+};++test "#680: each stall reconnect widens the between-lines wait the SSE reader arms" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer server.deinit(io); // registered first → torn down LAST, after the task is joined+ var done: std.atomic.Value(bool) = .init(false);+ var fut = io.async(Srv.run, .{ io, &server, @as(usize, 3), &done });+ defer fut.await(io);+ defer done.store(true, .release); // …so the LIFO order is: signal, join, close++ // Scale the budget down so the ladder fits a test: base 1200ms, so the+ // three attempts arm 300 / 600 / 1200ms once prose has flowed. The 15s+ // floor would otherwise make every rung identical; both are process-wide.+ const saved_stream = http.stream_stall_ms;+ const saved_floor = http_stall.idle_floor_ms;+ http.stream_stall_ms = 1200;+ http_stall.idle_floor_ms = 100;+ defer http.stream_stall_ms = saved_stream;+ defer http_stall.idle_floor_ms = saved_floor;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var out: Io.Writer.Allocating = .init(gpa); // a writer: printDelta only grows partial_text for an agent with a frontend+ defer out.deinit();+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/chat/completions", .{server.socket.address.getPort()});+ var agent: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &client,+ .provider = .{ .id = "test", .kind = .openai, .auth = .bearer, .url = url, .api_key = "k", .model = "m", .context = 0 },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "",+ .out = &out.writer,+ };++ // All three attempts run before any assertion, so a failure can never+ // leave the server blocked in accept() with the join waiting on it.+ var waits: [3]i64 = undefined;+ var errs: [3]?anyerror = @splat(null);+ for (0..3) |i| {+ if (i > 0) agent_stream.noteStallRetry(&agent, i); // what request() does before each reconnect+ const t0 = nowMs(io);+ const r = agent_stream.postStreamWithClient(&agent, &client, "{}");+ waits[i] = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |e| errs[i] = e;+ }+ for (errs) |e| try std.testing.expectEqual(@as(?anyerror, error.StreamStalled), e);+ // Each attempt waited its own rung — comfortably past its budget (so the+ // watchdog really ran) and comfortably short of the next rung's.+ try std.testing.expect(waits[0] >= 250 and waits[0] < 550);+ try std.testing.expect(waits[1] >= 550 and waits[1] < 1100);+ try std.testing.expect(waits[2] >= 1150 and waits[2] < 2200);+ // The give-up message reports the wait that actually tripped.+ try std.testing.expectEqual(@as(u64, 1200), agent.stall.tripped_ms);+ const msg = agent_stream.stallGiveUpMessage(&agent, 2) orelse return error.TestUnexpectedResult;+ try std.testing.expect(std.mem.indexOf(u8, msg, "for 1s") != null);+ try std.testing.expect(std.mem.indexOf(u8, msg, "after 2 reconnect attempts") != null);+}diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex d6898626..69b9a38a 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -510,7 +510,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// here is equivalent and lets both regimes share one watchdog arm.read: {const head_wait = reused and frames_seen == 0;- const budget = if (head_wait) http.head_stall_ms else http_stall.interFrameBudgetMs(http.stream_stall_ms, frames_seen > 0, text_seen);+ const budget = if (head_wait) http.head_stall_ms else http_stall.interFrameBudgetMs(http.stream_stall_ms, frames_seen > 0, text_seen, self.stall.widen);const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };var rd_buf: [2]ReadDone = undefined;var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);@@ -548,6 +548,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {return watchdogError(w, error.HungRequest);} else {// Only the deadline gets a notice; a user Esc stays silent.+ if (w == .deadline) self.stall.tripped_ms = budget; // #680: the turn-ending message reports THIS waitif (w == .deadline) emitAbort(self, .stalled, false);if (self.tracer) |tr| tr.note("ws", if (w == .esc) "esc" else "stall");return watchdogError(w, error.StreamStalled);diff --git a/src/http.zig b/src/http.zigindex 2d513f03..42ddc650 100644--- a/src/http.zig+++ b/src/http.zig@@ -238,9 +238,9 @@ fn postWatchdog(io: Io) WatchdogFired {// resets its clock on every line, so it measures the gap between tokens/// keep-alives/reasoning deltas) is a dead or hung connection. This is the// PRE-first-token budget, generous because a silent reasoning phase legitimately-// runs minutes; http_stall.budgetMs tightens it once tokens are flowing (#56).-// Tunable via GRAFF_STREAM_STALL_SECS (session_run.setupSkillsAndTheme), which-// scales both regimes. Giving up is error.StreamStalled, NEVER a user Esc (#134).+// runs minutes; http_stall.budgetMs tightens it once tokens flow (#56); each stall+// reconnect widens it back toward the total (#680). Tunable via GRAFF_STREAM_STALL_SECS+// (session_run.setupSkillsAndTheme), both regimes. Giving up is error.StreamStalled, NEVER a user Esc (#134).pub var stream_stall_ms: u64 = 120 * 1000;/// A response head idle this long = the server accepted the connection but isdiff --git a/src/http_stall.zig b/src/http_stall.zigindex 136589ac..810934b3 100644--- a/src/http_stall.zig+++ b/src/http_stall.zig@@ -35,19 +35,46 @@ pub var idle_floor_ms: u64 = 15 * 1000;/// idle_floor_ms; production writes it only from session_settings.pub var head_ceiling_ms: u64 = 45 * 1000;+/// Per-request reconnect state the SSE and WS readers consult (#680). Owned by+/// the Agent, reset at the top of every request(), advanced by each stall+/// reconnect.+pub const State = struct {+ /// Stall reconnects this request has already made. Each one widens the+ /// between-lines budget (budgetMsWidened): a stream that stalled at the+ /// same point twice is a model pausing mid-response — composing a large+ /// tool call, say — not a dead socket, and re-sending the identical+ /// request into the identical budget only re-pays the generation.+ widen: u8 = 0,+ /// The budget (ms) of the read that last tripped, so the turn-ending+ /// message reports what was actually waited rather than the configured+ /// total. 0 until a watchdog fires.+ tripped_ms: u64 = 0,+};+pub fn budgetMs(base_ms: u64, tokens_flowing: bool) u64 {+ return budgetMsWidened(base_ms, tokens_flowing, 0);+}++/// budgetMs with the reconnect ladder applied (#680): `widen` is how many+/// stall reconnects this request has made. The between-lines divisor halves+/// each time — a quarter, a half, then the full configured budget — and the+/// floor and the configured total still bound it. The pre-first-token+/// ceiling is NOT widened: a socket that never answered is dead on arrival+/// (#401), and that regime has its own retry ladder (HungRequest).+pub fn budgetMsWidened(base_ms: u64, tokens_flowing: bool, widen: u8) u64 {if (!tokens_flowing) return @min(base_ms, head_ceiling_ms);- return @min(base_ms, @max(idle_floor_ms, base_ms / idle_divisor));+ const divisor = idle_divisor >> @intCast(@min(widen, 2));+ return @min(base_ms, @max(idle_floor_ms, base_ms / divisor));}/// Inter-frame wait. No bytes yet is a dead socket (head ceiling). Protocol/// frames without prose is a reasoning model (full `base_ms` — gpt-5.6-sol/// high/max often encrypts thinking and emits nothing for well over 45s).-/// Visible prose tightens to the between-lines budget.-pub fn interFrameBudgetMs(base_ms: u64, saw_protocol: bool, tokens_flowing: bool) u64 {- if (tokens_flowing) return budgetMs(base_ms, true);+/// Visible prose tightens to the between-lines budget, widened per reconnect.+pub fn interFrameBudgetMs(base_ms: u64, saw_protocol: bool, tokens_flowing: bool, widen: u8) u64 {+ if (tokens_flowing) return budgetMsWidened(base_ms, true, widen);if (saw_protocol) return base_ms;- return budgetMs(base_ms, false);+ return budgetMsWidened(base_ms, false, widen);}/// True once a silent read has outlasted its budget — the watchdog loop's only@@ -92,7 +119,27 @@ test "stall budget (#56): between-lines silence trips sooner than a pre-first-totest "stall budget: protocol-seen thinking keeps the full wait, not the 45s ceiling" {const base: u64 = 120 * 1000;- try std.testing.expectEqual(head_ceiling_ms, interFrameBudgetMs(base, false, false));- try std.testing.expectEqual(base, interFrameBudgetMs(base, true, false));- try std.testing.expectEqual(@as(u64, 30 * 1000), interFrameBudgetMs(base, true, true));+ try std.testing.expectEqual(head_ceiling_ms, interFrameBudgetMs(base, false, false, 0));+ try std.testing.expectEqual(base, interFrameBudgetMs(base, true, false, 0));+ try std.testing.expectEqual(@as(u64, 30 * 1000), interFrameBudgetMs(base, true, true, 0));+}++// The #680 signature: reasoning streamed, one line of prose, then >30s of+// silence while the model composed a large tool call. The old ladder armed the+// same 30s on every reconnect, so all three attempts died at the same point+// and the turn ended claiming "no data for 120s".+test "stall budget (#680): each reconnect widens the between-lines wait — a quarter, a half, then all of it" {+ const base: u64 = 120 * 1000;+ try std.testing.expectEqual(@as(u64, 30 * 1000), budgetMsWidened(base, true, 0));+ try std.testing.expectEqual(@as(u64, 60 * 1000), budgetMsWidened(base, true, 1));+ try std.testing.expectEqual(base, budgetMsWidened(base, true, 2));+ try std.testing.expectEqual(base, budgetMsWidened(base, true, 7)); // past the ladder: still the configured total+ // Through the reader's entry point, and only for the prose regime.+ try std.testing.expectEqual(@as(u64, 60 * 1000), interFrameBudgetMs(base, true, true, 1));+ try std.testing.expectEqual(base, interFrameBudgetMs(base, true, false, 1)); // protocol-only: already the full wait+ try std.testing.expectEqual(head_ceiling_ms, interFrameBudgetMs(base, false, false, 2)); // dead on arrival is not widened+ // The floor and the total still bound a short GRAFF_STREAM_STALL_SECS.+ try std.testing.expectEqual(idle_floor_ms, budgetMsWidened(20 * 1000, true, 1)); // 10s < floor+ try std.testing.expectEqual(@as(u64, 20 * 1000), budgetMsWidened(20 * 1000, true, 2));+ try std.testing.expectEqual(@as(u64, 5 * 1000), budgetMsWidened(5 * 1000, true, 1));}