Skip to content

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

Python

compaction: recover rejected encrypted state

justrach7d672d59a7ab
diff --git a/src/agent_gateway_retry.zig b/src/agent_gateway_retry.zig
index 6d32a6be..ec311663 100644
--- a/src/agent_gateway_retry.zig
+++ b/src/agent_gateway_retry.zig
@@ -95,7 +95,8 @@ pub fn afterServerErrorOrParseReject(self: *Agent, etype: []const u8, code: ?[]c
// its diagnostic also mentions capacity or a request-body parse error,
// or a ChatGPT plan code OpenAI says to stop on, such as a spent allowance
// whose message says "try again later" (ADR 0221).
- if (isModelUnavailable(code) or isStructuredOverflow(code) or quota.isPlanStop(code)) return false;
+ if (isModelUnavailable(code) or isStructuredOverflow(code) or quota.isPlanStop(code) or
+ @import("compaction_window.zig").rejectedByProvider(msg, code)) return false;
if (try retryTransientServerError(self, etype, code, msg, server_retries)) return true;
if (try retryShortGatewayFlake(self, etype, code, msg, server_retries)) return true;
return retryBodyParseAfterTimeouts(self, msg, state);
@@ -337,6 +338,22 @@ test "structured context overflow wins over gateway flake wording" {
try std.testing.expect(isShortGatewayFlake("invalid_request_error", null, "Body must be valid JSON"));
}
+test "rejected encrypted state bypasses every generic retry ladder" {
+ var agent: Agent = undefined; // the terminal guard returns before touching it
+ var retries: usize = 0;
+ var state: GatewayRetryState = .{ .transport_timeouts = 3 };
+ try std.testing.expect(!try afterServerErrorOrParseReject(
+ &agent,
+ "api_error",
+ "invalid_encrypted_content",
+ "server_error: encrypted content could not be decrypted or parsed; try again",
+ &retries,
+ &state,
+ ));
+ try std.testing.expectEqual(@as(usize, 0), retries);
+ try std.testing.expectEqual(@as(usize, 0), state.parse_retries);
+}
+
test "isTransientServerError (#opencode-parity): overload/server_error retry; quota/invalid/auth do not" {
// transient server conditions → retry like a 5xx
try std.testing.expect(isTransientServerError("overloaded_error", null, ""));
diff --git a/src/agent_responses.zig b/src/agent_responses.zig
index 72f0a9ff..b9efe319 100644
--- a/src/agent_responses.zig
+++ b/src/agent_responses.zig
@@ -129,7 +129,7 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
/// Each field is single-lined and bounded before it reaches last_api_error or
/// the default-on trace.
pub fn failureDiagnostic(allocator: std.mem.Allocator, provider: []const u8, failure: ResponsesFailure) ![]u8 {
- var buf: [768]u8 = undefined;
+ var buf: [1024]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try writeDiagnosticField(&w, provider, 40);
try w.writeAll(" api error");
@@ -145,6 +145,8 @@ pub fn failureDiagnostic(allocator: std.mem.Allocator, provider: []const u8, fai
try writeDiagnosticField(&w, rid, 96);
try w.writeByte(']');
}
+ if (@import("compaction_window.zig").rejectedByProvider(failure.message, failure.code))
+ try w.writeAll(@import("compaction_window.zig").rejection_hint);
// A spent ChatGPT plan allowance, often mid-stream (ADR 0221).
if (policy.isPlanUsageLimit(failure.code)) try w.writeAll(" \xe2\x80\x94 " ++ @import("oauth_chatgpt.zig").usage_hint);
// Reached only after the one refresh-and-retry could not help.
@@ -170,6 +172,21 @@ test "failureDiagnostic points a spent ChatGPT plan at its usage page, a rejecte
try std.testing.expectEqualStrings("Usage limit reached.", (ResponsesFailure{ .message = "Usage limit reached.", .code = "subscription_sharing_usage_limit_exceeded" }).authText());
}
+test "failureDiagnostic makes rejected encrypted state terminal and history-preserving" {
+ const a = std.testing.allocator;
+ const diagnostic = try failureDiagnostic(a, "codex", .{
+ .message = "Encrypted content could not be decrypted or parsed.",
+ .code = "invalid_encrypted_content",
+ });
+ defer a.free(diagnostic);
+ try std.testing.expect(std.mem.indexOf(u8, diagnostic, "history is unchanged") != null);
+ try std.testing.expect(std.mem.endsWith(u8, diagnostic, @import("compaction_window.zig").rejection_hint));
+
+ const ordinary = try failureDiagnostic(a, "codex", .{ .message = "bad request", .code = "invalid_request_error" });
+ defer a.free(ordinary);
+ try std.testing.expect(std.mem.indexOf(u8, ordinary, "compaction state") == null);
+}
+
fn writeDiagnosticField(w: *std.Io.Writer, raw: []const u8, max: usize) !void {
const prefix = util.utf8Prefix(raw, max);
for (prefix) |b| try w.writeByte(if (b < 0x20 or b == 0x7f) ' ' else b);
diff --git a/src/codex_chain.zig b/src/codex_chain.zig
index c14f3670..603ea375 100644
--- a/src/codex_chain.zig
+++ b/src/codex_chain.zig
@@ -72,6 +72,10 @@ pub fn chainBrandOk(provider_id: []const u8) bool {
/// A failed turn must drop the chain: not-found (ZDR / store:false evict),
/// the 25-minute connection cap, or a generic previous_response_id reject.
pub fn shouldDropChain(message: []const u8, code: ?[]const u8) bool {
+ // A delta chained onto rejected opaque state cannot repair that state.
+ // Re-anchor once with the complete canonical window instead; if that is
+ // rejected too, shouldReanchorRequest is false and the error surfaces.
+ if (@import("compaction_window.zig").rejectedByProvider(message, code)) return true;
if (code) |c| {
if (std.mem.indexOf(u8, c, "previous_response_not_found") != null) return true;
if (std.mem.indexOf(u8, c, "websocket_connection_limit_reached") != null) return true;
@@ -223,3 +227,14 @@ test "shouldReanchorRequest requires a rejected previous_response_id request" {
try std.testing.expect(!shouldReanchorRequest(full, "missing", "previous_response_not_found"));
try std.testing.expect(!shouldReanchorRequest(chained, "bad request", "invalid_request_error"));
}
+
+test "rejected encrypted state earns one full resend, never a retry loop" {
+ const chained = "{\"previous_response_id\":\"resp_1\",\"input\":[]}";
+ const full = "{\"input\":[{\"type\":\"compaction\"}]}";
+ const msg = "Encrypted content could not be decrypted or parsed.";
+ try std.testing.expect(shouldReanchorRequest(chained, msg, "invalid_encrypted_content"));
+ // Once the request already carries full input there is no new recovery
+ // shape to try; the terminal diagnostic must reach the user instead.
+ try std.testing.expect(!shouldReanchorRequest(full, msg, "invalid_encrypted_content"));
+ try std.testing.expect(!shouldReanchorRequest(chained, msg, "invalid_request_error"));
+}
diff --git a/src/compaction_window.zig b/src/compaction_window.zig
index 2f1307f5..e59f8a67 100644
--- a/src/compaction_window.zig
+++ b/src/compaction_window.zig
@@ -16,6 +16,16 @@ pub fn latestBlob(items: []const Value) ?usize {
return latest;
}
+/// The provider could not consume its opaque compaction state. A chained
+/// request may re-anchor once with full input; an unchained rejection is
+/// terminal for that context and must not enter a generic retry ladder.
+pub fn rejectedByProvider(message: []const u8, code: ?[]const u8) bool {
+ if (code) |c| return std.ascii.eqlIgnoreCase(c, "invalid_encrypted_content");
+ return std.mem.indexOf(u8, message, "invalid_encrypted_content") != null;
+}
+
+pub const rejection_hint = " — history is unchanged; retrying the same encrypted compaction state will not recover it. Start a new session or restore an earlier saved session.";
+
fn fingerprint(a: Allocator, item: Value) ![32]u8 {
const bytes = try std.json.Stringify.valueAlloc(a, item, .{});
defer a.free(bytes);