graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(retry): gateway body-parse retry after timeouts; attribute retry notes
justrach168234978e01
diff --git a/src/agent_request.zig b/src/agent_request.zigindex 23cecb16..7b0ea782 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -104,6 +104,17 @@ fn showRecoveredTransportRetry(kind: run_budget_mod.CallKind) bool {return kind != .recap;}+/// #gateway-forensics: retry trace notes used to be anonymous — attributing a+/// 5xx to the subagent that drew it required ms-arithmetic across api spans+/// (one parallel-subagent session drew three 5xx retries; none said who).+/// Tag the agent label into the note detail. REPL lines stay unchanged; the+/// record is serialized synchronously inside note(), so arena scratch is safe.+fn retryNote(self: *Agent, what: []const u8) void {+ const tr = self.tracer orelse return;+ const detail = std.fmt.allocPrint(self.arena, "{s} [{s}]", .{ what, self.label }) catch what;+ tr.note("retry", detail);+}+/// #390 — appended once, on the run's final admitted model call, right where/// the tools disappear, so the model knows WHY and lands instead of retrying.pub const landing_note =@@ -216,6 +227,11 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {var server_retries: usize = 0; // #opencode-parity: bounded retries for a transient in-stream server overloadvar openai404_retries: usize = 0; // #opencode-parity: bounded retries for OpenAI's spurious model 404sconst max_openai404_retries: usize = 2;+ // #gateway-artifact: timeout history for THIS request, so a body-parse+ // rejection arriving right after a timeout run can be recognized as a+ // gateway answering from a half-recovered state instead of a real 400.+ var transport_timeouts: usize = 0;+ var gateway_parse_retries: usize = 0;rebuild: while (true) {const live = !self.sub and self.out != null and !self.stream_quiet;self.streamed_text = false;@@ -357,7 +373,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// OpenRouter and similar include user ids, BYOK/settings// URLs, and routing docs. Classifiers still read g_5xx_body_buf.try self.say("[{s}{s} — retrying in {d}s ({d}/{d})]\n", .{ what, ra_note, delay_ms / 1000, attempt + 1, max_attempts });- if (self.tracer) |tr| tr.note("retry", what);+ retryNote(self, what);self.sleepInterruptible(delay_ms) catch return error.Interrupted;} else {// Transport flake (HttpConnectionClosing, a reset,@@ -372,7 +388,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// Same trace breadcrumb the 429/5xx branch leaves: a// transport-flake retry is otherwise invisible in the// session trace, hiding how flaky a provider really is.- if (self.tracer) |tr| tr.note("retry", @errorName(err));+ retryNote(self, @errorName(err));+ if (err == error.Timeout) transport_timeouts += 1; // #gateway-artifactself.sleepInterruptible(delay_ms) catch return error.Interrupted;}continue;@@ -464,6 +481,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// response.failed arm too. Keep it on the same bounded// overload retry path as SSE and JSON error envelopes.if (try retryTransientServerError(self, "", failure.code, msg, &server_retries)) continue :rebuild;+ if (try policy.retryBodyParseAfterTimeouts(self, msg, transport_timeouts, &gateway_parse_retries)) continue :rebuild; // #gateway-artifactif (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("codex api error: {s}", .{msg});return error.ApiError;@@ -484,6 +502,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: streamed error event overflow (by code or phrasing) → trim + retryif (try retryTransientServerError(self, etype, ecode, emsg, &server_retries)) continue; // #opencode-parity: transient server overload → retry+ if (try policy.retryBodyParseAfterTimeouts(self, emsg, transport_timeouts, &gateway_parse_retries)) continue; // #gateway-artifactif (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });return error.ApiError;@@ -513,6 +532,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: {"type":"error"} overflow (by code or phrasing) → trim + retryif (try retryTransientServerError(self, etype, ecode, emsg, &server_retries)) continue; // #opencode-parity: transient server overload → retry+ if (try policy.retryBodyParseAfterTimeouts(self, emsg, transport_timeouts, &gateway_parse_retries)) continue; // #gateway-artifactif (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });return error.ApiError;@@ -556,6 +576,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {// local provider whose message text we don't match on still recovers.if (recoverContextOverflow(self, msg, errorCode(root), &context_retried)) continue;if (try retryTransientServerError(self, "", errorCode(root), msg, &server_retries)) continue; // #opencode-parity: transient server overload → retry, not hard-fail+ if (try policy.retryBodyParseAfterTimeouts(self, msg, transport_timeouts, &gateway_parse_retries)) continue; // #gateway-artifactif (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error: {s}", .{msg});return error.ApiError;diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex f63983d8..813e4cd0 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -391,6 +391,54 @@ pub fn retryTransientServerError(self: *Agent, etype: []const u8, code: ?[]constreturn true;}+/// #gateway-artifact: a 4xx whose body rejects the REQUEST BODY as unparseable+/// JSON ("Body must be valid JSON", "Malformed JSON in request body", ...) is a+/// real client bug — unless the same attempt-sequence just endured consecutive+/// transport timeouts. The body bytes do not change between attempts, so they+/// cannot become invalid mid-turn; a gateway answering from a half-recovered+/// state (redeploy, failover, reset pool) is the likelier story. Matched from+/// the message so any vendor phrasing of the same rejection classifies alike.+pub fn isBodyParseRejection(msg: []const u8) bool {+ const pairs = [_][2][]const u8{+ .{ "json", "body" },+ .{ "json", "parse" },+ .{ "json", "parsing" },+ .{ "parse", "request" },+ };+ for (pairs) |pair| {+ if (util.indexOfIgnoreCase(msg, pair[0]) != null and+ util.indexOfIgnoreCase(msg, pair[1]) != null) return true;+ }+ return false;+}++pub const min_timeout_history_for_parse_retry: usize = 2; // a lone timeout is not a pattern+pub const max_gateway_parse_retries: usize = 2; // then surface the provider's message++/// Gate (pure, testable): a body-parse rejection is retried only when THIS+/// request already hit enough transport timeouts to indict the gateway and the+/// bounded retry budget is not spent. Without the timeout history it stays a+/// fail-fast 400, exactly as before.+pub fn shouldRetryBodyParseAfterTimeouts(msg: []const u8, transport_timeouts: usize, retries: usize) bool {+ if (transport_timeouts < min_timeout_history_for_parse_retry) return false;+ if (retries >= max_gateway_parse_retries) return false;+ return isBodyParseRejection(msg);+}++/// The gate on the Agent: announce, trace, back off (1·2s — the gateway just+/// answered, give it a beat), clear partial text for a fresh re-stream, and+/// tell the caller to `continue`. Esc during the backoff still propagates.+pub fn retryBodyParseAfterTimeouts(self: *Agent, msg: []const u8, transport_timeouts: usize, retries: *usize) !bool {+ if (!shouldRetryBodyParseAfterTimeouts(msg, transport_timeouts, retries.*)) return false;+ retries.* += 1;+ self.partial_text.clearRetainingCapacity(); // fresh re-stream after the retry, no concat+ const delay_ms = RetryPlan.delayMs(true, retries.* - 1); // 1·2s+ try self.say("[gateway answered after {d} timeouts with a body-parse rejection — retrying in {d}s ({d}/{d})]\n", .{ transport_timeouts, delay_ms / 1000, retries.*, max_gateway_parse_retries });+ if (self.tracer) |tr| tr.note("retry", "body-parse rejection after transport timeouts (gateway artifact?)");+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;+ return true;+}+/// SSE keep-alive-only body: every non-blank line is an SSE comment (':' prefix)/// — OpenRouter's ": OPENROUTER PROCESSING" queue pings. No data events ever/// arrived, so the stream reassembler returns null and the plain-JSON fallback@@ -592,3 +640,27 @@ pub fn handOffExhaustedPlan(self: *Agent) bool {) catch {};return true;}++test "isBodyParseRejection (#gateway-artifact): body-parse phrasings match, unrelated 400s do not" {+ try std.testing.expect(isBodyParseRejection("Body must be valid JSON"));+ try std.testing.expect(isBodyParseRejection("Malformed JSON in request body"));+ try std.testing.expect(isBodyParseRejection("We could not parse the JSON body of your request."));+ try std.testing.expect(isBodyParseRejection("failed to parse the request"));+ // not a body-parse rejection: model-capability / billing / content errors+ try std.testing.expect(!isBodyParseRejection("response_format json_schema is not supported by this model"));+ try std.testing.expect(!isBodyParseRejection("messages: text content blocks must be non-empty"));+ try std.testing.expect(!isBodyParseRejection("Your credit balance is too low to use this model"));+ try std.testing.expect(!isBodyParseRejection(""));+}++test "shouldRetryBodyParseAfterTimeouts (#gateway-artifact): timeout history gates it, budget bounds it" {+ // a lone timeout (or none) before the 400 -> real client bug, fail fast+ try std.testing.expect(!shouldRetryBodyParseAfterTimeouts("Body must be valid JSON", 0, 0));+ try std.testing.expect(!shouldRetryBodyParseAfterTimeouts("Body must be valid JSON", 1, 0));+ // 3 timeouts then the rejection (the 2026-08-29 glm/codegraff incident shape) -> retry+ try std.testing.expect(shouldRetryBodyParseAfterTimeouts("Body must be valid JSON", 3, 0));+ // budget spent -> surface the provider's message instead of looping+ try std.testing.expect(!shouldRetryBodyParseAfterTimeouts("Body must be valid JSON", 3, max_gateway_parse_retries));+ // an unrelated message never retries, however many timeouts preceded it+ try std.testing.expect(!shouldRetryBodyParseAfterTimeouts("quota exceeded", 5, 0));+}