Skip to content

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

Python

fix(memory): keep per-request parse garbage off the session arena (#124 slice 2b)

Rach Pradhaneb8493e7facb
diff --git a/benchmarks/README.md b/benchmarks/README.md
index f69ab65d..8bec01b5 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -22,11 +22,13 @@ task, the model, and the network.
| `cost.py` | USD per task (each tool's own usage, [gateway prices](https://codegraff.com/docs/models)) | graff/deepseek-v4-pro **$0.022** vs Claude Code/Opus-4.8 **$0.51** vs Codex/gpt-5.5 **$0.42** |
| `memory.py` | Peak RSS + CPU (`/usr/bin/time -l`) | graff **~25 MB** floor vs Node **~410 MB** vs Rust **~206 MB** |
| `latency.py` | One-shot turn latency, same gpt-5.5 endpoint, concurrent pairs | graff **4.4 s** vs codex **8.9 s** (one-shot only) |
+| `memory_session.py` | RSS-vs-turn slope of ONE persistent `--json` session (the #124 leak detector; `memory.py` is one-shot peak RSS and structurally blind to per-turn growth) | flat slope after warmup = no per-turn leak |
```sh
python3 benchmarks/cost.py
python3 benchmarks/memory.py
python3 benchmarks/latency.py 8
+python3 benchmarks/memory_session.py 50 # N turns, one persistent session
```
Tasks live in `tasks.py` (edit to test other work).
@@ -42,6 +44,8 @@ Tasks live in `tasks.py` (edit to test other work).
invocations, where graff's tiny Zig startup beats Codex's heavier per-call
launch. In a long interactive session this amortizes and turns are model-bound.
- **Memory is task-dependent.** graff's RSS grows with how much code it reads into
- context, so the floor (~25 MB) is the headline, not a fixed number.
+ context, so the floor (~25 MB) is the headline, not a fixed number. Growth over
+ a long session (independent of what is read) is a leak; `memory_session.py`
+ measures exactly that slope per turn.
- `cost.py` omits graff on `gpt-5.5`: the codegraff gateway alias is not in graff's
local price table, so graff reports `$0` for it (deepseek/glm price fine).
diff --git a/src/agent_request.zig b/src/agent_request.zig
index d4d45091..7372639b 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -29,6 +29,7 @@ const normalizeOpenAIHistory = messages_mod.normalizeOpenAIHistory;
const serde = @import("serde.zig");
const writeAnthropicMessages = serde.writeAnthropicMessages;
const writeOpenAIMessageNormalized = serde.writeOpenAIMessageNormalized;
+const util = @import("util.zig");
const http = @import("http.zig");
const postWatched = http.postWatched;
@@ -75,23 +76,28 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
var force = self.strict and tools != null;
var stream_usage = true; // openai stream_options; dropped if rejected
var auth_refreshed = false; // #148: at most one forced token refresh + retry
+ // #124: reclaim last request's transient parse garbage FIRST, so everything
+ // below (oauth refresh internals, per-event parse trees, tool-arg parses)
+ // can use the scratch arena for this request. Safe: all scratch data is
+ // consumed before the next request(); messages/todos/prompts live on the
+ // session arena.
+ if (self.scratch_arena) |sa| _ = sa.reset(.retain_capacity);
// #148: a login-sourced OAuth token (kimi/xai, ~1h) expires mid-session and
// is minted only at startup; refresh it in place before the call when near
// expiry so a long session — or a subagent that inherited the on-disk token —
// never 401s. Login-sourced keys only (env keys untouched); a cheap disk read
- // unless actually near expiry.
+ // unless actually near expiry. The refresh internals (file read + JSON parse,
+ // ~1-2KB) are scratch (#124); only the token itself is duped to survive
+ // future requests.
if (self.provider.source == .login) {
- if (oauth.refreshOAuthKey(self.io, self.gpa, self.arena, self.home, self.provider.id, false)) |fresh| {
- self.provider.api_key = fresh;
+ if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false)) |fresh| {
+ self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;
}
}
// #95: scrub any malformed function_call_output before it hits the wire.
sanitizeMessagesUtf8(self.arena, &self.messages); // invalid UTF-8 (any source/format) -> '?' so content never serializes as a byte-int array the API rejects
if (self.provider.kind == .responses) normalizeResponsesHistory(self.arena, &self.messages);
if (self.provider.kind == .openai) normalizeOpenAIHistory(self.arena, &self.messages); // #99: chat-completions sibling of the above
- // #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);
rebuild: while (true) {
const live = !self.sub and self.out != null and !self.stream_quiet;
self.streamed_text = false;
@@ -288,9 +294,11 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// invalid/expired"; force a refresh and retry once (kimi-code's
// buildAuth(true)). Give up only if the fresh token also fails.
if (!auth_refreshed and self.provider.source == .login and isAuthError(msg)) {
- if (oauth.refreshOAuthKey(self.io, self.gpa, self.arena, self.home, self.provider.id, true)) |fresh| {
+ if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true)) |fresh| {
auth_refreshed = true;
- self.provider.api_key = fresh;
+ // #124: dupe off the scratch refresh internals — the key must
+ // survive every later request of the session.
+ self.provider.api_key = self.arena.dupe(u8, fresh) catch fresh;
if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");
continue;
}
@@ -366,6 +374,14 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
// The final output items arrive as individual `response.output_item.done`
// events; `response.completed` carries usage but an empty output array.
// Collect the done-items and synthesize a {output, usage} object.
+ //
+ // #124 slice 2b: every SSE event of the stream parses on the per-request
+ // scratch arena — the text deltas are the bulk of the body and their parse
+ // trees used to pile up on the session arena forever (~30-45 KB/turn
+ // measured). Only what escapes this request is detached onto the session
+ // arena: the output items (stepResponses appends them to history verbatim)
+ // via dupeJsonValue, and the usage/id/error scalars.
+ const scratch = self.scratchAlloc();
var items = std.json.Array.init(self.arena);
var usage: ?Value = null;
var resp_id: ?[]const u8 = null; // response.id, for previous_response_id delta continuation (#codex-ws)
@@ -377,22 +393,25 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
if (!std.mem.startsWith(u8, line, "data:")) continue;
const payload = std.mem.trim(u8, line["data:".len..], " ");
if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) continue;
- const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue;
+ const v = std.json.parseFromSliceLeaky(Value, scratch, payload, .{ .allocate = .alloc_always }) catch continue;
if (v != .object) continue;
const t = v.object.get("type") orelse continue;
if (t != .string) continue;
if (std.mem.eql(u8, t.string, "response.output_item.done")) {
- if (v.object.get("item")) |item| try items.append(item);
+ if (v.object.get("item")) |item| try items.append(try util.dupeJsonValue(self.arena, item));
} else if (std.mem.eql(u8, t.string, "response.completed") or std.mem.eql(u8, t.string, "response.incomplete")) {
saw_completed = true;
if (v.object.get("response")) |r| if (r == .object) {
- if (r.object.get("usage")) |u| usage = u;
+ if (r.object.get("usage")) |u| usage = try util.dupeJsonValue(self.arena, u);
if (r.object.get("id")) |idv| if (idv == .string) {
- resp_id = idv.string;
+ resp_id = try self.arena.dupe(u8, idv.string);
};
};
} else if (std.mem.eql(u8, t.string, "response.failed") or std.mem.eql(u8, t.string, "error")) {
- err_msg = errorMessage(v.object) orelse "codex stream reported a failure";
+ err_msg = if (errorMessage(v.object)) |m|
+ self.arena.dupe(u8, m) catch "codex stream reported a failure"
+ else
+ "codex stream reported a failure";
}
}
if (saw_completed or items.items.len > 0) {
@@ -403,9 +422,13 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
return .{ .ok = resp };
}
if (err_msg) |m| return .{ .err = m };
- // Not an SSE stream — maybe a JSON error body (401, rate limit, …).
- const v = std.json.parseFromSliceLeaky(Value, self.arena, body, .{ .allocate = .alloc_always }) catch return error.Unparseable;
- if (v == .object) if (errorMessage(v.object)) |m| return .{ .err = m };
+ // Not an SSE stream — maybe a JSON error body (401, rate limit, …). The
+ // message is duped off the scratch parse: sayApiError re-formats it onto
+ // the session arena, but the retry loop may also inspect it after another
+ // rebuild iteration reset the scratch arena.
+ const v = std.json.parseFromSliceLeaky(Value, scratch, body, .{ .allocate = .alloc_always }) catch return error.Unparseable;
+ if (v == .object) if (errorMessage(v.object)) |m|
+ return .{ .err = self.arena.dupe(u8, m) catch "unparseable provider error" };
return error.Unparseable;
}
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index aa3353d3..eee3e0c3 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -18,6 +18,7 @@ const Agent = agent_mod.Agent;
const ToolCall = tools_mod.ToolCall;
const messages_mod = @import("messages.zig");
+const util = @import("util.zig");
const toolResultMessage = messages_mod.toolResultMessage;
// ssePayload/sseIndex live in agent_stream.zig; reached through the Agent
@@ -61,7 +62,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
const input: Value = if (args.len == 0)
.{ .object = .empty }
else
- std.json.parseFromSliceLeaky(Value, self.arena, args, .{ .allocate = .alloc_always }) catch .{ .object = .empty };
+ std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), args, .{ .allocate = .alloc_always }) catch .{ .object = .empty }; // #124: execution-only, same contract as the openai site below
try calls.append(self.gpa, .{ .id = call_id, .name = name, .input = input });
}
}
@@ -176,7 +177,7 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
const input: Value = if (args_str.len == 0)
.{ .object = .empty }
else
- (std.json.parseFromSliceLeaky(Value, self.arena, args_str, .{ .allocate = .alloc_always }) catch .{ .object = .empty });
+ (std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), args_str, .{ .allocate = .alloc_always }) catch .{ .object = .empty }); // #124: execution-only — every consumer (runTools, gate prompts, emits) finishes before the next request()'s scratch reset; the history message carries the arguments STRING, not this tree
const name = if (function.object.get("name")) |n| (if (n == .string) n.string else "") else "";
if (name.len == 0) continue; // can't dispatch a nameless call
const id = if (tc.object.get("id")) |x| (if (x == .string) x.string else "") else "";
@@ -231,6 +232,13 @@ const BlockAcc = struct {
/// via content_block_delta (text / partial_json / thinking / signature);
/// message_delta carries stop_reason and output-token usage.
pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
+ // #124 slice 2b: the whole assembly — per-event parse trees, delta
+ // accumulators, the stitched message — lives on the per-request scratch
+ // arena; the finished message is deep-copied onto the session arena once
+ // at return (it becomes the assistant history message, so it must survive
+ // the next request's scratch reset). Previously every event's parse tree
+ // landed on the session arena for the life of the process.
+ const scratch = self.scratchAlloc();
var root: ?std.json.ObjectMap = null;
var blocks: std.ArrayList(BlockAcc) = .empty;
var stop_reason: ?Value = null;
@@ -238,7 +246,7 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
const payload = ssePayload(raw_line) orelse continue;
- const v = std.json.parseFromSliceLeaky(Value, self.arena, payload, .{ .allocate = .alloc_always }) catch continue; // #124: MUST stay on the session arena — the Anthropic path reuses the parsed message/content_block objects (root=m.object, blocks[i].obj=cb.object) AS the assistant message, so scratch would UAF on the next request's reset
+ const v = std.json.parseFromSliceLeaky(Value, scratch, payload, .{ .allocate = .alloc_always }) catch continue;
if (v != .object) continue;
const t = v.object.get("type") orelse continue;
if (t != .string) continue;
@@ -248,7 +256,7 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
};
} else if (std.mem.eql(u8, t.string, "content_block_start")) {
const idx = sseIndex(v.object) orelse continue;
- while (blocks.items.len <= idx) try blocks.append(self.arena, .{});
+ while (blocks.items.len <= idx) try blocks.append(scratch, .{});
if (v.object.get("content_block")) |cb| if (cb == .object) {
blocks.items[idx].obj = cb.object;
};
@@ -258,10 +266,10 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
const d = v.object.get("delta") orelse continue;
if (d != .object) continue;
const b = &blocks.items[idx];
- if (d.object.get("text")) |x| if (x == .string) try b.text.appendSlice(self.arena, x.string);
- if (d.object.get("partial_json")) |x| if (x == .string) try b.json.appendSlice(self.arena, x.string);
- if (d.object.get("thinking")) |x| if (x == .string) try b.thinking.appendSlice(self.arena, x.string);
- if (d.object.get("signature")) |x| if (x == .string) try b.signature.appendSlice(self.arena, x.string);
+ if (d.object.get("text")) |x| if (x == .string) try b.text.appendSlice(scratch, x.string);
+ if (d.object.get("partial_json")) |x| if (x == .string) try b.json.appendSlice(scratch, x.string);
+ if (d.object.get("thinking")) |x| if (x == .string) try b.thinking.appendSlice(scratch, x.string);
+ if (d.object.get("signature")) |x| if (x == .string) try b.signature.appendSlice(scratch, x.string);
} else if (std.mem.eql(u8, t.string, "message_delta")) {
if (v.object.get("delta")) |d| if (d == .object) {
if (d.object.get("stop_reason")) |sr| if (sr == .string) {
@@ -273,36 +281,38 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
};
} else if (std.mem.eql(u8, t.string, "error")) {
// Hand the envelope back as the root: request()'s existing
- // type=="error" check reports it.
- return v.object;
+ // type=="error" check reports it. Detached from scratch — the
+ // rebuild loop can reset the scratch arena before the message
+ // is done being read.
+ return (try util.dupeJsonValue(self.arena, v)).object;
}
}
var r = root orelse return null;
- var content = std.json.Array.init(self.arena);
+ var content = std.json.Array.init(scratch);
for (blocks.items) |*b| {
if (b.obj.get("type") == null) continue; // never started
- if (b.text.items.len > 0) try b.obj.put(self.arena, "text", .{ .string = b.text.items });
- if (b.thinking.items.len > 0) try b.obj.put(self.arena, "thinking", .{ .string = b.thinking.items });
- if (b.signature.items.len > 0) try b.obj.put(self.arena, "signature", .{ .string = b.signature.items });
+ if (b.text.items.len > 0) try b.obj.put(scratch, "text", .{ .string = b.text.items });
+ if (b.thinking.items.len > 0) try b.obj.put(scratch, "thinking", .{ .string = b.thinking.items });
+ if (b.signature.items.len > 0) try b.obj.put(scratch, "signature", .{ .string = b.signature.items });
if (b.json.items.len > 0) {
- const input = std.json.parseFromSliceLeaky(Value, self.arena, b.json.items, .{ .allocate = .alloc_always }) catch Value{ .object = .empty };
- try b.obj.put(self.arena, "input", input);
+ const input = std.json.parseFromSliceLeaky(Value, scratch, b.json.items, .{ .allocate = .alloc_always }) catch Value{ .object = .empty };
+ try b.obj.put(scratch, "input", input);
}
try content.append(.{ .object = b.obj });
}
- try r.put(self.arena, "content", .{ .array = content });
- try r.put(self.arena, "stop_reason", stop_reason orelse Value{ .string = "end_turn" });
+ try r.put(scratch, "content", .{ .array = content });
+ try r.put(scratch, "stop_reason", stop_reason orelse Value{ .string = "end_turn" });
if (usage_delta) |ud| {
var usage: std.json.ObjectMap = .empty;
if (r.get("usage")) |base| if (base == .object) {
var e = base.object.iterator();
- while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
+ while (e.next()) |kv| try usage.put(scratch, kv.key_ptr.*, kv.value_ptr.*);
};
var e = ud.object.iterator();
- while (e.next()) |kv| try usage.put(self.arena, kv.key_ptr.*, kv.value_ptr.*);
- try r.put(self.arena, "usage", .{ .object = usage });
+ while (e.next()) |kv| try usage.put(scratch, kv.key_ptr.*, kv.value_ptr.*);
+ try r.put(scratch, "usage", .{ .object = usage });
}
- return r;
+ return (try util.dupeJsonValue(self.arena, .{ .object = r })).object;
}
/// One in-flight tool call while reassembling an OpenAI chat stream;
diff --git a/src/main.zig b/src/main.zig
index 5bc4f76a..462ee438 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -180,6 +180,11 @@ pub var g_path_env: []const u8 = "";
pub var g_cwd_display: []const u8 = ".";
pub var g_worktree_branch: ?[]const u8 = null; // -w: the worktree's scratch branch; non-null = auto-commit each turn's edits to it
pub var g_worktree_autocommit: bool = true; // --no-autocommit turns off the per-turn checkpoint commits
+/// #124: allocator-level leak telemetry (GRAFF_MEM_DEBUG=1): the process-lifetime
+/// session arena, queryable at turn boundaries so a per-turn `mem` event can
+/// report its capacity next to the scratch arena's.
+pub var g_session_arena: ?*std.heap.ArenaAllocator = null;
+pub var g_mem_debug: bool = false;
/// Short task label for terminal/TUI headers (mirrors the GUI's first-prompt fallback: the user's first message as a compact tab/session title).
// Session-title + header rendering + provider-response text parsers live in title.zig.
const title_mod = @import("title.zig");
@@ -245,6 +250,8 @@ pub fn main(init: std.process.Init) !void {
// reset each request() so a long REPL/--json/serve session's RSS stays flat.
var scratch_state = std.heap.ArenaAllocator.init(gpa);
defer scratch_state.deinit();
+ g_session_arena = init.arena;
+ g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;
// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.
if (builtin.os.tag == .windows) tty.enableVtOutput();
// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 010d0ad0..d5f29e0c 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -673,6 +673,14 @@ pub fn run(ctx: *Ctx) !void {
final_text;
ctx.root.emit(.{ .type = "finalizing" });
ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = ctx.root.last_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = true, .metadata_complete = ctx.root.last_context_tokens > 0 });
+ // #124: allocator-level leak telemetry (GRAFF_MEM_DEBUG=1) — arena
+ // capacity per turn separates a session-arena leak from gpa-side
+ // growth, which OS-level RSS sampling can't tell apart.
+ if (main_mod.g_mem_debug) ctx.root.emit(.{
+ .type = "mem",
+ .session_arena_kb = if (main_mod.g_session_arena) |a| a.queryCapacity() / 1024 else 0,
+ .scratch_arena_kb = if (ctx.root.scratch_arena) |a| a.queryCapacity() / 1024 else 0,
+ });
}
// Apply the AI summary title + fleet champions that ran in the background
diff --git a/src/util.zig b/src/util.zig
index 781ac229..8fecfcc4 100644
--- a/src/util.zig
+++ b/src/util.zig
@@ -86,3 +86,50 @@ test "utf8Prefix truncates without splitting codepoints" {
try std.testing.expectEqualStrings("ab", utf8Prefix(&s, 3)); // é would split
try std.testing.expectEqualStrings("ab\xC3\xA9", utf8Prefix(&s, 4));
}
+
+/// Deep-copy a std.json.Value (keys and strings included) onto `arena` (#124).
+/// Detaches a subtree that must outlive a per-request scratch parse — e.g. a
+/// Responses output item or an assembled Anthropic message that gets appended
+/// to history — from the parse tree it aliases, so the scratch arena can be
+/// reset at the next request() without a use-after-free.
+pub fn dupeJsonValue(arena: std.mem.Allocator, v: Value) std.mem.Allocator.Error!Value {
+ switch (v) {
+ .null, .bool, .integer, .float => return v,
+ .number_string => |s| return .{ .number_string = try arena.dupe(u8, s) },
+ .string => |s| return .{ .string = try arena.dupe(u8, s) },
+ .array => |arr| {
+ var out = std.json.Array.init(arena);
+ try out.ensureTotalCapacityPrecise(arr.items.len);
+ for (arr.items) |item| out.appendAssumeCapacity(try dupeJsonValue(arena, item));
+ return .{ .array = out };
+ },
+ .object => |obj| {
+ var out: std.json.ObjectMap = .empty;
+ try out.ensureTotalCapacity(arena, obj.count());
+ var it = obj.iterator();
+ while (it.next()) |e|
+ out.putAssumeCapacity(try arena.dupe(u8, e.key_ptr.*), try dupeJsonValue(arena, e.value_ptr.*));
+ return .{ .object = out };
+ },
+ }
+}
+
+test "dupeJsonValue: copy survives the source arena being reset and clobbered" {
+ var src_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer src_state.deinit();
+ var dst_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer dst_state.deinit();
+ const src = std.json.parseFromSliceLeaky(Value, src_state.allocator(),
+ \\{"type":"message","content":[{"type":"output_text","text":"hello"}],"n":42,"big":123456789012345678901234567890}
+ , .{ .allocate = .alloc_always }) catch unreachable;
+ const copy = try dupeJsonValue(dst_state.allocator(), src);
+ // Simulate the per-request scratch reset + the next request overwriting it.
+ _ = src_state.reset(.retain_capacity);
+ const junk = try src_state.allocator().alloc(u8, 64 * 1024);
+ @memset(junk, 0xAA);
+ try std.testing.expectEqualStrings("message", copy.object.get("type").?.string);
+ const blocks = copy.object.get("content").?.array;
+ try std.testing.expectEqualStrings("hello", blocks.items[0].object.get("text").?.string);
+ try std.testing.expectEqual(@as(i64, 42), copy.object.get("n").?.integer);
+ try std.testing.expectEqualStrings("123456789012345678901234567890", copy.object.get("big").?.number_string);
+}