Skip to content

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

Python

fix(agent): close 4 context-overflow follow-up gaps from #193 (#201, #202)

Rach Pradhanea230ccef4c8
diff --git a/src/agent.zig b/src/agent.zig
index c3b63c21..dfcc684d 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -346,6 +346,7 @@ pub const Agent = struct {
// unchanged.
pub const request = @import("agent_request.zig").request;
pub const inputOverCompactThreshold = @import("agent_request.zig").inputOverCompactThreshold;
+ pub const fullInputEstimateTokens = @import("agent_request.zig").fullInputEstimateTokens;
pub const recordUsage = @import("agent_request.zig").recordUsage;
pub const usageInt = @import("agent_request.zig").usageInt;
pub const recordCost = @import("agent_request.zig").recordCost;
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index 1d409c1a..02b8dcb9 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -455,7 +455,8 @@ pub fn trimOldestToolOutputs(self: *Agent) usize {
if (seen > total - keep_recent) break; // keep the most recent verbatim
reclaimed += truncateToolOutput(self.arena, m, stub_cap, "[old tool output truncated to recover context (#163)]");
}
- if (reclaimed > 0) self.last_context_tokens = 0; // force a re-measure next turn
+ // #202: reflect the trimmed size instead of blinding the meter to 0.
+ if (reclaimed > 0) self.last_context_tokens = self.fullInputEstimateTokens();
return reclaimed;
}
@@ -476,7 +477,9 @@ pub fn capOversizedToolOutputs(self: *Agent, cap: usize) usize {
if (isToolOutputMsg(m.*))
reclaimed += truncateToolOutput(self.arena, m, cap, "[tool output truncated: over this model's per-result cap — read/fetch a smaller range (#193)]");
}
- if (reclaimed > 0) self.last_context_tokens = 0; // force a re-measure next turn
+ // #202: reflect the trimmed size instead of blinding the meter to 0, so the
+ // between-turns gate keeps working and an overflow recover-pin isn't clobbered.
+ if (reclaimed > 0) self.last_context_tokens = self.fullInputEstimateTokens();
return reclaimed;
}
@@ -554,7 +557,9 @@ test "trimOldestToolOutputs recovers a runaway tool-loop history (#163)" {
try std.testing.expect(emergencyCutIndex(agent.messages.items) == null);
const reclaimed = trimOldestToolOutputs(&agent);
try std.testing.expect(reclaimed > 0); // recovered instead of wedging
- try std.testing.expectEqual(@as(usize, 0), agent.last_context_tokens); // forces a re-measure
+ // #202: re-measured to the trimmed size instead of blinding the meter to 0
+ try std.testing.expect(agent.last_context_tokens > 0);
+ try std.testing.expectEqual(agent.fullInputEstimateTokens(), agent.last_context_tokens);
var truncated: usize = 0;
var full: usize = 0;
for (agent.messages.items) |m| {
@@ -614,7 +619,9 @@ test "capOversizedToolOutputs (#193): bounds an oversized output in every wire f
const reclaimed = capOversizedToolOutputs(&agent, cap);
try std.testing.expect(reclaimed > 0);
- try std.testing.expectEqual(@as(usize, 0), agent.last_context_tokens); // forces a re-measure
+ // #202: re-measured to the trimmed size instead of blinding the meter to 0
+ try std.testing.expect(agent.last_context_tokens > 0);
+ try std.testing.expectEqual(agent.fullInputEstimateTokens(), agent.last_context_tokens);
// every oversized tool output is now within the cap, with a marker
const out0 = agent.messages.items[0].object.get("output").?.string;
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 5f9903f5..5271f0ec 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -126,6 +126,33 @@ test "isContextOverflow (#193): matches every provider's overflow phrasing, not
try std.testing.expect(!isContextOverflow("model not found"));
}
+test "recordUsage (#202): floors the meter from the local estimate when usage is absent" {
+ 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);
+ var m: std.json.ObjectMap = .empty;
+ try m.put(a, "role", .{ .string = "user" });
+ try m.put(a, "content", .{ .string = "the quick brown fox jumps over the lazy dog" });
+ try msgs.append(.{ .object = m });
+
+ var agent: Agent = undefined;
+ agent.arena = a;
+ agent.messages = msgs;
+ agent.last_context_tokens = 0;
+
+ // a response body with NO usage object previously froze the meter at its stale
+ // value; now it floors to max(full-input estimate, req_body_len/4) so the
+ // between-turns compaction gate can still fire.
+ const root: std.json.ObjectMap = .empty;
+ recordUsage(&agent, root, 4000);
+
+ try std.testing.expect(agent.last_context_tokens > 0);
+ const expected = @max(fullInputEstimateTokens(&agent), @as(u64, 1000)); // 4000/4
+ try std.testing.expectEqual(expected, agent.last_context_tokens);
+}
+
test "recoverContextOverflow (#193): overflow trims + retries once; guard and non-overflow fall through" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
@@ -217,7 +244,14 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// window past what the in-turn recovery below can reclaim (it keeps the most
// recent outputs verbatim). Window-proportional, so large-context models keep
// full tool results untouched.
- _ = self.capOversizedToolOutputs(self.provider.perOutputCap());
+ const capped = self.capOversizedToolOutputs(self.provider.perOutputCap());
+ if (capped > 0) {
+ // #202: don't truncate silently. The model already sees an inline marker;
+ // surface it to the trace and (interactively) to the user too.
+ if (self.tracer) |tr| tr.note("context", "capped an oversized tool output before send");
+ if (!main_mod.json_mode and !self.sub)
+ self.say("[tool output over this model's per-result cap — truncated {d} bytes before send (#193)]\n", .{capped}) catch {};
+ }
var context_retried = false; // #193: at most one in-turn overflow recovery per request
rebuild: while (true) {
const live = !self.sub and self.out != null and !self.stream_quiet;
@@ -401,7 +435,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });
return error.ApiError;
};
- self.recordUsage(root);
+ self.recordUsage(root, body.len);
if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
return root;
@@ -464,18 +498,22 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
return error.ApiError;
}
- self.recordUsage(root);
+ self.recordUsage(root, body.len);
if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });
return root;
}
}
-pub fn recordUsage(self: *Agent, root: std.json.ObjectMap) void {
- const usage = root.get("usage") orelse return;
- if (usage != .object) return;
- const u = usage.object;
+pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize) void {
self.last_cache_read = 0;
+ // #202: keep the context meter live when the provider omits usage — otherwise
+ // the between-turns compaction gate freezes at a stale value and a long session
+ // can wedge. Mirror the codex/.responses fallback (req_body_len/4, floored at the
+ // full-input estimate) that recordUsageResponses already applies (#174).
+ const usage = root.get("usage") orelse return floorContextTokens(self, req_body_len / 4);
+ if (usage != .object) return floorContextTokens(self, req_body_len / 4);
+ const u = usage.object;
switch (self.provider.kind) {
.anthropic => {
var total: i64 = 0;
@@ -506,6 +544,14 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap) void {
}
}
+/// #202: floor the context meter at the local estimate (full-input byte/4, or the
+/// request-body byte/4 when the history isn't serialized yet) when the API omits
+/// usage, so auto-compaction still triggers. Never lowers an existing higher count.
+fn floorContextTokens(self: *Agent, est: u64) void {
+ const floor = @max(self.fullInputEstimateTokens(), est);
+ if (floor > self.last_context_tokens) self.last_context_tokens = floor;
+}
+
/// An integer usage field, or 0 if absent / wrong type.
pub fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {
if (obj.get(name)) |v| if (v == .integer) return v.integer;
diff --git a/src/provider.zig b/src/provider.zig
index 484ae7a9..09f57f3e 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -86,17 +86,26 @@ pub const Provider = struct {
return p.context / 10 * 8;
}
- /// #193 follow-up: the largest a SINGLE tool output may be, in serialized
- /// bytes, before it is truncated at send time (capOversizedToolOutputs).
- /// Window-proportional — ~50% of the window in estimated tokens (~4 bytes /
- /// token) — so large-context models keep full tool results untouched and only
- /// a result big enough to threaten the window on its own is bounded. This
- /// guarantees no single output can alone overflow past what the in-turn
- /// emergency-trim recovery can reclaim (it keeps the most-recent outputs
- /// verbatim). 0 (unknown window) disables the cap.
+ /// #201: absolute ceiling for a single tool output regardless of window size,
+ /// so a huge-context model still bounds one pathological result.
+ const abs_output_cap_bytes: usize = 256 * 1024;
+
+ /// #193 follow-up / #201: the largest a SINGLE tool output may be, in serialized
+ /// bytes, before it is truncated at send time (capOversizedToolOutputs). It must
+ /// stay small enough that `keep_recent` (=4) such outputs — which
+ /// trimOldestToolOutputs keeps VERBATIM during in-turn recovery — still leave
+ /// room for the trimmed remainder + system prompt to fit on retry. At the old
+ /// `context * 2` (~50% of the window each) four recent outputs pinned ~2x the
+ /// window, past what recovery could reclaim → wedge (#201). Now window-proportional
+ /// at ~1/8 of the window in estimated tokens (context/2 bytes at ~4 bytes/token),
+ /// so 4 recent outputs occupy ~50% of the window, plus an absolute ceiling for
+ /// very large windows. Large-context models still keep normal tool results
+ /// untouched; only a result big enough to threaten the window is bounded.
+ /// 0 (unknown window) disables the cap.
pub fn perOutputCap(p: Provider) usize {
if (p.context == 0) return 0;
- return @intCast(p.context * 2);
+ const proportional: usize = @intCast(p.context / 2);
+ return @min(proportional, abs_output_cap_bytes);
}
};
@@ -247,3 +256,19 @@ test "Keys.build: g_codex_url_override rewires only the codex endpoint" {
const anthropic = try all.providerById("anthropic", "claude-opus-4-8");
try std.testing.expectEqualStrings("https://api.anthropic.com/v1/messages", anthropic.url);
}
+
+test "perOutputCap (#201): window-proportional with an absolute ceiling, keep_recent-safe" {
+ var p: Provider = undefined;
+ // ~1/8 of the window in tokens (context/2 bytes at ~4 bytes/token)
+ p.context = 270_000;
+ try std.testing.expectEqual(@as(usize, 135_000), p.perOutputCap());
+ // #201 invariant: keep_recent (=4) verbatim outputs must stay reclaimable —
+ // 4 * cap (in estimated tokens) < the window.
+ try std.testing.expect(4 * (p.perOutputCap() / 4) < p.context);
+ // absolute ceiling bounds a huge window so one result can't dominate
+ p.context = 4_000_000;
+ try std.testing.expectEqual(@as(usize, 256 * 1024), p.perOutputCap());
+ // unknown window disables the cap
+ p.context = 0;
+ try std.testing.expectEqual(@as(usize, 0), p.perOutputCap());
+}