Skip to content

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

Python

fix(codex): put the WS send and dial under the stall watchdog (#401)

Rach Pradhan6a1f8d8b41c0
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 389c68ea..fc6ef1e7 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -31,6 +31,7 @@ const tty = term.tty;
const http = @import("http.zig");
const WatchdogFired = http.WatchdogFired;
const streamStallTask = http.streamStallTask;
+const headStallTask = http.headStallTask;
const watchdogError = http.watchdogError;
const isStreamEnd = @import("agent_stream.zig").isStreamEnd;
@@ -164,6 +165,95 @@ fn wsReadTask(client: *ws.WsClient, gpa: std.mem.Allocator, out: *std.ArrayList(
return client.readMessage(gpa, out);
}
+fn wsSendTask(client: *ws.WsClient, frame: []const u8) ws.Error!void {
+ return client.sendText(frame);
+}
+
+fn wsConnectTask(gpa: std.mem.Allocator, io: Io, url: []const u8, headers: []const ws.Header) ws.Error!*ws.WsClient {
+ return 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.
+///
+/// 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.
+pub fn sendFrameWatched(io: Io, client: *ws.WsClient, frame: []const u8, poll_stdin: bool) !void {
+ 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 {
+ const r = ssel.await() catch |e| {
+ ssel.cancelDiscard();
+ return e;
+ };
+ ssel.cancelDiscard();
+ return r.sent;
+ };
+ const first = ssel.await() catch |e| {
+ ssel.cancelDiscard();
+ return e;
+ };
+ // cancelDiscard (not cancel): the send arm returns void, and the
+ // synchronous join is what keeps the borrowed `frame`/`client` alive.
+ ssel.cancelDiscard();
+ switch (first) {
+ .sent => |s| try s,
+ .stall => |w| return watchdogError(w, error.StreamStalled),
+ }
+}
+
+/// Cancel the remaining dial arms, closing a socket that finished connecting
+/// after the watchdog fired — cancelDiscard would leak the client and its fd.
+fn drainDialSelect(gpa: std.mem.Allocator, sel: anytype) void {
+ while (sel.cancel()) |late| switch (late) {
+ .dialed => |d| if (d) |c| {
+ c.dead = true; // the peer just proved it is wedged; don't block on a close frame
+ c.deinit(gpa);
+ } else |_| {},
+ .stall => {},
+ };
+}
+
+/// (#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.
+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 {
+ const r = dsel.await() catch |e| {
+ drainDialSelect(gpa, &dsel);
+ return e;
+ };
+ drainDialSelect(gpa, &dsel);
+ return r.dialed;
+ };
+ const first = dsel.await() catch |e| {
+ drainDialSelect(gpa, &dsel);
+ return e;
+ };
+ drainDialSelect(gpa, &dsel);
+ switch (first) {
+ .dialed => |d| return d,
+ .stall => |w| return watchdogError(w, error.StreamStalled),
+ }
+}
+
/// 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.
@@ -223,8 +313,12 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
// dials; subsequent requests reuse it and send previous_response_id + delta.
// The open connection IS the sticky context (no x-codex-turn-state to echo).
if (self.codex_ws == null) {
- self.codex_ws = ws.WsClient.connect(gpa, self.io, url, false, &headers) catch |e| {
- if (self.tracer) |tr| tr.note("ws", @errorName(e));
+ self.codex_ws = connectWatched(gpa, self.io, url, &headers, orig_tio != null) catch |e| {
+ if (self.tracer) |tr| tr.note("ws", switch (e) {
+ error.StreamStalled => "connect stall",
+ error.Interrupted => "esc",
+ else => @errorName(e),
+ });
return e;
};
self.codex_ws_used_ms = nowAwakeMs(self.io); // fresh socket = fresh idle window (#codex-ws)
@@ -233,8 +327,25 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
const client = self.codex_ws.?;
// Any error → close + reset the session so the next request re-anchors (fresh
// WS full history, or SSE fallback via postLive's ws_off path). Never leaks.
- errdefer self.closeCodexWs();
- try client.sendText(frame);
+ // (#401) …and mark it dead first: deinit's courtesy close frame is another
+ // blocking write on a socket that may be exactly what wedged us.
+ errdefer {
+ if (self.codex_ws) |c| c.dead = true;
+ 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).
+ if (self.tracer) |tr| tr.note("ws", switch (e) {
+ error.StreamStalled => "send stall",
+ error.Interrupted => "esc",
+ else => @errorName(e),
+ });
+ return e;
+ };
var full: Io.Writer.Allocating = .init(gpa);
errdefer full.deinit();
diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zig
index 2a3f0ce1..d776c640 100644
--- a/src/agent_ws_test.zig
+++ b/src/agent_ws_test.zig
@@ -1,6 +1,9 @@
//! 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");
@@ -340,3 +343,147 @@ test "buildBody (.responses): never emits a top-level max_output_tokens (codex g
defer std.testing.allocator.free(title);
try 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);
+}
diff --git a/src/http.zig b/src/http.zig
index b1e3e95e..d85fdfa9 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -239,12 +239,12 @@ fn postWatchdog(io: Io) WatchdogFired {
// is error.StreamStalled — a harness stall, 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.
-const head_stall_ms: u64 = 30 * 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.
+pub var head_stall_ms: u64 = 30 * 1000;
/// Retry policy for request() after a failed attempt. Transport flakes
/// (HttpConnectionClosing / WriteFailed / reset / truncated TLS) are now far
diff --git a/src/ws.zig b/src/ws.zig
index 2a6571f6..186fa5af 100644
--- a/src/ws.zig
+++ b/src/ws.zig
@@ -79,6 +79,11 @@ pub const WsClient = struct {
ca_bundle: std.crypto.Certificate.Bundle = .empty,
ca_lock: Io.RwLock = .init,
gpa: Allocator,
+ /// (#401) The peer is wedged or gone — tear down with a plain FIN instead
+ /// of deinit's courtesy close frame, which is another blocking write on the
+ /// very socket that just proved it won't drain (it would re-hang the
+ /// recovery path that is trying to abandon this connection).
+ dead: bool = false,
sock_rbuf: [sock_buf_cap]u8 = undefined,
sock_wbuf: [sock_buf_cap]u8 = undefined,
tls_rbuf: [tls_buf_cap]u8 = undefined,
@@ -118,6 +123,13 @@ pub const WsClient = struct {
self.* = .{ .io = io, .stream = stream, .rd = undefined, .wr = undefined, .gpa = gpa };
self.rd = net.Stream.Reader.init(stream, io, &self.sock_rbuf);
self.wr = net.Stream.Writer.init(stream, io, &self.sock_wbuf);
+ // From here the client owns the socket (and, for wss, the CA bundle):
+ // release both if the TLS or upgrade handshake fails, or every failed
+ // dial leaks an fd — which #401's reconnect ladder now retries into.
+ errdefer {
+ self.ca_bundle.deinit(gpa);
+ self.stream.close(io);
+ }
if (u.tls) {
var entropy: [tls.Client.Options.entropy_len]u8 = undefined;
@@ -154,7 +166,7 @@ pub const WsClient = struct {
}
pub fn deinit(self: *WsClient, gpa: Allocator) void {
- self.sendFrame(.close, "") catch {};
+ if (!self.dead) self.sendFrame(.close, "") catch {}; // (#401) see `dead`
self.ca_bundle.deinit(gpa);
self.stream.close(self.io);
gpa.destroy(self);