graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): tighten the WS read budget once frames flow (#401)
Rach Pradhanfa35d542485d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8dbbd031..ca45dfd6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,26 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## Unreleased++- Codex WebSocket turns no longer sit silent for minutes when the backend goes+ quiet mid-response. The WS reader armed its stall watchdog with a hardcoded+ "no tokens yet", so it re-armed the full 120s pre-first-token budget on every+ frame and never tightened once data was flowing — the SSE reader has always+ tightened to a quarter. Silence after frames now trips in ~30s, and the trace+ gains `sent <n>b` and `first frame` notes, so a hang says which half of the+ turn went quiet instead of stopping dead at `reuse (delta)` (#401).+- The WS send and dial are under a deadline too (an unbounded blocking write /+ an unbounded dial through DNS + TLS + the 101 status line), with Esc live+ during both. They report the transport-flake error the SSE guard uses, so a+ wedged socket is retried on a fresh one rather than spending the turn's stall+ budget; the send deadline scales with the frame so a full-conversation+ re-anchor is not a false positive. A held socket that any path already+ condemned is re-anchored instead of reused (openai/codex `is_closed()`+ parity), and a suspect socket is torn down with a plain FIN rather than a+ courtesy close frame that could block again. A failed WS handshake no longer+ leaks its fd and CA bundle.+## v0.0.237 (2026-08-04)- Ultracode redesigned around an escalation ladder: the codeword now meansdiff --git a/src/agent_ws.zig b/src/agent_ws.zigindex fc6ef1e7..e16ce396 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -10,10 +10,13 @@//! re-anchor, then latch onto the launch-scoped prewarmed HTTP client for SSE.//!//! Observability (issue #134's ask): every ws lifecycle step is routed to the-//! tracer ("ws" notes: connecting/connected/completed/stall/fallback/errors),-//! which lands in the run's file under .graff/traces so an agent can debug a-//! ws turn after the fact; GRAFF_WS_DEBUG=1 additionally dumps the handshake +-//! frames to stderr.+//! tracer ("ws" notes: connecting/connected/reuse (delta)/sent Nb/first frame/+//! completed/send stall/stall/esc/fallback/errors), which lands in the run's+//! file under .graff/traces so an agent can debug a ws turn after the fact;+//! GRAFF_WS_DEBUG=1 additionally dumps the handshake + frames to stderr. The+//! `sent`/`first frame` pair is what makes a hang diagnosable: which of the+//! turn's two halves went quiet is otherwise unrecoverable from the trace+//! (#401).const std = @import("std");const Io = std.Io;@@ -30,8 +33,8 @@ const tty = term.tty;const http = @import("http.zig");const WatchdogFired = http.WatchdogFired;-const streamStallTask = http.streamStallTask;-const headStallTask = http.headStallTask;+const streamStallWatch = http.streamStallWatch;+const deadlineStallTask = http.deadlineStallTask;const watchdogError = http.watchdogError;const isStreamEnd = @import("agent_stream.zig").isStreamEnd;@@ -173,27 +176,51 @@ fn wsConnectTask(gpa: std.mem.Allocator, io: Io, url: []const u8, headers: []conreturn ws.WsClient.connect(gpa, io, url, false, headers);}-/// (#401) Send one ws frame under a deadline. `sendText` is a blocking socket-/// write: on a REUSED codex socket whose peer silently stopped draining — the-/// half-open shape a connection lands in while a tool call runs — the frame-/// fills the kernel send buffer and parks in the syscall until TCP gives up,-/// which is minutes to never. The read loop below was already guarded, so the-/// turn hung with no `stall` note, no `esc` note and no Esc path at all.+/// The deadline for writing a frame of `frame_len` bytes.///-/// Race the write against the same watchdog the SSE send+head uses-/// (agent_stream.zig), so the failure surfaces as error.StreamStalled and-/// request()'s bounded reconnect → WS→SSE ladder recovers. head_stall_ms (not-/// stream_stall_ms) is the right budget: this measures "the frame is not on-/// the wire yet", never "the model is thinking" — that grace lives in the read-/// loop, and the outbound size is already capped by capOversizedToolOutputs.+/// NOT a flat head-sized budget, because the frame most likely to sit under+/// this guard is the LARGEST one: every recovery re-anchors with the full+/// conversation (closeCodexWs nulls codex_prev_id), so the retried frame is the+/// whole history where the delta was a few KB. A flat 30s over a ~1MB re-anchor+/// on a slow uplink is a false positive that costs a transport failure — and+/// two of those latch SSE for the session.+///+/// Policy: start at the head budget (a small frame really must be on the wire in+/// head time) and add one second per 64KB — a ~512 kbit/s floor, far below any+/// link that can carry a codex session — clamped to the read budget so the send+/// guard can never outlast the watchdog that covers the reply.+pub fn sendDeadlineMs(frame_len: usize, head_ms: u64, stream_ms: u64) u64 {+ const grow: u64 = @as(u64, @intCast(frame_len / (64 * 1024))) *| 1000;+ return @min(head_ms +| grow, @max(head_ms, stream_ms));+}++/// Bound the outbound half of a ws turn. `sendText` is a blocking socket write+/// with no deadline: if the peer stops draining, it parks in the syscall until+/// TCP gives up (minutes to never), and nothing polls Esc there either.+///+/// SCOPE — this is NOT the diagnosis for #401. A frame only parks once it+/// exceeds SO_SNDBUF plus the peer's receive window (>=256KB in practice on a+/// TLS WAN socket), and a delta frame at #401's reported scale (~70KB of total+/// conversation, one tool result under the 256KB per-output cap) copies into the+/// socket buffer and returns. What this closes is the rarer, larger case: a+/// full-history re-anchor on a wedged or blackholed socket, where the write+/// genuinely can block forever. #401's own signature is a READ-side stall — see+/// the frames-flowing budget in postResponsesWs.+///+/// A deadline is error.HungRequest, matching the SSE send+head guard it mirrors+/// (agent_stream.zig): postLive counts it as a transport failure, so it retries+/// a fresh socket and latches SSE on the second — WITHOUT spending the read+/// loop's 2-slot stall budget, which StreamStalled would. An Esc is+/// error.Interrupted, which request() never retries.pub fn sendFrameWatched(io: Io, client: *ws.WsClient, frame: []const u8, poll_stdin: bool) !void {+ const budget = sendDeadlineMs(frame.len, http.head_stall_ms, http.stream_stall_ms);const SendDone = union(enum) { sent: ws.Error!void, stall: WatchdogFired };var sd_buf: [2]SendDone = undefined;var ssel: Io.Select(SendDone) = .init(io, &sd_buf);// #56 Fix-B: pool exhausted — never degrade to a bare blocking sendText,// which IS the hang this guard exists for. Fail retryable instead.- ssel.concurrent(.sent, wsSendTask, .{ client, frame }) catch return error.StreamStalled;- ssel.concurrent(.stall, headStallTask, .{ io, poll_stdin }) catch {+ ssel.concurrent(.sent, wsSendTask, .{ client, frame }) catch return error.HungRequest;+ ssel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget }) catch {const r = ssel.await() catch |e| {ssel.cancelDiscard();return e;@@ -210,7 +237,7 @@ pub fn sendFrameWatched(io: Io, client: *ws.WsClient, frame: []const u8, poll_stssel.cancelDiscard();switch (first) {.sent => |s| try s,- .stall => |w| return watchdogError(w, error.StreamStalled),+ .stall => |w| return watchdogError(w, error.HungRequest),}}@@ -226,16 +253,25 @@ fn drainDialSelect(gpa: std.mem.Allocator, sel: anytype) void {};}-/// (#401) Dial under the same deadline as the send. DNS + TCP + the TLS-/// handshake + the blocking 101 status-line read are all unbounded, so a host-/// that accepts the connection but never upgrades would swallow the very retry-/// the send guard triggers — hanging at the "connecting" note instead.+/// Dial under a deadline. DNS + TCP + the TLS handshake + the blocking read of+/// the 101 status line are all unbounded, so a host that accepts the connection+/// but never upgrades would swallow the very retry the other guards trigger —+/// hanging at the "connecting" note instead.+///+/// Budget: the flat head budget, not sendDeadlineMs — a dial carries no payload,+/// so there is nothing to scale by. The one slow step inside is ca_bundle.rescan+/// (a local CA-store scan, tens of ms warm); a machine where that genuinely+/// needs >30s is already failing every HTTPS request in the process.+///+/// error.HungRequest, like the send guard: a failed dial is a transport failure+/// (postLive's ws_transport_failures ladder → one fresh retry, then SSE), never+/// a spend against the read loop's stall budget.pub fn connectWatched(gpa: std.mem.Allocator, io: Io, url: []const u8, headers: []const ws.Header, poll_stdin: bool) !*ws.WsClient {const Dialed = union(enum) { dialed: ws.Error!*ws.WsClient, stall: WatchdogFired };var dl_buf: [2]Dialed = undefined;var dsel: Io.Select(Dialed) = .init(io, &dl_buf);- dsel.concurrent(.dialed, wsConnectTask, .{ gpa, io, url, headers }) catch return error.StreamStalled;- dsel.concurrent(.stall, headStallTask, .{ io, poll_stdin }) catch {+ dsel.concurrent(.dialed, wsConnectTask, .{ gpa, io, url, headers }) catch return error.HungRequest;+ dsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, http.head_stall_ms }) catch {const r = dsel.await() catch |e| {drainDialSelect(gpa, &dsel);return e;@@ -250,10 +286,24 @@ pub fn connectWatched(gpa: std.mem.Allocator, io: Io, url: []const u8, headers:drainDialSelect(gpa, &dsel);switch (first) {.dialed => |d| return d,- .stall => |w| return watchdogError(w, error.StreamStalled),+ .stall => |w| return watchdogError(w, error.HungRequest),}}+/// (reference parity, openai/codex) A cached socket must be liveness-checked+/// before it is reused: codex-rs asks the pooled connection `is_closed()` and+/// dials fresh when its read pump already saw the stream end, rather than+/// sending a turn into a socket it has decided is gone. graff's client is+/// synchronous — there is no background pump to set a "closed" bit — so the+/// equivalent signal is `dead`, which every teardown that touches a SUSPECT+/// socket sets (the send/read errdefer in postResponsesWs, the idle-expiry+/// close, the late-dial drain). A wall-clock idle window alone is not this+/// check: it cannot see a socket the peer or an LB blackholed 30s into a tool+/// call, which is well inside the window.+pub fn wsReusable(client: *const ws.WsClient) bool {+ return !client.dead;+}+/// One Responses turn over ws. Returns the reassembled body as SSE-format/// `data:` lines (parseResponses consumes it unchanged). Connect/transport/// failures return the ws error so postLive can fall back to SSE.@@ -301,13 +351,25 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// (previous_response_id + partial input) is useless on a fresh connection —// return error.CodexWsReanchor so request()'s rebuild: loop rebuilds full// input. A non-delta body is self-contained: just fall through and dial.- if (self.codex_ws != null and codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms)) {- self.closeCodexWs();- if (self.tracer) |tr| {- var nbuf: [64]u8 = undefined;- tr.note("ws", std.fmt.bufPrint(&nbuf, "idle > {d}s — re-anchoring with fresh connection", .{@divTrunc(codex_ws_idle_ms, std.time.ms_per_s)}) catch "idle — re-anchoring with fresh connection");+ //+ // …and the liveness half of the same decision (wsReusable): a socket some+ // earlier path already condemned is never reused, whatever the clock says.+ if (self.codex_ws) |held| {+ const idle = codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms);+ if (idle or !wsReusable(held)) {+ // Both branches hold a SUSPECT socket, so neither may spend a+ // blocking courtesy close frame on it (ws.WsClient.deinit).+ held.dead = true;+ self.closeCodexWs();+ if (self.tracer) |tr| {+ var nbuf: [64]u8 = undefined;+ tr.note("ws", if (idle)+ std.fmt.bufPrint(&nbuf, "idle > {d}s — re-anchoring with fresh connection", .{@divTrunc(codex_ws_idle_ms, std.time.ms_per_s)}) catch "idle — re-anchoring with fresh connection"+ else+ "held socket marked dead — re-anchoring with fresh connection");+ }+ if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) return error.CodexWsReanchor;}- if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) return error.CodexWsReanchor;}// Hold ONE WS across the turn's tool loop (codex-style): the first request// dials; subsequent requests reuse it and send previous_response_id + delta.@@ -334,28 +396,47 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {self.closeCodexWs();}sendFrameWatched(self.io, client, frame, orig_tio != null) catch |e| {- if (e == error.StreamStalled and !main_mod.json_mode) if (self.out) |o| {- o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};- o.flush() catch {};- };- // The trace must never go silent after "reuse (delta)" again (#401).+ // No user-facing "stream stalled — ending turn" line here: a send+ // failure is a TRANSPORT failure (HungRequest), which postLive retries+ // on a fresh socket — the turn is not over.if (self.tracer) |tr| tr.note("ws", switch (e) {- error.StreamStalled => "send stall",+ error.HungRequest => "send stall",error.Interrupted => "esc",else => @errorName(e),});return e;};+ // (#401) The note the reported trace was missing. It splits the turn's two+ // halves in the trace: with it, silence after "reuse (delta)" means the+ // FRAME never went out, and silence after this one means the SERVER went+ // quiet — the distinction that made #401 undiagnosable from its trace.+ if (self.tracer) |tr| {+ var nbuf: [48]u8 = undefined;+ tr.note("ws", std.fmt.bufPrint(&nbuf, "sent {d}b — awaiting frames", .{frame.len}) catch "sent — awaiting frames");+ }var full: Io.Writer.Allocating = .init(gpa);errdefer full.deinit();var fbuf: std.ArrayList(u8) = .empty;defer fbuf.deinit(gpa);+ // (#401) Frames received for THIS response. The read watchdog's budget is a+ // function of it: before the first frame the model may legitimately reason+ // in silence for minutes (the full stream_stall_ms), but once frames have+ // arrived and stopped, that is a dead socket and http_stall.budgetMs+ // tightens to a quarter (#56). The WS reader used to hardcode "no tokens+ // yet", so it re-armed the FULL 120s budget on every frame and never+ // tightened — the SSE reader has always passed a real signal+ // (agent_stream.zig, partial_text.items.len != 0). That is why #401's+ // mid-stream silence sat for 120s per attempt, ~4 minutes before the SSE+ // latch, against successful turns of 3.6-11.6s.+ var frames_seen: usize = 0;stream: while (true) {// Race the frame read against the shared idle-stall watchdog so a dead// ws can't hang the turn — a deadline surfaces as error.StreamStalled- // (never a user Esc), handled identically to the SSE path (#134).+ // (never a user Esc), handled identically to the SSE path (#134). The+ // budget is re-decided every iteration from frames_seen, so silence+ // AFTER frames tightens to a quarter the way SSE's always has (#401).read: {const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };var rd_buf: [2]ReadDone = undefined;@@ -372,7 +453,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {if (self.tracer) |tr| tr.note("ws", "stall");return error.StreamStalled;};- rsel.concurrent(.stall, streamStallTask, .{ self.io, orig_tio != null }) catch {+ rsel.concurrent(.stall, streamStallWatch, .{ self.io, orig_tio != null, frames_seen != 0 }) catch {const r = rsel.await() catch |e| {rsel.cancelDiscard();return e;@@ -398,6 +479,11 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {},}}+ // A frame landed: bytes are flowing, so from here silence is a dead+ // socket rather than a thinking model. Counted before the empty-frame+ // skip below — an empty frame is still evidence the peer is alive.+ frames_seen += 1;+ if (frames_seen == 1) if (self.tracer) |tr| tr.note("ws", "first frame");if (fbuf.items.len == 0) continue :stream;// Wrap the ws frame as an SSE data: line so parseResponses/isStreamEnddiff --git a/src/agent_ws_stall_test.zig b/src/agent_ws_stall_test.zignew file mode 100644index 00000000..b94e8ed5--- /dev/null+++ b/src/agent_ws_stall_test.zig@@ -0,0 +1,498 @@+//! (#401) End-to-end transport tests for the codex WebSocket turn, driven by a+//! loopback WebSocket server that can misbehave on demand. These exercise the+//! REAL production entry point (agent_ws.postResponsesWs) rather than the guard+//! helpers in isolation, because #401's whole lesson was that the call sites and+//! the budgets — not the helpers — were where the turn went silent.+//!+//! The mock is a WS server in the same spirit as the GRAFF_CODEX_URL/lmstudio+//! HTTP mocks: `provider.url` is pointed at 127.0.0.1, wssUrl rewrites it to+//! ws://, and no network, key or provider is involved.++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 trace = @import("trace.zig");+const ws = @import("ws.zig");+const agent_ws = @import("agent_ws.zig");+const Agent = @import("agent.zig").Agent;++fn nowMs(io: Io) i64 {+ return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));+}++const delta_event = "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}";+const completed_event = "{\"type\":\"response.completed\"}";++/// A loopback WebSocket peer with a scripted failure mode.+const Mock = struct {+ const Mode = enum {+ /// Accept the TCP connection and never answer the upgrade — the dial+ /// that hangs before the 101 status line.+ no_upgrade,+ /// Upgrade, then never read again: the client's frame fills the socket+ /// buffers and its write parks in the kernel.+ never_drain,+ /// Upgrade, take the client's frame, answer with ONE delta frame and+ /// then go permanently silent. This is #401's reported signature: the+ /// turn is under way, data flowed, and the server stopped.+ frame_then_silence,+ /// The healthy control: delta, then response.completed.+ frame_then_complete,+ };++ fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {+ const c = server.accept(io) catch return;+ defer c.close(io);+ var rbuf: [8192]u8 = undefined;+ var wbuf: [4096]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);+ if (mode == .no_upgrade) return idle(io, done);++ while (true) {+ const line = sr.interface.takeDelimiterInclusive('\n') catch return idle(io, done);+ if (line.len <= 2) break; // the blank line ends the upgrade request+ }+ sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch return idle(io, done);+ sw.interface.flush() catch return idle(io, done);++ switch (mode) {+ .no_upgrade, .never_drain => {},+ .frame_then_silence, .frame_then_complete => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);+ if (mode == .frame_then_complete)+ writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);+ },+ }+ idle(io, done);+ }++ /// Hold the connection open (and, for never_drain, undrained) until the+ /// test releases it. Closing early would hand the client a clean EOF, which+ /// is a different failure than the silence being reproduced.+ fn idle(io: Io, done: *std.atomic.Value(bool)) void {+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch break;+ }++ /// Consume one masked client frame (RFC 6455 §5.2); the payload is ignored.+ fn readClientFrame(r: *Io.Reader) !void {+ const h = try r.takeArray(2);+ var len: u64 = h[1] & 0x7f;+ if (len == 126) {+ len = std.mem.readInt(u16, try r.takeArray(2), .big);+ } else if (len == 127) {+ len = std.mem.readInt(u64, try r.takeArray(8), .big);+ }+ if ((h[1] & 0x80) != 0) _ = try r.takeArray(4); // mask key+ try r.discardAll(@intCast(len));+ }++ /// One unmasked server->client text frame (payloads here are all < 126 B).+ fn writeTextFrame(w: *Io.Writer, payload: []const u8) !void {+ try w.writeAll(&[_]u8{ 0x81, @intCast(payload.len) });+ try w.writeAll(payload);+ try w.flush();+ }+};++/// A root-shaped Agent pointed at the mock. `out`/`in` stay null: no TTY means+/// no spinner, no Esc poll and no user-facing stall line, so the test observes+/// the transport alone.+fn mockAgent(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: Io, url: []const u8) Agent {+ return .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = undefined, // the WS path never touches the HTTP client+ .provider = .{+ .id = "codex",+ .kind = .responses,+ .auth = .bearer,+ .url = url,+ .api_key = "k",+ .model = "gpt-5",+ .context = 100_000,+ },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "",+ .out = null,+ };+}++fn traced(tw: *Io.Writer.Allocating, needle: []const u8) bool {+ return std.mem.indexOf(u8, tw.written(), needle) != null;+}++// ── the #401 read-side stall ─────────────────────────────────────────────────++// THE #401 regression test.+//+// The reported turn sent a delta over a reused codex WS after a tool result and+// then sat on the thinking indicator until the user interrupted, with a trace+// that stopped dead at "ws reuse (delta)". The read loop WAS watchdogged — but+// it armed http.streamStallTask, which hardcodes tokens_flowing=false, so it+// re-armed the FULL pre-first-token budget (stream_stall_ms, 120s by default) on+// every single frame and never tightened once data was flowing. The SSE reader+// has always passed a real signal (agent_stream.zig: partial_text.items.len+// != 0) and tightens to a quarter. So a server that went quiet mid-response cost+// 120s per attempt — ~4 minutes before the SSE latch — against successful turns+// of 3.6-11.6s, and left nothing in the trace to tell the two halves apart.+//+// Here the mock answers with one delta frame and then goes silent forever. The+// read must give up on the TIGHTENED budget, emit the notes that make the+// signature diagnosable, and tear the session down so request()'s rebuild loop+// re-anchors on a fresh socket.+test "#401: silence after frames trips the tightened read budget, not the full pre-first-token one" {+ 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(Mock.run, .{ io, &server, Mock.Mode.frame_then_silence, &done });+ defer fut.await(io);+ defer done.store(true, .release); // …so the LIFO order is: signal, join, close++ // Scale both regimes down: 2000ms pre-first-token, a quarter (500ms) once+ // frames flow. The 15s floor exists so a small GRAFF_STREAM_STALL_SECS can't+ // kill healthy streams; without shrinking it the two regimes are identical+ // at every duration a test can afford to wait. Both are process-wide.+ const saved_stream = http.stream_stall_ms;+ const saved_floor = http_stall.idle_floor_ms;+ http.stream_stall_ms = 2000;+ http_stall.idle_floor_ms = 100;+ defer http.stream_stall_ms = saved_stream;+ defer http_stall.idle_floor_ms = saved_floor;+ try std.testing.expectEqual(@as(u64, 500), http_stall.budgetMs(http.stream_stall_ms, true));++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tw: Io.Writer.Allocating = .init(gpa);+ defer tw.deinit();+ var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &tw.writer, .start = Io.Timestamp.now(io, .awake) };++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ var agent = mockAgent(gpa, arena, io, url);+ agent.tracer = &tracer;++ // The exact state #401 was reported from: a socket already held across the+ // tool call, so this request takes the reuse (delta) path.+ var ws_url_buf: [64]u8 = undefined;+ const ws_url = try std.fmt.bufPrint(&ws_url_buf, "ws://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ agent.codex_ws = try ws.WsClient.connect(gpa, io, ws_url, false, &.{});+ agent.codex_ws_used_ms = nowMs(io); // fresh: the idle re-anchor must not fire+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ const body = "{\"model\":\"gpt-5\",\"previous_response_id\":\"resp_1\",\"input\":[]}";+ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ try std.testing.expectError(error.StreamStalled, r);+ // The tightened budget: comfortably past 500ms (so the watchdog really ran,+ // rather than an unrelated instant failure) and comfortably short of the+ // 2000ms pre-first-token budget the reader used to re-arm on every frame.+ try std.testing.expect(ms >= 400);+ try std.testing.expect(ms < 1500);++ // …and the trace now names both halves of the turn, so a recurrence is+ // diagnosable instead of being an unexplained gap after "reuse (delta)".+ try std.testing.expect(traced(&tw, "\"detail\":\"reuse (delta)\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"sent "));+ try std.testing.expect(traced(&tw, "\"detail\":\"first frame\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"stall\""));++ // The session is torn down, which is what lets request()'s rebuild loop+ // reconnect with FULL input and no previous_response_id (agent_request.zig).+ try std.testing.expect(agent.codex_ws == null);+ try std.testing.expect(agent.codex_prev_id == null);+ try std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto);+}++// The control for the test above: the same harness, the same tightened budgets,+// a server that actually finishes. Proves the stall is the SERVER's silence and+// not an artifact of the mock or of the frames_seen wiring — and pins the happy+// path's notes, so a future change that stops emitting them is caught here too.+test "#401 control: a mock that completes the response still finishes the turn cleanly" {+ 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);+ var done: std.atomic.Value(bool) = .init(false);+ var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.frame_then_complete, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ const saved_stream = http.stream_stall_ms;+ const saved_floor = http_stall.idle_floor_ms;+ http.stream_stall_ms = 2000;+ 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 tw: Io.Writer.Allocating = .init(gpa);+ defer tw.deinit();+ var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &tw.writer, .start = Io.Timestamp.now(io, .awake) };++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ var agent = mockAgent(gpa, arena, io, url);+ agent.tracer = &tracer;+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ // No held socket: this exercises the fresh-dial path through connectWatched.+ const body = "{\"model\":\"gpt-5\",\"input\":[]}";+ const out = try agent_ws.postResponsesWs(&agent, body);+ defer gpa.free(out);++ try std.testing.expect(std.mem.indexOf(u8, out, delta_event) != null);+ try std.testing.expect(std.mem.indexOf(u8, out, completed_event) != null);+ try std.testing.expect(traced(&tw, "\"detail\":\"connected\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"sent "));+ try std.testing.expect(traced(&tw, "\"detail\":\"first frame\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"completed\""));+ try std.testing.expect(!traced(&tw, "\"detail\":\"stall\""));+ try std.testing.expect(agent.codex_ws != null); // held for the next delta+}++// ── the outbound half: production wiring, not the helper ─────────────────────++// The guard the previous round left untested where it matters. `sendText` is a+// blocking socket write; against a peer that stops draining, a large enough+// frame parks in the kernel until TCP gives up. This drives postResponsesWs+// itself, so it covers the CALL SITE and the errdefer, not just the helper:+// reverting agent_ws.zig's `sendFrameWatched(...)` to a bare+// `try client.sendText(frame)` makes this test hang rather than fail fast.+//+// Note the error: HungRequest, the SSE send+head guard's error, NOT+// StreamStalled. StreamStalled would spend a slot of request()'s 2-slot stall+// budget and PERMANENTLY latch ws_off on the second occurrence; a frame that+// never left the harness is a transport failure, which postLive retries on a+// fresh socket and only then falls back to SSE.+test "#401: a peer that stops draining fails the send fast, tears down, and does not latch the stall budget" {+ if (builtin.os.tag == .windows) return error.SkipZigTest; // loopback buffer sizing is not deterministic there+ 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);+ var done: std.atomic.Value(bool) = .init(false);+ var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.never_drain, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ // sendDeadlineMs scales with the frame, clamped to the read budget — so the+ // read budget is what bounds this 16MB frame's deadline. Shrink both.+ const saved_head = http.head_stall_ms;+ const saved_stream = http.stream_stall_ms;+ http.head_stall_ms = 400;+ http.stream_stall_ms = 1000;+ defer http.head_stall_ms = saved_head;+ defer http.stream_stall_ms = saved_stream;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tw: Io.Writer.Allocating = .init(gpa);+ defer tw.deinit();+ var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &tw.writer, .start = Io.Timestamp.now(io, .awake) };++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ var agent = mockAgent(gpa, arena, io, url);+ agent.tracer = &tracer;+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ // Larger than any plausible loopback send+receive buffer pair, so the write+ // genuinely blocks instead of slipping through. postResponsesWs never parses+ // the body — it only splices it into the response.create envelope.+ const body = try gpa.alloc(u8, 16 * 1024 * 1024);+ defer gpa.free(body);+ @memset(body, 'x');+ @memcpy(body[0.."{\"input\":\"".len], "{\"input\":\"");+ body[body.len - 2] = '"';+ body[body.len - 1] = '}';++ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ try std.testing.expectError(error.HungRequest, r);+ // Whole call, INCLUDING the errdefer's teardown: `dead` is what keeps+ // ws.WsClient.deinit from spending another blocking close-frame write on+ // the same wedged socket and re-hanging the recovery.+ try std.testing.expect(ms < 15_000); // unguarded, this never returned at all+ try std.testing.expect(ms >= 300); // the watchdog fired, not the pool-exhausted shortcut+ try std.testing.expect(traced(&tw, "\"detail\":\"send stall\""));+ try std.testing.expect(agent.codex_ws == null);+}++// Once the send is guarded, the retry it triggers redials — and the dial is+// unbounded too: DNS + TCP + TLS + a blocking read of the 101 status line. A+// host that accepts the connection and never upgrades would swallow the very+// recovery the other guards trigger, hanging at the "connecting" note.+test "#401: a host that accepts but never upgrades fails the dial instead of hanging" {+ 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);+ var done: std.atomic.Value(bool) = .init(false);+ var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.no_upgrade, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ const saved = http.head_stall_ms;+ http.head_stall_ms = 300;+ defer http.head_stall_ms = saved;++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "ws://127.0.0.1:{d}/x", .{server.socket.address.getPort()});++ const t0 = nowMs(io);+ const dialed = agent_ws.connectWatched(gpa, io, url, &.{}, false);+ const ms = nowMs(io) - t0;+ if (dialed) |c| {+ c.dead = true;+ c.deinit(gpa);+ } else |_| {}++ try std.testing.expectError(error.HungRequest, dialed);+ try std.testing.expect(ms < 10_000);+ try std.testing.expect(ms >= 200); // the watchdog, not the pool-exhausted shortcut+}++// ── reference parity: liveness before reuse ──────────────────────────────────++// openai/codex checks `is_closed()` on a pooled WS before reusing it. graff's+// only pre-reuse gate was a 4-minute wall clock, which cannot see a socket the+// peer or an LB blackholed 30 seconds into a tool call — squarely inside the+// window, and squarely #401's shape. `dead` is the synchronous equivalent, and+// this pins that the gate consults it: a condemned socket is re-anchored, never+// sent into. Removing the `or !wsReusable(held)` clause makes this test fail+// with StreamStalled (the turn proceeds and dies in the read loop) instead.+test "#401 parity: a held socket already marked dead is re-anchored, never reused" {+ 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);+ var done: std.atomic.Value(bool) = .init(false);+ var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.frame_then_silence, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ const saved_stream = http.stream_stall_ms;+ const saved_floor = http_stall.idle_floor_ms;+ http.stream_stall_ms = 2000;+ 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 tw: Io.Writer.Allocating = .init(gpa);+ defer tw.deinit();+ var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &tw.writer, .start = Io.Timestamp.now(io, .awake) };++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ var agent = mockAgent(gpa, arena, io, url);+ agent.tracer = &tracer;++ var ws_url_buf: [64]u8 = undefined;+ const ws_url = try std.fmt.bufPrint(&ws_url_buf, "ws://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ const held = try ws.WsClient.connect(gpa, io, ws_url, false, &.{});+ held.dead = true; // some earlier path condemned it+ agent.codex_ws = held;+ agent.codex_ws_used_ms = nowMs(io); // …and the IDLE branch must NOT be what fires+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ const body = "{\"model\":\"gpt-5\",\"previous_response_id\":\"resp_1\",\"input\":[]}";+ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ // A delta body is useless on a fresh connection, so the caller is asked to+ // rebuild full input — the same contract as the idle-expiry branch.+ try std.testing.expectError(error.CodexWsReanchor, r);+ try std.testing.expect(agent.codex_ws == null);+ try std.testing.expect(ms < 1000); // decided up front; no frame was ever sent+ try std.testing.expect(traced(&tw, "\"detail\":\"held socket marked dead"));+ try std.testing.expect(!traced(&tw, "\"detail\":\"idle >"));+ try std.testing.expect(!traced(&tw, "\"detail\":\"sent "));+}++// ── the send-deadline policy ─────────────────────────────────────────────────++// A flat head-sized send deadline is a false-positive generator on exactly the+// frame most likely to sit under it: every recovery re-anchors with the FULL+// conversation, so the retried frame is hundreds of KB where the delta was a+// few. Two such false positives latch SSE for the session, so the budget grows+// with the payload — while still never outlasting the read watchdog.+test "sendDeadlineMs (#401): head budget for a delta, transmit room for a full re-anchor, capped by the read budget" {+ const head: u64 = 30 * 1000;+ const stream: u64 = 120 * 1000;++ // A delta frame keeps the flat head budget: it must be on the wire fast.+ try std.testing.expectEqual(head, agent_ws.sendDeadlineMs(0, head, stream));+ try std.testing.expectEqual(head, agent_ws.sendDeadlineMs(4 * 1024, head, stream));+ try std.testing.expectEqual(head, agent_ws.sendDeadlineMs(64 * 1024 - 1, head, stream));++ // One second per 64KB (~512 kbit/s, far below any link that can carry a+ // codex session): a ~1MB full re-anchor gets 16 extra seconds.+ try std.testing.expectEqual(head + 1000, agent_ws.sendDeadlineMs(64 * 1024, head, stream));+ try std.testing.expectEqual(head + 16_000, agent_ws.sendDeadlineMs(1024 * 1024, head, stream));++ // …but never past the watchdog that covers the reply, however large.+ try std.testing.expectEqual(stream, agent_ws.sendDeadlineMs(64 * 1024 * 1024, head, stream));+ try std.testing.expectEqual(stream, agent_ws.sendDeadlineMs(std.math.maxInt(usize), head, stream));++ // A shrunken read budget (a test, or a low GRAFF_STREAM_STALL_SECS) can+ // never clamp the send below the head budget.+ try std.testing.expectEqual(head, agent_ws.sendDeadlineMs(1024 * 1024, head, 500));+}diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex d776c640..13dbdbd1 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -1,9 +1,6 @@//! Regression tests for Codex WebSocket delta-session re-anchoring.const std = @import("std");-const builtin = @import("builtin");-const Io = std.Io;-const http = @import("http.zig");const Agent = @import("agent.zig").Agent;const textMessage = @import("messages.zig").textMessage;const ws = @import("ws.zig");@@ -344,146 +341,12 @@ test "buildBody (.responses): never emits a top-level max_output_tokens (codex gtry std.testing.expect(std.mem.indexOf(u8, title, "max_output_tokens") == null);}-// ── #401: the WS transport's outbound half ───────────────────────────────────--fn nowMs(io: Io) i64 {- return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));-}--// A loopback listener that completes the upgrade and then stops reading. That-// is the half-open shape a held codex socket lands in while a tool call runs,-// and the one the #401 trace shows: "ws reuse (delta)" and then nothing.-const HalfOpenServer = struct {- fn run(io: Io, server: *std.Io.net.Server, upgrade: bool, done: *std.atomic.Value(bool)) void {- const c = server.accept(io) catch return;- defer c.close(io);- if (upgrade) {- var rbuf: [4096]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);- while (true) {- const line = sr.interface.takeDelimiterInclusive('\n') catch break;- if (line.len <= 2) break; // blank line: end of the upgrade request- }- var wbuf: [256]u8 = undefined;- var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);- sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch {};- sw.interface.flush() catch {};- }- // …and from here never read (or, with upgrade=false, never answer at- // all): the socket stays open and undrained until the test releases it.- while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch break;- }-};--// #401 regression. A main-agent request sent over a REUSED codex WS right after-// a tool result hung forever: `sendText` was a bare blocking socket write with-// no deadline, no Esc poll and no trace note, so a peer that had silently-// stopped draining parked the turn inside the write syscall until TCP gave up-// (minutes to never). The read loop was already watchdogged, which is why the-// trace stopped dead at "reuse (delta)" with no stall/esc/completed note. The-// guarded send must surface error.StreamStalled promptly instead, so-// request()'s bounded reconnect → WS→SSE ladder can recover the turn.-test "sendFrameWatched (#401): a peer that stops draining fails fast instead of hanging" {- // Windows loopback buffer sizing / RST timing is not deterministic enough- // to guarantee the write blocks rather than failing outright (same reason- // the #177 poison test is POSIX-only).- 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, .{});- var done: std.atomic.Value(bool) = .init(false);- var fut = io.async(HalfOpenServer.run, .{ io, &server, true, &done });- defer fut.await(io);- defer done.store(true, .release);- defer server.deinit(io);-- const bound = server.socket.address;- var url_buf: [64]u8 = undefined;- const url = try std.fmt.bufPrint(&url_buf, "ws://127.0.0.1:{d}/x", .{bound.getPort()});- const client = try ws.WsClient.connect(gpa, io, url, false, &.{});-- // head_stall_ms is shared with the SSE head path — restore it or every- // later test in this binary inherits a 300ms budget.- const saved = http.head_stall_ms;- http.head_stall_ms = 300;- defer http.head_stall_ms = saved;-- // Bigger than any plausible loopback send+receive buffer, so the write- // really blocks in the kernel instead of slipping through.- const big = try gpa.alloc(u8, 16 * 1024 * 1024);- defer gpa.free(big);- @memset(big, 'x');-- const t0 = nowMs(io);- const sent = agent_ws.sendFrameWatched(io, client, big, false);- const send_ms = nowMs(io) - t0;-- // …and the recovery must not re-hang: deinit's courtesy close frame is- // another blocking write on the same wedged socket, so `dead` skips it.- const t1 = nowMs(io);- client.dead = true;- client.deinit(gpa);- const close_ms = nowMs(io) - t1;-- try std.testing.expectError(error.StreamStalled, sent);- try std.testing.expect(send_ms < 10_000); // before the fix this never returned at all- // …and it was the WATCHDOG that ended it, not the pool-exhausted shortcut- // (which also returns StreamStalled, instantly, and would pass vacuously).- try std.testing.expect(send_ms >= 200);- try std.testing.expect(close_ms < 5_000);-}--// #401 (F3). Once the send is guarded, the retry it triggers redials — and the-// dial was unbounded too: DNS + TCP + TLS + a blocking read of the 101 status-// line. A host that accepts the connection but never upgrades would hang at the-// "connecting" note and swallow the recovery. Same watchdog, same error, so-// request()'s stall budget applies and the second failure latches SSE.-test "connectWatched (#401): a host that accepts but never upgrades times out" {- 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, .{});- var done: std.atomic.Value(bool) = .init(false);- var fut = io.async(HalfOpenServer.run, .{ io, &server, false, &done });- defer fut.await(io);- defer done.store(true, .release);- defer server.deinit(io);-- const bound = server.socket.address;- var url_buf: [64]u8 = undefined;- const url = try std.fmt.bufPrint(&url_buf, "ws://127.0.0.1:{d}/x", .{bound.getPort()});-- const saved = http.head_stall_ms;- http.head_stall_ms = 300;- defer http.head_stall_ms = saved;-- const t0 = nowMs(io);- const dialed = agent_ws.connectWatched(gpa, io, url, &.{}, false);- const dial_ms = nowMs(io) - t0;- if (dialed) |c| {- c.dead = true;- c.deinit(gpa);- } else |_| {}-- try std.testing.expectError(error.StreamStalled, dialed);- try std.testing.expect(dial_ms < 10_000);- try std.testing.expect(dial_ms >= 200); // the watchdog fired, not the pool-exhausted shortcut-}--// #134's classification, pinned for the two arms #401 adds. A wedged send is a-// harness stall (the turn reconnects, and mainloop records it as "response-// ended early"), never "[response interrupted by user]"; a real Esc during the-// send — which was inert before #401, since nothing polled stdin there — must-// stay a deliberate interrupt that request()'s retry loop refuses to retry.-test "the #401 send/dial guards classify a deadline as a stall and an Esc as an interrupt" {- try std.testing.expect(http.watchdogError(.deadline, error.StreamStalled) == error.StreamStalled);- try std.testing.expect(http.watchdogError(.deadline, error.StreamStalled) != error.Interrupted);- try std.testing.expect(http.watchdogError(.esc, error.StreamStalled) == error.Interrupted);- // The send budget is the head budget, not the pre-first-token stream budget:- // it measures "the frame is not on the wire yet", not "the model is slow".- try std.testing.expect(http.head_stall_ms < http.stream_stall_ms);+// #401's transport tests (mock-WS end-to-end) live in agent_ws_stall_test.zig:+// they need a loopback WebSocket server and a real Agent, which is more harness+// than this file's pure-decision tests carry. main.zig's test root is AT the+// 600-line cap, so that module is hooked transitively through this one, which is+// already on the root chain (reference_zig_test_wiring: a module with no path to+// the root compiles but never runs a single test).+comptime {+ _ = @import("agent_ws_stall_test.zig");}diff --git a/src/http.zig b/src/http.zigindex d85fdfa9..5f3863e0 100644--- a/src/http.zig+++ b/src/http.zig@@ -231,19 +231,16 @@ fn postWatchdog(io: Io) WatchdogFired {// A streaming response idle THIS LONG (not total response time — the watchdog// resets its clock on every line, so it measures the gap between tokens/-// keep-alives/reasoning deltas) is a dead or hung connection, so a turn can't-// wait forever. 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 (wired in-// session_run.setupSkillsAndTheme), which scales both regimes. Giving up here-// is error.StreamStalled — a harness stall, NEVER a user Esc (#134).+// 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).pub var stream_stall_ms: u64 = 120 * 1000;-/// A response head (HTTP status line + headers) idle this long means the server-/// accepted the connection but isn't responding — common right after a-/// keep-alive drop that caused an HttpConnectionClosing retry. Shorter than-/// stream_stall_ms because the head should arrive in milliseconds; any delay-/// past this is a stall, not a slow model. Mutable so a test can shrink it.+/// A response head idle this long = the server accepted the connection but is+/// not answering (common right after a keep-alive drop). Mutable so a test can+/// shrink it; anything that does must restore it (shared process-wide).pub var head_stall_ms: u64 = 30 * 1000;/// Retry policy for request() after a failed attempt. Transport flakes@@ -319,13 +316,11 @@ pub fn streamStallTask(io: Io, poll_stdin: bool) WatchdogFired {return streamStallWatch(io, poll_stdin, false);}-/// Select-arm wrapper: fires after head_stall_ms (head receive stall), or-/// early on Esc. Races postStream's send + receiveHead so a freshly-redialed-/// connection that the server accepts but never answers can't hang the turn-/// (the root cause of the "retrying (1/3)" → "thinking… forever" bug).-pub fn headStallTask(io: Io, poll_stdin: bool) WatchdogFired {+/// Select-arm wrapper: fires after `budget_ms` of silence, or early on Esc.+/// Parameterized so a payload-sized deadline (agent_ws.sendDeadlineMs) shares it.+pub fn deadlineStallTask(io: Io, poll_stdin: bool, budget_ms: u64) WatchdogFired {var waited: u64 = 0;- while (waited < head_stall_ms) {+ while (waited < budget_ms) {io.sleep(.fromMilliseconds(50), .awake) catch return .deadline;waited += 50;if (poll_stdin and Agent.drainSteerStdin(true)) {@@ -337,6 +332,12 @@ pub fn headStallTask(io: Io, poll_stdin: bool) WatchdogFired {return .deadline;}+/// Races postStream's send + receiveHead so a redialed connection the server+/// accepts but never answers can't hang the turn ("retrying (1/3)" → forever).+pub fn headStallTask(io: Io, poll_stdin: bool) WatchdogFired {+ return deadlineStallTask(io, poll_stdin, head_stall_ms);+}+/// Select-arm wrapper for `post` (pins the member type to anyerror![]u8).fn postTask(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8) anyerror![]u8 {return post(gpa, client, provider, body);diff --git a/src/http_stall.zig b/src/http_stall.zigindex 42efaf8e..db36903a 100644--- a/src/http_stall.zig+++ b/src/http_stall.zig@@ -16,7 +16,10 @@ const idle_divisor: u64 = 4;/// ...but never below this, so a small GRAFF_STREAM_STALL_SECS cannot shrink/// the between-lines budget to a couple of seconds and start killing healthy/// streams. Clamped to the configured budget, which always wins when smaller.-const idle_floor_ms: u64 = 15 * 1000;+/// Mutable ONLY so a test can exercise the two regimes apart without sleeping+/// through a real 15s floor; production never writes it. A test that shrinks it+/// must restore it (process-wide, shared with every later test in the binary).+pub var idle_floor_ms: u64 = 15 * 1000;/// How long a stream read may sit silent before the watchdog calls it dead./// `base_ms` is the configured budget (http.stream_stall_ms); `tokens_flowing`