Skip to content

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

Python

fix(agent): honor provider Retry-After on 429/503 backoff (opencode parity)

Rach Pradhanb064b7b31b39
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 158a92fa..42f2cc26 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -385,12 +385,17 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
const max_attempts: usize = RetryPlan.maxAttempts(throttled);
if (attempt < max_attempts) {
if (throttled) {
- const delay_ms = RetryPlan.delayMs(throttled, attempt);
+ // #retry-after: prefer the provider's Retry-After
+ // (429/503) over our computed backoff, capped — like
+ // opencode, so we wait exactly as long as the server asked.
+ const server_ra = main_mod.g_retry_after_ms;
+ const delay_ms = if (server_ra > 0) server_ra else RetryPlan.delayMs(throttled, attempt);
+ const ra_note: []const u8 = if (server_ra > 0) " (server retry-after)" else "";
const what: []const u8 = if (err == error.RateLimited) "rate limited (429)" else "server error (5xx)";
if (main_mod.g_5xx_body_len > 0) {
- try self.say("[{s} — retrying in {d}s ({d}/{d})] {s}\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] });
+ try self.say("[{s}{s} — retrying in {d}s ({d}/{d})] {s}\n", .{ what, ra_note, delay_ms / 1000, attempt + 1, max_attempts, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] });
} else {
- try self.say("[{s} — retrying in {d}s ({d}/{d})]\n", .{ what, delay_ms / 1000, attempt + 1, max_attempts });
+ 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", if (main_mod.g_5xx_body_len > 0) main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] else what);
self.sleepInterruptible(delay_ms) catch return error.Interrupted;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 43aa81e9..6c49289d 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -301,6 +301,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// off and retries (surfaced in the trace as a "retry" note).
const status_code = @intFromEnum(response.head.status);
if (status_code == 429 or status_code >= 500) {
+ http.captureRetryAfter(&response); // #retry-after: honor the provider's requested backoff
// Drain a snippet of the error body so the retry message can
// surface the gateway's diagnostic (e.g. "upstream timeout")
// instead of a bare "server error (5xx)".
diff --git a/src/http.zig b/src/http.zig
index 9b13a53e..054db681 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -94,6 +94,50 @@ pub fn capture5xxBodyStream(gpa: Allocator, response: *std.http.Client.Response)
}
}
+/// Max backoff we honor from a provider's Retry-After (429/503), mirroring
+/// opencode's default cap. A larger server value is clamped to this.
+pub const retry_after_cap_ms: u64 = 30_000;
+
+/// Pure: resolve Retry-After headers to a backoff in ms (0 = none/unparseable).
+/// Prefers the millisecond form (`retry-after-ms`, which Anthropic/OpenAI send on
+/// 429s); `retry-after` is integer seconds — the HTTP-date form is ignored (0),
+/// falling back to our own exponential backoff. Capped at retry_after_cap_ms.
+pub fn retryAfterMs(retry_after: ?[]const u8, retry_after_ms: ?[]const u8) u64 {
+ if (retry_after_ms) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |ms| return @min(ms, retry_after_cap_ms) else |_| {}
+ }
+ if (retry_after) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| return @min(secs *| 1000, retry_after_cap_ms) else |_| {}
+ }
+ return 0;
+}
+
+/// Capture a 429/503 response's Retry-After into g_retry_after_ms so request()'s
+/// throttle backoff waits exactly as long as the server asked (#retry-after).
+pub fn captureRetryAfter(response: *std.http.Client.Response) void {
+ var ra: ?[]const u8 = null;
+ var ra_ms: ?[]const u8 = null;
+ var it = response.head.iterateHeaders();
+ while (it.next()) |h| {
+ if (std.ascii.eqlIgnoreCase(h.name, "retry-after")) {
+ ra = h.value;
+ } else if (std.ascii.eqlIgnoreCase(h.name, "retry-after-ms")) {
+ ra_ms = h.value;
+ }
+ }
+ root.g_retry_after_ms = retryAfterMs(ra, ra_ms);
+}
+
+test "retryAfterMs: seconds, ms preferred, cap, HTTP-date/none -> 0 (#retry-after)" {
+ try std.testing.expectEqual(@as(u64, 5000), retryAfterMs("5", null)); // integer seconds
+ try std.testing.expectEqual(@as(u64, 1500), retryAfterMs(null, "1500")); // millisecond form
+ try std.testing.expectEqual(@as(u64, 1500), retryAfterMs("60", "1500")); // ms preferred over seconds
+ try std.testing.expectEqual(@as(u64, retry_after_cap_ms), retryAfterMs("120", null)); // 120s clamped to 30s
+ try std.testing.expectEqual(@as(u64, 3000), retryAfterMs(" 3 ", null)); // whitespace-trimmed
+ try std.testing.expectEqual(@as(u64, 0), retryAfterMs(null, null)); // no header -> our backoff
+ try std.testing.expectEqual(@as(u64, 0), retryAfterMs("Wed, 21 Oct 2025 07:28:00 GMT", null)); // HTTP-date form ignored
+}
+
/// POST the request body; returns the raw response body (caller frees).
/// Built on client.request, NOT client.fetch: fetch never exposes the
/// Request, so a failed body send could not be poisoned — std re-pooled the
@@ -140,6 +184,7 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co
if (code == 429 or code >= 500) {
// Drain a snippet of the error body for the retry message, then
// poison: the connection still holds unread body bytes.
+ captureRetryAfter(&response); // #retry-after: honor the provider's requested backoff
capture5xxBodyStream(gpa, &response);
if (req.connection) |conn| conn.closing = true;
return if (code == 429) error.RateLimited else error.ServerError;
diff --git a/src/main.zig b/src/main.zig
index 15fcd185..f5544e06 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -222,6 +222,7 @@ pub var g_thinking_fold_request: bool = false; // Ctrl-T in escPressed → fold/
pub var g_thinking_open: bool = false; // a live Thinking block is on screen (gates the mouse-click fold, #92)
pub var g_5xx_body_buf: [600]u8 = undefined; // snippet of the last 5xx/429 error body
pub var g_5xx_body_len: usize = 0; // 0 = no body captured
+pub var g_retry_after_ms: u64 = 0; // #retry-after: provider Retry-After (429/503) in ms, honored by request()'s throttle backoff; 0 = use our computed backoff
// fillCompletions/wrapAt/LineRender/parseDsrCol live in input_util.zig.
// Terminal primitives (Windows console shim + cross-platform raw-mode tty layer + size/poll/row-count helpers) live in term.zig; tty is aliased back so call sites stay unqualified.
const terminal = @import("term.zig");