Skip to content

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

Python

fix(codex): never replay a WS delta body over SSE + preemptive idle re-anchor

justrach03bcea6c6a82
diff --git a/src/agent.zig b/src/agent.zig
index 63b781c5..7b4e5da0 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -99,6 +99,7 @@ pub const Agent = struct {
codex_ws: ?*ws.WsClient = null,
codex_prev_id: ?[]const u8 = null, // last response.id (gpa-owned); null = re-anchor with full input
codex_sent_upto: usize = 0, // messages the server already holds; delta = messages[codex_sent_upto..]
+ codex_ws_used_ms: i64 = 0, // .awake-clock ms of the WS's last successful use; gates the idle preemptive re-anchor (#codex-ws)
sub: bool,
label: []const u8,
out: ?*Io.Writer,
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index f1a0d162..903dafc0 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -43,6 +43,11 @@ const ToolOutput = tools_mod.ToolOutput;
const subagent = @import("subagent.zig");
const judgeTask = subagent.judgeTask;
+const provider_mod = @import("provider.zig"); // codex-ws regression tests below
+const Provider = provider_mod.Provider;
+const ws = @import("ws.zig");
+const agent_ws = @import("agent_ws.zig"); // codexWsIdleExpired/codex_ws_idle_ms (#codex-ws)
+
/// Run the configured --eval scoring command, append the result to the
/// scores log (.graff/eval-log.tsv), and return a verdict for the model:
/// score (0-100), best so far, target, and whether the target is met. The
@@ -472,6 +477,90 @@ test "closeCodexWs resets the delta session state + frees the response id (codex
try std.testing.expect(agent.codex_ws == null);
}
+// (#codex-ws) The delta-body detection string check in agent_ws.zig's
+// postLive() gates the WS-reanchor path (never SSE-replay a delta): it
+// looks for the literal `"previous_response_id"` key that buildBody's
+// .responses branch emits. Pin the exact substring so the two stay in
+// sync — a future rename of the JSON key on either side breaks this test
+// instead of silently reopening the SSE-replay bug.
+test "postLive's delta-body detection matches the key buildBody emits (codex-ws)" {
+ const delta_body = "{\"model\":\"gpt-5\",\"previous_response_id\":\"resp_1\",\"input\":[]}";
+ const full_body = "{\"model\":\"gpt-5\",\"input\":[]}";
+ try std.testing.expect(std.mem.indexOf(u8, delta_body, "\"previous_response_id\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, full_body, "\"previous_response_id\"") == null);
+}
+
+// (#codex-ws) The preemptive idle re-anchor decision (postResponsesWs closes a
+// held WS the server has likely already killed instead of eating a failed
+// round trip). Pure helper so no socket is needed: exactly-at-limit must NOT
+// expire (only strictly past it), and a WS used moments ago must survive.
+// opencode pools at 5 min; ours defaults to 4 (the backend killed a real
+// session within 8.5 min idle).
+test "codexWsIdleExpired: fires only strictly past the idle limit (codex-ws)" {
+ const limit = agent_ws.codex_ws_idle_ms;
+ try std.testing.expectEqual(@as(i64, 4 * std.time.ms_per_min), limit); // default: stay under the observed server kill
+ try std.testing.expect(!agent_ws.codexWsIdleExpired(1_000_000, 1_000_000)); // just used
+ try std.testing.expect(!agent_ws.codexWsIdleExpired(1_000_000 + limit, 1_000_000)); // exactly at the limit — keep
+ try std.testing.expect(agent_ws.codexWsIdleExpired(1_000_000 + limit + 1, 1_000_000)); // past it — re-anchor
+ try std.testing.expect(agent_ws.codexWsIdleExpired(1_000_000 + 510 * std.time.ms_per_s, 1_000_000)); // the real 8.5-min trace gap
+}
+
+// (#codex-ws) End-to-end regression for the reanchor fix: buildBody's
+// .responses branch must emit previous_response_id + a message-slice delta
+// while a WS session + prev id are held, and after closeCodexWs (called by
+// postLive on a delta transport error, and again by request()'s
+// error.CodexWsReanchor handler) a rebuilt body must carry the FULL
+// message history with no previous_response_id — never a stale delta
+// replayed against a dead session.
+test "buildBody (.responses): delta while WS live; full input after closeCodexWs (codex-ws)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try textMessage(a, "user", "first"));
+ try msgs.append(try textMessage(a, "assistant", "second"));
+ try msgs.append(try textMessage(a, "user", "third — not yet sent"));
+
+ var dummy_ws: ws.WsClient = undefined; // buildBody only checks != null, never dereferences
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = a,
+ .io = undefined, // unused by buildBody
+ .client = undefined, // unused by buildBody
+ .provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://x/responses", .api_key = "k", .model = "gpt-5", .context = 100_000 },
+ .messages = msgs,
+ .sub = false,
+ .label = "",
+ .out = null,
+ .codex_ws = &dummy_ws,
+ .codex_prev_id = try std.testing.allocator.dupe(u8, "resp_live"),
+ .codex_sent_upto = 2, // server already holds messages[0..2]; delta = [2..]
+ };
+
+ const delta_body = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(delta_body);
+ try std.testing.expect(std.mem.indexOf(u8, delta_body, "\"previous_response_id\":\"resp_live\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, delta_body, "third — not yet sent") != null);
+ try std.testing.expect(std.mem.indexOf(u8, delta_body, "\"first\"") == null); // NOT resent — already on the server
+
+ // Simulate closeCodexWs's effect (covered by its own unit test above)
+ // without invoking it directly: it would call ws.WsClient.deinit on
+ // codex_ws, which sends a real close frame over `dummy_ws`'s
+ // uninitialized io/fd — fine for a live connection, unsafe for this
+ // struct-literal stand-in. What matters here is buildBody's behavior
+ // given the post-close state postLive/request() leave it in.
+ std.testing.allocator.free(agent.codex_prev_id.?);
+ agent.codex_ws = null;
+ agent.codex_prev_id = null;
+ agent.codex_sent_upto = 0;
+ const rebuilt_body = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(rebuilt_body);
+ try std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "\"previous_response_id\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "\"first\"") != null); // full history restored
+ try std.testing.expect(std.mem.indexOf(u8, rebuilt_body, "third — not yet sent") != null);
+}
+
test "emergencyCutIndex: cuts at a clean user turn at/after the midpoint" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 40d56140..d4d45091 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -92,7 +92,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// #124: reclaim last request's transient parse garbage. Safe: all scratch data
// is consumed within a request(); messages/todos/prompts live on the session arena.
if (self.scratch_arena) |sa| _ = sa.reset(.retain_capacity);
- while (true) {
+ rebuild: while (true) {
const live = !self.sub and self.out != null and !self.stream_quiet;
self.streamed_text = false;
self.streamed_args = .none;
@@ -143,6 +143,11 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
if (self.tracer) |tr| tr.note("stream_dropped", self.last_api_error.?);
return error.StreamDropped;
}
+ // (#codex-ws) postLive already closed the dead WS session —
+ // rebuild (full input, no previous_response_id) + retry via
+ // a fresh WS instead of replaying the stale delta over SSE.
+ // codex_prev_id is now null, so this can't recur this request.
+ if (err == error.CodexWsReanchor) continue :rebuild;
// 429/5xx: the server asked us to back off — wait
// (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few
// more attempts than a plain transport flake gets.
@@ -207,6 +212,17 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
return obj;
},
.err => |msg| {
+ // (#codex-ws) Belt-and-braces mirror of openai/codex: server
+ // rejected previous_response_id (stale WS session it no
+ // longer recognizes) — close it and retry once with full
+ // input. Gated on codex_prev_id != null (a delta was
+ // actually sent); it's null after the retry, so this can't
+ // loop for this request.
+ if (self.codex_prev_id != null and std.mem.indexOf(u8, msg, "previous_response_id") != null) {
+ self.closeCodexWs();
+ if (self.tracer) |tr| tr.note("ws", "server rejected previous_response_id — re-anchoring with full input");
+ continue :rebuild;
+ }
if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("codex api error: {s}", .{msg});
return error.ApiError;
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 2574be5a..8f912931 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -44,6 +44,27 @@ pub fn wsEligible(self: *Agent) bool {
self.provider.kind == .responses and self.out != null and !self.stream_quiet;
}
+/// (#codex-ws) Client-side idle limit on the held codex WS, opencode's
+/// OpenAIWebSocketPool design: never reuse a socket the server may already
+/// have killed. A real trace showed the backend closing ours somewhere
+/// within 8.5 min idle (user parked on an ask_user prompt) — 4 min stays
+/// comfortably under (opencode uses 5). Overridable via
+/// GRAFF_CODEX_WS_IDLE_SECS (parsed in session_run.zig beside the other
+/// codex transport knobs).
+pub var codex_ws_idle_ms: i64 = 4 * std.time.ms_per_min;
+
+/// (#codex-ws) The idle-reanchor decision, pure so the regression test can
+/// exercise it without a socket: has the held WS sat unused past the limit?
+pub fn codexWsIdleExpired(now_ms: i64, used_ms: i64) bool {
+ return now_ms - used_ms > codex_ws_idle_ms;
+}
+
+/// The .awake monotonic clock in ms — same time source as request()'s
+/// latency measurement, so codex_ws_used_ms compares consistently.
+fn nowAwakeMs(io: Io) i64 {
+ return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));
+}
+
/// Transport selector: try ws for eligible codex turns, else SSE (postStream).
/// A ws transport/handshake failure disables ws for the session and falls back
/// to SSE; a deliberate Esc/stall propagates unchanged.
@@ -70,6 +91,21 @@ pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
if (!wsEligible(self)) return if (self.ws_off) postStreamFresh(self, body) else self.postStream(body);
return postResponsesWs(self, body) catch |e| {
if (e == error.Interrupted or e == error.StreamStalled) return e;
+ // (#codex-ws) A delta body carries previous_response_id + only the new
+ // messages, anchored to the WS session that just died — the codex HTTP
+ // endpoint rejects previous_response_id outright ("Unsupported
+ // parameter"), and even if it didn't, the referenced response died with
+ // the socket. Never replay it over SSE. closeCodexWs's errdefer inside
+ // postResponsesWs already reset codex_ws/codex_prev_id/codex_sent_upto by
+ // the time we get here; call it again defensively (idempotent) so a
+ // rebuilt body definitely carries full input with no prior-id, and ask
+ // request() to rebuild + retry (a fresh WS re-anchors with full history)
+ // instead of falling back to a stale SSE replay.
+ if (std.mem.indexOf(u8, body, "\"previous_response_id\"") != null) {
+ self.closeCodexWs();
+ if (self.tracer) |tr| tr.note("ws", "reuse failed — re-anchoring with full input");
+ return error.CodexWsReanchor;
+ }
self.ws_off = true;
if (self.tracer) |tr| tr.note("ws", "transport error — falling back to fresh-client SSE for this session");
return postStreamFresh(self, body);
@@ -134,6 +170,22 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
defer self.spinnerStop();
if (self.tracer) |tr| tr.note("ws", "connecting");
+ // (#codex-ws) Preemptive idle re-anchor: don't reuse a WS the server has
+ // likely already killed (it closes idle sockets well before our reuse in a
+ // real trace) — that costs a failed round trip before the reactive
+ // CodexWsReanchor path kicks in. Close it up front instead. Subtlety: the
+ // body was already built while codex_ws was non-null, so a DELTA body
+ // (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");
+ }
+ 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.
// The open connection IS the sticky context (no x-codex-turn-state to echo).
@@ -142,6 +194,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
if (self.tracer) |tr| tr.note("ws", @errorName(e));
return e;
};
+ self.codex_ws_used_ms = nowAwakeMs(self.io); // fresh socket = fresh idle window (#codex-ws)
if (self.tracer) |tr| tr.note("ws", "connected");
} else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");
const client = self.codex_ws.?;
@@ -215,6 +268,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
}
if (orig_tio != null and escPressed(true)) return error.Interrupted;
}
+ self.codex_ws_used_ms = nowAwakeMs(self.io); // completed turn — restart the idle window (#codex-ws)
return full.toOwnedSlice();
}
diff --git a/src/cli.zig b/src/cli.zig
index ed24c2b6..64a8038f 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -21,6 +21,11 @@ const harness_version = root.harness_version;
pub const changelog_text =
\\What's new
\\──────────
+ \\0.0.200
+ \\ • Codex WS delta bodies are never replayed over SSE — fixes "Unsupported parameter: previous_response_id" after a long idle
+ \\ • The held codex WS now re-anchors preemptively after 4 min idle (GRAFF_CODEX_WS_IDLE_SECS to tune) instead of eating a dead-socket round trip
+ \\ • A server-side previous_response_id rejection now self-heals with one full-input retry
+ \\
\\0.0.192
\\ • The REPL prompt now shows color-coded reasoning and active mode badges
\\ • PTY debugging can script commands, keys, assertions, and terminal dimensions
diff --git a/src/session_run.zig b/src/session_run.zig
index a59732e9..9b12fb4f 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -30,6 +30,7 @@ const approvals_mod = @import("approvals.zig");
const tools_mod = @import("tools.zig");
const http = @import("http.zig");
const ws = @import("ws.zig");
+const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -358,6 +359,15 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
if (environ_map.get("GRAFF_CODEX_WS")) |v| {
main_mod.g_codex_ws = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
}
+ // (#codex-ws) GRAFF_CODEX_WS_IDLE_SECS raises/lowers the held-WS idle limit
+ // (default 4 min — the backend killed ours within 8.5 min idle; opencode
+ // pools at 5). Mirrors GRAFF_STREAM_STALL_SECS above: seconds, ignored if
+ // unparseable or 0, clamped to <=1 day.
+ if (environ_map.get("GRAFF_CODEX_WS_IDLE_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) agent_ws.codex_ws_idle_ms = @intCast(@min(secs, 86_400) * 1000);
+ } else |_| {}
+ }
ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;
// GRAFF_WS_FORCE_FAIL_ONCE=1|true|on|yes arms the one-shot forced WS
// connect failure (integration-test seam for the SSE fallback + ws_off