graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): key the WS stall budget on output text, not frame arrival (#401)
Rach Pradhan93aaa4c5a400
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 82bf1bd2..64a6dafd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,22 +15,26 @@ current is part of cutting a release.- Codex WebSocket turns no longer sit silent for minutes when the backend goesquiet 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).+ frame and never tightened once the model was actually emitting — the SSE+ reader has always tightened to a quarter. Silence after visible output text+ now trips in ~30s, while a silent reasoning phase keeps the full budget,+ exactly as on SSE: the signal is the same `response.output_text.delta` the SSE+ reader keys on, not mere frame arrival, because the protocol events land+ milliseconds after the send and would otherwise stall out a long thinking+ turn. The trace gains `sent <n>b`, `first frame` and `first output text`+ 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 liveduring both. They report the transport-flake error the SSE guard uses, so awedged socket is retried on a fresh one rather than spending the turn's stallbudget; 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. Both guards name themselves in- the trace (`send stall` / `connect stall`), so a stalled dial is no longer- reported as a bare error name. A failed WS handshake no longer leaks its fd- and CA bundle.+ re-anchor is not a false positive. When the Io pool is exhausted both fail+ retryable instead of degrading to an unwatched blocking call, and both name+ themselves in the trace (`send stall` / `connect stall`), so a stalled dial is+ no longer reported as a bare error name. A socket the idle window condemns is+ torn down with a plain FIN rather than a courtesy close frame that could block+ again, and a failed WS handshake no longer leaks its fd and CA bundle.## v0.0.237 (2026-08-04)diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 16e655d3..864a46e3 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -11,12 +11,11 @@//!//! Observability (issue #134's ask): every ws lifecycle step is routed to the//! 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).+//! first output text/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 (#401).const std = @import("std");const Io = std.Io;@@ -178,17 +177,14 @@ fn wsConnectTask(gpa: std.mem.Allocator, io: Io, url: []const u8, headers: []con/// The deadline for writing a frame of `frame_len` bytes.///-/// 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.+/// NOT a flat head-sized budget: the frame most likely to sit under this guard+/// is the LARGEST one, because every recovery re-anchors with the full+/// conversation (closeCodexWs nulls codex_prev_id). A flat 30s over a ~1MB+/// re-anchor on a slow uplink is a false positive costing a transport failure,+/// and two of those latch SSE for the session. Policy: the head budget plus 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 covering 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));@@ -205,28 +201,28 @@ pub fn sendDeadlineMs(frame_len: usize, head_ms: u64, stream_ms: u64) u64 {/// 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.+/// the output-text 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.+/// loop's 2-slot stall budget, which StreamStalled would. Esc is Interrupted.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.HungRequest;- ssel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget }) catch {- const r = ssel.await() catch |e| {- ssel.cancelDiscard();- return e;- };- ssel.cancelDiscard();- return r.sent;+ // which IS the hang this guard exists for; fail retryable (HungRequest) the+ // way the SSE head guard does. The WATCHDOG is spawned FIRST so that stays+ // possible on the SECOND spawn too: once an unbounded blocking write is in+ // flight, the only way out of this function is to join it — #401's hang+ // through a different door. Watchdog-first leaves every failure with+ // nothing running, or only a cancellable sleeper to unwind.+ ssel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget }) catch return error.HungRequest;+ ssel.concurrent(.sent, wsSendTask, .{ client, frame }) catch {+ ssel.cancelDiscard(); // only the sleeper is running; it unwinds at once+ return error.HungRequest;};const first = ssel.await() catch |e| {ssel.cancelDiscard();@@ -258,26 +254,21 @@ fn drainDialSelect(gpa: std.mem.Allocator, sel: anytype) void {/// 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.+/// Budget: the flat head budget, not sendDeadlineMs — a dial carries no payload+/// to scale by. 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.HungRequest;- dsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, http.head_stall_ms }) catch {- const r = dsel.await() catch |e| {- drainDialSelect(gpa, &dsel);- return e;- };+ // Watchdog first, then the dial — same #56 Fix-B reasoning as+ // sendFrameWatched: neither spawn failure may leave an unwatched blocking+ // call, and an in-flight dial can only be unwound by joining it.+ dsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, http.head_stall_ms }) catch return error.HungRequest;+ dsel.concurrent(.dialed, wsConnectTask, .{ gpa, io, url, headers }) catch {drainDialSelect(gpa, &dsel);- return r.dialed;+ return error.HungRequest;};const first = dsel.await() catch |e| {drainDialSelect(gpa, &dsel);@@ -290,18 +281,74 @@ pub fn connectWatched(gpa: std.mem.Allocator, io: Io, url: []const u8, headers:}}-/// (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;+// (reference parity, openai/codex) A pre-reuse LIVENESS CHECK is deliberately+// NOT implemented; this is the record of why, since the gap is real.+//+// codex-rs asks a pooled connection `is_closed()` before reusing it. That bit+// exists because a BACKGROUND READ PUMP is already draining the socket, so the+// stream end has been observed by the time the next turn asks. graff's ws+// client is synchronous — nothing has touched the socket since the last turn+// ended — so there is no observation to consult, and every substitute is worse+// than the gap:+//+// * A `dead` flag on the held client is unreachable by construction: every+// path that sets it destroys the client on the next statement+// (drainDialSelect, the idle-expiry close, postResponsesWs's errdefer, all+// funnelling through closeCodexWs, which deinits it and nulls+// agent.codex_ws). A still-referenced held client can never carry it, so+// the branch would be dead code claiming to be a check. An earlier round of+// this fix shipped exactly that; it is deleted rather than left to read+// like coverage. `dead` keeps its real job: suppressing deinit's blocking+// courtesy close frame on a socket that already wedged us.+// * A zero-timeout poll for readability cannot see the case that matters — a+// peer or LB that BLACKHOLES the socket sends nothing, so the fd looks+// exactly like a healthy idle one. What it WOULD see is a routine+// between-turns server ping or a partial TLS record, and read them as+// "closed", trading a healthy session's prompt-cache anchor for a+// full-history re-anchor. A false positive here is expensive.+// * A blocking peek is #401's hang, moved earlier in the turn.+//+// So the held socket is written into on faith and DETECTION is the pair of+// deadlines this file adds: sendFrameWatched bounds the write into a wedged+// socket, and the read watchdog bounds the silence after it. A dead reused+// socket costs one bounded round trip plus a re-anchor instead of an unbounded+// hang — what `is_closed()` buys, one turn later.++/// (#401) Does this ws frame carry VISIBLE OUTPUT TEXT — the WS side of the+/// SSE reader's tokens-flowing signal?+///+/// It must mean EXACTLY what the SSE signal means, because both feed the same+/// http_stall.budgetMs. SSE passes `self.partial_text.items.len != 0`, and+/// partial_text grows in exactly one place for `.responses` (agent_stream.zig,+/// streamSseLine): a `response.output_text.delta` whose `delta` is a non-empty+/// string. Reasoning deltas are handled ABOVE that arm's `if (text.len == 0)+/// return;` and never reach the append, so a silent reasoning phase keeps the+/// FULL pre-first-token budget on SSE — deliberately, since it legitimately+/// runs minutes. `response.output_item.done` carries the finished text and also+/// never touches partial_text. Both are excluded here for the same reason.+///+/// Frame ARRIVAL is not that signal: response.created / response.in_progress /+/// response.output_item.added land within milliseconds of the send, long before+/// the model has thought (and ping/pong never surfaces from readMessage at+/// all). Keying the budget on "a frame landed" tightens every WS turn to a+/// quarter budget from ~100ms in, so a high-effort turn reasoning silently past+/// that is killed as a stall, re-sent as a full re-anchor, stalled again, and+/// latched off WS for the session — while the identical turn survives on SSE.+///+/// Shape mirrors isStreamEnd: a cheap substring candidate, then an+/// authoritative parse, so a reasoning delta that merely QUOTES the event name+/// is not mistaken for one. Called only until it first returns true.+pub fn frameHasOutputText(gpa: std.mem.Allocator, frame: []const u8) bool {+ const ev = "response.output_text.delta";+ if (std.mem.indexOf(u8, frame, ev) == null) return false;+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const v = std.json.parseFromSliceLeaky(std.json.Value, scratch.allocator(), frame, .{ .allocate = .alloc_always }) catch return false;+ if (v != .object) return false;+ const ty = v.object.get("type") orelse return false;+ if (ty != .string or !std.mem.eql(u8, ty.string, ev)) return false;+ const d = v.object.get("delta") orelse return false;+ return d == .string and d.string.len != 0;}/// One Responses turn over ws. Returns the reassembled body as SSE-format@@ -352,21 +399,19 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// return error.CodexWsReanchor so request()'s rebuild: loop rebuilds full// input. A non-delta body is self-contained: just fall through and dial.//- // …and the liveness half of the same decision (wsReusable): a socket some- // earlier path already condemned is never reused, whatever the clock says.+ // This CLOCK is the only pre-send gate there is — see the liveness note+ // above for why a real is_closed() equivalent is not available here, and+ // which deadlines cover the socket it cannot judge.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).+ if (codexWsIdleExpired(nowAwakeMs(self.io), self.codex_ws_used_ms)) {+ // The premise of this branch is that the server has likely already+ // killed this socket, so it is SUSPECT: it must not 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");+ 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");}if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) return error.CodexWsReanchor;}@@ -425,24 +470,28 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {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.+ // (#401) Frames received for THIS response — the OBSERVABILITY counter,+ // used only for the "first frame" trace note that splits a hung turn into+ // its two halves.var frames_seen: usize = 0;+ // (#401) …and, separately, whether VISIBLE OUTPUT TEXT has arrived — THIS is+ // what the read watchdog's budget keys on. Before the first token the model+ // may legitimately reason in silence for minutes (the full stream_stall_ms);+ // once text has flowed 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 — 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. frameHasOutputText mirrors the SSE reader's signal exactly.+ var text_seen = false;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). 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).+ // budget is re-decided every iteration from text_seen, so silence AFTER+ // OUTPUT TEXT tightens to a quarter the way SSE's always has, and a+ // silent reasoning phase keeps the full budget the way SSE's does (#401).read: {const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };var rd_buf: [2]ReadDone = undefined;@@ -459,7 +508,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {if (self.tracer) |tr| tr.note("ws", "stall");return error.StreamStalled;};- rsel.concurrent(.stall, streamStallWatch, .{ self.io, orig_tio != null, frames_seen != 0 }) catch {+ rsel.concurrent(.stall, streamStallWatch, .{ self.io, orig_tio != null, text_seen }) catch {const r = rsel.await() catch |e| {rsel.cancelDiscard();return e;@@ -485,12 +534,19 @@ 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.+ // A frame landed. This only feeds the trace note — it is NOT the budget+ // signal (the first frames of a turn are protocol events that arrive+ // before the model has thought). 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;+ // …and THIS is the budget signal: visible output text, the same event+ // that grows partial_text on SSE. Checked only until it first fires.+ if (!text_seen and frameHasOutputText(gpa, fbuf.items)) {+ text_seen = true;+ if (self.tracer) |tr| tr.note("ws", "first output text — tightening stall budget");+ }// Wrap the ws frame as an SSE data: line so parseResponses/isStreamEnd// (shared with the SSE path) handle reassembly + completion.diff --git a/src/agent_ws_stall_test.zig b/src/agent_ws_stall_test.zigindex 2b2fd164..d6589fbe 100644--- a/src/agent_ws_stall_test.zig+++ b/src/agent_ws_stall_test.zig@@ -2,10 +2,9 @@//! 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 in the same spirit as the GRAFF_CODEX_URL/lmstudio HTTP mocks:-//! `provider.url` points at 127.0.0.1 and no network, key or provider is used.+//! the budgets — not the helpers — were where the turn went silent. The mock is+//! in the same spirit as the GRAFF_CODEX_URL/lmstudio HTTP mocks: `provider.url`+//! points at 127.0.0.1, and no network, key or provider is used.const std = @import("std");const builtin = @import("builtin");@@ -25,6 +24,16 @@ fn nowMs(io: Io) i64 {const delta_event = "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}";const completed_event = "{\"type\":\"response.completed\"}";+/// What the backend actually puts on the socket in the first milliseconds after+/// a send, before the model has produced anything: the two protocol events, then+/// a reasoning delta. None of these grows partial_text on the SSE path, so none+/// may tighten the WS read budget either.+const protocol_events = [_][]const u8{+ "{\"type\":\"response.created\",\"response\":{\"id\":\"r1\"}}",+ "{\"type\":\"response.in_progress\",\"response\":{\"id\":\"r1\"}}",+ "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"thinking\"}",+};+/// A loopback WebSocket peer with a scripted failure mode.const Mock = struct {const Mode = enum {@@ -40,6 +49,10 @@ const Mock = struct {frame_then_silence,/// The healthy control: delta, then response.completed.frame_then_complete,+ /// Upgrade, take the client's frame, answer with `protocol_events` and+ /// then go quiet while the model "thinks". Frames flow, none of them is+ /// output text — so the budget must stay at the pre-first-token value.+ protocol_then_silence,};fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {@@ -66,13 +79,18 @@ const Mock = struct {if (mode == .frame_then_complete)writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);},+ .protocol_then_silence => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ for (protocol_events) |ev|+ writeTextFrame(&sw.interface, ev) 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.+ /// Hold the connection open (and, for never_drain, undrained) until the test+ /// releases it. Closing early hands the client a clean EOF, 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;}@@ -98,9 +116,8 @@ const Mock = struct {}};-/// 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.+/// 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 — the transport alone.fn mockAgent(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: Io, url: []const u8) Agent {return .{.gpa = gpa,@@ -134,14 +151,13 @@ fn traced(tw: *Io.Writer.Allocating, needle: []const u8) bool {// The reported turn sent a delta over a reused codex WS after a tool result, sat// on the thinking indicator until the user interrupted, and left 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 (120s) on every frame and never-// tightened once data flowed; the SSE reader has always passed a real signal+// armed a hardcoded tokens_flowing=false, so it re-armed the FULL+// pre-first-token budget (120s) on every frame and never tightened once VISIBLE+// OUTPUT TEXT flowed; the SSE reader has always passed a real signal// (agent_stream.zig: partial_text.items.len != 0) and tightens to a quarter.-//-// Here the mock answers 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() re-anchors.+// Here the mock answers one output_text delta 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() re-anchors.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;@@ -219,9 +235,8 @@ test "#401: silence after frames trips the tightened read budget, not the full ptry std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto);}-// The control for the test above: same harness, same tightened budgets, a-// server that finishes. Proves the stall is the SERVER's silence, not the mock-// or the frames_seen wiring — and pins the happy path's notes.+// The control: same harness, same tightened budgets, a server that finishes.+// Proves the stall is the SERVER's silence, not the mock — and pins the notes.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;@@ -275,17 +290,82 @@ test "#401 control: a mock that completes the response still finishes the turn ctry std.testing.expect(agent.codex_ws != null); // held for the next delta}+// The other half of the budget signal, and the round-2 regression it pins.+//+// `frames_seen != 0` was not SSE parity: the backend answers a send with+// response.created / response.in_progress within milliseconds, tightening the+// budget to a quarter before the model has thought — so a silent reasoning phase+// longer than that became a stall, a full re-anchor, a second stall, and a+// permanent ws_off latch, while the identical turn survives on SSE. This mock+// sends exactly those events plus a reasoning delta and then goes quiet: at+// 500ms tightened vs 2000ms pre-first-token, the turn must outlive the tightened+// budget. Reverting the watchdog arg to `frames_seen != 0` fails this at+// `ms >= 1500`. The FIRST test in this file is the paired positive case.+test "#401: protocol and reasoning frames do NOT tighten the read budget (SSE parity)" {+ 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.protocol_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;+ 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;+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ const body = "{\"model\":\"gpt-5\",\"input\":[]}";+ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ // It still ends as a stall — nothing here is unbounded — but on the FULL+ // pre-first-token budget, which is what a thinking model is entitled to.+ try std.testing.expectError(error.StreamStalled, r);+ try std.testing.expect(ms >= 1500); // the tightened 500ms budget was NOT used+ try std.testing.expect(ms < 6000); // …and the full one still bounds it+ // Frames DID arrive (so this is a budget decision, not a dead mock) and none+ // of them counted as output text.+ try std.testing.expect(traced(&tw, "\"detail\":\"first frame\""));+ try std.testing.expect(!traced(&tw, "\"detail\":\"first output text"));+}+// ── 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, so-// it covers the CALL SITE and the errdefer, not just the helper: reverting-// `sendFrameWatched(...)` to a bare `try client.sendText(frame)` hangs it.-//-// The error is HungRequest, the SSE send+head guard's error, NOT StreamStalled —-// which 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 is a transport+// `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, so it covers the CALL SITE and the errdefer, not just the+// helper: reverting it to a bare `try client.sendText(frame)` hangs. The error+// is HungRequest, the SSE send+head guard's error, NOT StreamStalled — which+// 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 is a transport// failure: postLive retries 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@@ -352,14 +432,12 @@ test "#401: a peer that stops draining fails the send fast, tears down, and doestry 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 and never upgrades would swallow the very recovery the-// other guards trigger, hanging at the "connecting" note. This drives-// postResponsesWs, so it covers the CALL SITE and its trace note — the half the-// previous round left untested, and the half that was wrong: the note matched-// error.StreamStalled, which connectWatched no longer returns, so a stalled-// dial traced a bare "HungRequest". A bare ws.WsClient.connect hangs this test.+// The dial is unbounded too: DNS + TCP + TLS + a blocking read of the 101 status+// line. A host that accepts and never upgrades would swallow the very recovery+// the other guards trigger, hanging at the "connecting" note. This drives+// postResponsesWs, so it covers the CALL SITE and its trace note — which was+// wrong: it matched error.StreamStalled, which connectWatched no longer returns,+// so a stalled dial traced a bare "HungRequest". A bare connect hangs this test.test "#401: a stalled dial fails the turn fast and traces `connect stall` (production call site)" {if (builtin.os.tag == .windows) return error.SkipZigTest;const gpa = std.testing.allocator;@@ -413,104 +491,6 @@ test "#401: a stalled dial fails the turn fast and traces `connect stall` (produtry std.testing.expect(agent.codex_ws == null);}-// ── 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-// blackholed 30s into a tool call — inside the window, and #401's shape. `dead`-// is the synchronous equivalent; removing the `or !wsReusable(held)` clause-// makes this test fail with StreamStalled (the turn dies in the read loop).-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));-}-// ── teardown: a suspect socket gets a FIN, not a courtesy close frame ────────// How the client ended the connection, as seen from the other side.@@ -518,9 +498,9 @@ const saw_nothing: u8 = 0;const saw_close_frame: u8 = 1;const saw_fin: u8 = 2;-/// Complete the upgrade, then classify the next thing the client does: a ws-/// close frame (opcode 0x8) or EOF. `deinit` normally writes a courtesy close-/// frame — one more BLOCKING write on a socket that may be what wedged us.+/// Complete the upgrade, then classify the next thing the client does: a ws close+/// frame (opcode 0x8) or EOF. `deinit` normally writes a courtesy close frame —+/// one more BLOCKING write on a socket that may be what wedged us.fn closeObserver(io: Io, server: *std.Io.net.Server, seen: *std.atomic.Value(u8), done: *std.atomic.Value(bool)) void {const c = server.accept(io) catch return;defer c.close(io);diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 13dbdbd1..c58ba118 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -341,6 +341,60 @@ 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 exact SSE-parity boundary. `frames_seen != 0` was NOT this: it+// went true on response.created, milliseconds after the send, so the tightened+// 30s budget covered the whole silent reasoning phase — which SSE gives the full+// 120s. Everything in `quiet` below leaves the pre-first-token budget standing.+test "#401: only a visible output-text delta is the tokens-flowing signal (SSE parity)" {+ const gpa = std.testing.allocator;+ const quiet = [_][]const u8{+ "{\"type\":\"response.created\",\"response\":{}}", // protocol events: the+ "{\"type\":\"response.in_progress\",\"response\":{}}", // model has not+ "{\"type\":\"response.output_item.added\",\"output_index\":0}", // thought yet+ "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"hmm\"}", // never feeds partial_text+ // …nor does one that merely QUOTES the event name: the cheap substring+ // pre-filter must not be what decides.+ "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"response.output_text.delta\"}",+ "{\"type\":\"response.output_item.done\",\"item\":{\"content\":[{\"text\":\"hi\"}]}}", // carries text, but SSE ignores it too+ "{\"type\":\"response.output_text.delta\",\"delta\":\"\"}", // SSE's `text.len == 0` gate+ "{\"type\":\"response.completed\"}",+ "not json",+ "",+ };+ for (quiet) |f| try std.testing.expect(!agent_ws.frameHasOutputText(gpa, f));+ // …and the one thing that IS the signal, whatever the key order.+ try std.testing.expect(agent_ws.frameHasOutputText(gpa, "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}"));+ try std.testing.expect(agent_ws.frameHasOutputText(gpa, "{\"seq\":3,\"delta\":\"h\",\"type\":\"response.output_text.delta\"}"));+}++// 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));+}+// #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 thediff --git a/src/http.zig b/src/http.zigindex 5f3863e0..e6c441aa 100644--- a/src/http.zig+++ b/src/http.zig@@ -311,11 +311,6 @@ pub fn streamStallWatch(io: Io, poll_stdin: bool, tokens_flowing: bool) Watchdogreturn .deadline;}-/// Pre-first-token arm: the codex WS reader has no per-read token signal (#56).-pub fn streamStallTask(io: Io, poll_stdin: bool) WatchdogFired {- return streamStallWatch(io, poll_stdin, false);-}-/// 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 {