Skip to content

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

Python

perf(#124): per-turn scratch arena + session-RSS sampler (Slice 1 + 2a)

justrach653061a4f7e5
diff --git a/benchmarks/memory_session.py b/benchmarks/memory_session.py
new file mode 100644
index 00000000..8e4df3fd
--- /dev/null
+++ b/benchmarks/memory_session.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3
+"""Session RSS-vs-turn: does a long-lived graff conversation leak memory?
+
+`memory.py` measures ONE-SHOT peak RSS, which is structurally blind to per-turn
+growth — a one-shot reads one line and exits before accumulation matters. This
+drives a SINGLE persistent `graff --json` child through N turns (stdin kept
+open), samples its RSS at each turn boundary, and prints the RSS-vs-turn curve
+plus a least-squares MB/turn slope over the post-warmup tail.
+
+Flat-after-warmup = fine. A positive slope is the #124 leak (the root Agent's
+session arena never resets, so per-SSE-event parse garbage accumulates for the
+life of the process) — now with a number to confirm or refute a fix.
+
+Run: CODEGRAFF_API_KEY=... python3 benchmarks/memory_session.py [N] [graff-path]
+ N defaults to 16; graff-path defaults to `graff` on PATH.
+"""
+import subprocess, json, os, sys
+
+os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+N = int(sys.argv[1]) if len(sys.argv) > 1 else 16
+GRAFF = sys.argv[2] if len(sys.argv) > 2 else "graff"
+
+# Short prompts that each stream a paragraph — many SSE events per turn (the
+# parse-garbage axis #124 is about) without slow multi-tool work, so the RSS
+# curve has plenty of samples. Swap in benchmarks/tasks.py for tool-heavy turns.
+PROMPTS = [
+ "In one paragraph, explain what a mutex is.",
+ "Name five programming languages and one strength of each.",
+ "Write a haiku about garbage collection.",
+ "In one paragraph, explain TCP vs UDP.",
+ "List four sorting algorithms with their average time complexity.",
+ "In one paragraph, explain what an arena allocator is.",
+]
+
+
+def rss_mb(pid):
+ try:
+ out = subprocess.run(["ps", "-o", "rss=", "-p", str(pid)],
+ capture_output=True, text=True)
+ return int(out.stdout.strip()) / 1024.0
+ except Exception:
+ return 0.0
+
+
+def main():
+ env = {**os.environ, "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}
+ p = subprocess.Popen([GRAFF, "--model", "deepseek-v4-pro", "--json"],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, text=True, env=env, bufsize=1)
+ samples = []
+ try:
+ # Queue all turns up front (small JSON lines fit the pipe buffer), keep
+ # stdin open so the child stays alive for the final RSS sample, then read
+ # + sample at each turn boundary. graff processes them sequentially.
+ for i in range(N):
+ p.stdin.write(json.dumps({"type": "user", "text": PROMPTS[i % len(PROMPTS)]}) + "\n")
+ p.stdin.flush()
+ p.stdin.close() # EOF after the queued turns so graff drains them all then exits
+ done = 0
+ while done < N:
+ line = p.stdout.readline()
+ if not line:
+ raise RuntimeError("graff exited early after %d/%d turns" % (done, N))
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("type") == "error":
+ print(" (error: %s)" % ev.get("message"))
+ if ev.get("type") == "turn" and ev.get("complete"):
+ done += 1
+ r = rss_mb(p.pid)
+ samples.append((done, r))
+ print(" turn %2d: RSS = %7.1f MB" % (done, r))
+ finally:
+ try:
+ p.stdin.close(); p.terminate(); p.wait(timeout=5)
+ except Exception:
+ p.kill()
+
+ tail = samples[2:] if len(samples) > 4 else samples # drop warmup
+ if len(tail) >= 2:
+ xs = [x for x, _ in tail]
+ ys = [y for _, y in tail]
+ n = len(tail)
+ mx, my = sum(xs) / n, sum(ys) / n
+ den = sum((x - mx) ** 2 for x in xs) or 1.0
+ slope = sum((x - mx) * (y - my) for x, y in tail) / den
+ verdict = "FLAT — no per-turn leak" if abs(slope) < 0.1 else "GROWING — leak present"
+ print("\nRSS growth over turns %d..%d: %+.3f MB/turn (%s)"
+ % (xs[0], xs[-1], slope, verdict))
+ print("first-tail %.1f MB -> peak %.1f MB" % (ys[0], max(ys)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agent.zig b/src/agent.zig
index d3ddbeb1..aa03843a 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -82,6 +82,12 @@ pub const TodoItem = struct {
pub const Agent = struct {
gpa: Allocator,
arena: Allocator,
+ /// #124: per-turn transient parse garbage (per-SSE-event envelope parses,
+ /// isStreamEnd) allocates here and is reset each request(), so the long-lived
+ /// ROOT agent's session arena stops growing unboundedly. Optional — null on
+ /// subagents/one-shots (they free their own arena per task); scratchAlloc()
+ /// then falls back to arena, so their behavior is unchanged.
+ scratch_arena: ?*std.heap.ArenaAllocator = null,
io: Io,
client: *std.http.Client,
provider: Provider,
@@ -401,6 +407,12 @@ pub const Agent = struct {
// unchanged. esc_cancel/esc_watch_done above stay here (never alias a
// `var`); ssePayload/sseIndex live there too since they're only
// consumed alongside the interrupt-watch plumbing in postStream.
+ /// Allocator for per-turn transient scratch (#124): the reset-per-request
+ /// scratch arena when set (root), else the session arena (subagents/one-shot).
+ pub fn scratchAlloc(self: *Agent) Allocator {
+ return if (self.scratch_arena) |sa| sa.allocator() else self.arena;
+ }
+
pub const escWatchTask = @import("agent_interrupt.zig").escWatchTask;
pub const escPressed = @import("agent_interrupt.zig").escPressed;
pub const drainSteerStdin = @import("agent_interrupt.zig").drainSteerStdin;
diff --git a/src/agent_request.zig b/src/agent_request.zig
index eeb747fa..6ca87aa3 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -89,6 +89,9 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
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);
while (true) {
const live = !self.sub and self.out != null and !self.stream_quiet;
self.streamed_text = false;
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 1111cd3a..25b7fa03 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -227,7 +227,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;
+ 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
if (v != .object) continue;
const t = v.object.get("type") orelse continue;
if (t != .string) continue;
@@ -315,7 +315,7 @@ pub fn assembleOpenAI(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;
+ const v = std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), payload, .{ .allocate = .alloc_always }) catch continue; // #124: per-event parse tree is transient (deltas are appendSlice'd into session accumulators)
if (v != .object) continue;
// The final usage chunk (stream_options.include_usage) may have
// an empty choices array.
@@ -365,7 +365,7 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
if (!saw_chunk) return null;
var message: std.json.ObjectMap = .empty;
- try message.put(self.arena, "role", .{ .string = role });
+ try message.put(self.arena, "role", .{ .string = try self.arena.dupe(u8, role) }); // #124: role slices the scratch parse tree; dupe so it survives the per-request scratch reset
try message.put(self.arena, "content", if (content.items.len > 0) Value{ .string = content.items } else .null);
if (reasoning_content.items.len > 0) try message.put(self.arena, "reasoning_content", .{ .string = reasoning_content.items });
if (reasoning.items.len > 0) try message.put(self.arena, "reasoning", .{ .string = reasoning.items });
@@ -374,10 +374,10 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
for (calls.items) |c| {
if (c.id.len == 0 and c.name.len == 0) continue;
var function: std.json.ObjectMap = .empty;
- try function.put(self.arena, "name", .{ .string = c.name });
+ try function.put(self.arena, "name", .{ .string = try self.arena.dupe(u8, c.name) }); // #124: dupe off the scratch parse tree
try function.put(self.arena, "arguments", .{ .string = c.args.items });
var tc: std.json.ObjectMap = .empty;
- try tc.put(self.arena, "id", .{ .string = c.id });
+ try tc.put(self.arena, "id", .{ .string = try self.arena.dupe(u8, c.id) }); // #124: dupe off the scratch parse tree
try tc.put(self.arena, "type", .{ .string = "function" });
try tc.put(self.arena, "function", .{ .object = function });
try tcs.append(.{ .object = tc });
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 76011d3a..aad159f2 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -410,7 +410,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// provider never sends [DONE] — record it so a subsequent close counts
// as a clean end, but keep reading so a trailing usage chunk still lands.
if (self.provider.kind == .openai and openaiComplete(line.writer.buffered())) saw_done = true;
- if (isStreamEnd(self.arena, self.provider.kind, line.writer.buffered())) {
+ if (isStreamEnd(self.scratchAlloc(), self.provider.kind, line.writer.buffered())) { // #124: parse tree is a transient bool check
saw_done = true; // #133: the provider's terminal event landed — a later close is clean
if (req.connection) |conn| conn.closing = true;
break :stream;
diff --git a/src/main.zig b/src/main.zig
index 231a8053..fdc02e6e 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -240,6 +240,10 @@ pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
+ // #124: a per-turn scratch arena for the root agent's transient parse garbage,
+ // 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();
// 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.
@@ -366,6 +370,7 @@ pub fn main(init: std.process.Init) !void {
// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference
// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.
var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, mcp_tools, &snaps, flags, telem.endpoint);
+ root.scratch_arena = &scratch_state; // #124: route the root's transient parse garbage here; reset per request()
root.fallback_active = stale_saved_model != null;
root.fallback_blocked = root.fallback_active and preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, root.provider.id) and !fallback_config.contains(root.fallback_allow, root.provider.id);
defer joinElites(io); // reap if the session quits before any turn joins it