graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): give each session its own prompt-cache partition
justrachbcb5804a2a82
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 8814b1fd..a5b5ae49 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -10,7 +10,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 498,+ "test_count_baseline": 499,"required_invariants": [{"id": "goal-epochs",diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 27213316..4ab5dc7f 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -8,6 +8,7 @@ const main_mod = @import("main.zig");const max_tokens = main_mod.max_tokens;const Agent = @import("agent.zig").Agent;const serde = @import("serde.zig");+const http_headers = @import("http_headers.zig");const pricing = @import("pricing.zig");const writeAnthropicMessages = serde.writeAnthropicMessages;const writeAnthropicTools = serde.writeAnthropicTools;@@ -174,6 +175,12 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo// returned encrypted and passed back for cross-turn continuity.try s.objectField("instructions");try s.write(self.systemPrompt());+ // Pin our full resends to a per-session cache partition, the way+ // openai/codex does (it defaults this to the same session UUID it+ // puts in the `session_id` header). Without it the backend has no+ // affinity hint for a prefix we re-upload every turn.+ try s.objectField("prompt_cache_key");+ try s.write(http_headers.sessionId(self.io));// Codex WS delta: once a response.id is held on a live WS session,// send previous_response_id + only the items the server does not yet// hold, instead of the full history (avoids the huge frame that the@@ -253,7 +260,7 @@ test "Kimi request body follows live native or Anthropic protocol metadata" {var agent: Agent = .{.gpa = std.testing.allocator,.arena = arena,- .io = undefined,+ .io = std.testing.io,.client = undefined,.provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "native-k3", .context = 1_048_576 },.messages = messages,@@ -345,7 +352,7 @@ test "retained reasoning: openai-chat history replays reasoning_content on the nvar agent: Agent = .{.gpa = std.testing.allocator,.arena = arena,- .io = undefined,+ .io = std.testing.io,.client = undefined,.provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 },.messages = messages,@@ -412,7 +419,7 @@ test "retained reasoning: anthropic replays thinking+signature inside a multi-stvar agent: Agent = .{.gpa = std.testing.allocator,.arena = arena,- .io = undefined,+ .io = std.testing.io,.client = undefined,.provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude", .context = 1_000_000 },.messages = messages,@@ -464,7 +471,7 @@ test "retained reasoning: codex full resend keeps encrypted reasoning items andvar agent: Agent = .{.gpa = std.testing.allocator,.arena = arena,- .io = undefined,+ .io = std.testing.io,.client = undefined,.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6", .context = 272_000 },.messages = messages,@@ -484,6 +491,12 @@ test "retained reasoning: codex full resend keeps encrypted reasoning items andtry std.testing.expect(std.mem.indexOf(u8, body, "\"store\":false") != null);// No live WS session -> no chaining, so the full input must carry it.try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);++ // Because store:false makes every turn a full resend, the backend needs a+ // cache partition to land it in. openai/codex sends prompt_cache_key on+ // this exact path, defaulting it to the per-session UUID.+ const key = try std.fmt.allocPrint(arena, "\"prompt_cache_key\":\"{s}\"", .{http_headers.sessionId(agent.io)});+ try std.testing.expect(std.mem.indexOf(u8, body, key) != null);}test "anthropic asks for summarized thinking; other anthropic-format providers do not" {@@ -497,7 +510,7 @@ test "anthropic asks for summarized thinking; other anthropic-format providers dvar agent: Agent = .{.gpa = std.testing.allocator,.arena = arena,- .io = undefined,+ .io = std.testing.io,.client = undefined,.provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude", .context = 1_000_000 },.messages = messages,diff --git a/src/agent_stream.zig b/src/agent_stream.zigindex d2b5ee1f..dd10ec1f 100644--- a/src/agent_stream.zig+++ b/src/agent_stream.zig@@ -194,7 +194,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons};defer if (bearer.len > 0) gpa.free(bearer);var headers_buf: [12]std.http.Header = undefined;- const extra = providerHeaders(provider, bearer, &headers_buf);+ const extra = providerHeaders(self.io, provider, bearer, &headers_buf);self.md_buf.clearRetainingCapacity(); // fresh markdown state per streamself.arg_live = .{}; // fresh tool-argument extractor per streamdiff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 36ae16ac..83d08f52 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -74,7 +74,7 @@ test "buildBody (.responses): delta while WS live; full input after closeCodexWsvar agent: Agent = .{.gpa = std.testing.allocator,.arena = a,- .io = undefined, // unused by buildBody+ .io = std.testing.io, // unused by buildBody.client = undefined, // unused by buildBody.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://x/responses", .api_key = "k", .model = "gpt-5", .context = 100_000 },.messages = msgs,@@ -139,7 +139,7 @@ test "buildBody (.responses): never emits a top-level max_output_tokens (codex gvar agent: Agent = .{.gpa = std.testing.allocator,.arena = a,- .io = undefined, // unused by buildBody+ .io = std.testing.io, // unused by buildBody.client = undefined, // unused by buildBody.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://x/responses", .api_key = "k", .model = "gpt-5.6-sol", .context = 270_000 },.messages = msgs,diff --git a/src/http.zig b/src/http.zigindex b9c5d6d7..2ab46cb2 100644--- a/src/http.zig+++ b/src/http.zig@@ -130,7 +130,7 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []codefer if (bearer.len > 0) gpa.free(bearer);var headers_buf: [12]std.http.Header = undefined;- const extra = providerHeaders(provider, bearer, &headers_buf);+ const extra = providerHeaders(client.io, provider, bearer, &headers_buf);var req = try client.request(.POST, try std.Uri.parse(provider.url), .{.redirect_behavior = .unhandled,diff --git a/src/http_headers.zig b/src/http_headers.zigindex 04dfc18a..a07a04ef 100644--- a/src/http_headers.zig+++ b/src/http_headers.zig@@ -1,10 +1,47 @@//! Provider-specific HTTP identity and authorization headers.const std = @import("std");+const Io = std.Io;const Provider = @import("provider.zig").Provider;const root = @import("main.zig");const kimi_catalog = @import("kimi_catalog.zig");+var session_id_buf: [36]u8 = undefined;+var session_id_len: usize = 0;+/// Spin-lock, not an Io.Mutex: providerHeaders has no Io handle to reach one+/// with, and the critical section is a single one-time 36-byte format.+var session_id_lock: std.atomic.Value(bool) = .init(false);++/// A UUIDv4 minted once per process, matching what openai/codex generates per+/// session. It rides two places: the `session_id` header and `prompt_cache_key`+/// on the Responses body, which is what the backend partitions its prompt cache+/// on. This was a single hardcoded constant shared by every graff user on every+/// machine, which is the worst case for that partition: one key carrying all+/// traffic overflows and DEGRADES hit rate, so the full histories we resend+/// each turn had no affinity to land on.+pub fn sessionId(io: Io) []const u8 {+ while (session_id_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();+ defer session_id_lock.store(false, .release);+ if (session_id_len == 0) {+ var raw: [16]u8 = undefined;+ io.random(&raw);+ raw[6] = (raw[6] & 0x0f) | 0x40; // version 4+ raw[8] = (raw[8] & 0x3f) | 0x80; // variant 1+ const hex = std.fmt.bytesToHex(raw, .lower);+ @memcpy(session_id_buf[0..8], hex[0..8]);+ session_id_buf[8] = '-';+ @memcpy(session_id_buf[9..13], hex[8..12]);+ session_id_buf[13] = '-';+ @memcpy(session_id_buf[14..18], hex[12..16]);+ session_id_buf[18] = '-';+ @memcpy(session_id_buf[19..23], hex[16..20]);+ session_id_buf[23] = '-';+ @memcpy(session_id_buf[24..36], hex[20..32]);+ session_id_len = 36;+ }+ return session_id_buf[0..session_id_len];+}+pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {if (std.mem.eql(u8, provider.id, "kimi")) {return .{ .override = root.kimi_user_agent };@@ -12,7 +49,7 @@ pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {return .default;}-pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {+pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {var count: usize = 0;switch (provider.auth) {.x_api_key => {@@ -39,8 +76,38 @@ pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[12]std.httcount += 1;buf[count] = .{ .name = "originator", .value = "codex_cli_rs" };count += 1;- buf[count] = .{ .name = "session_id", .value = "00000000-0000-0000-0000-000000000001" };+ buf[count] = .{ .name = "session_id", .value = sessionId(io) };count += 1;}return buf[0..count];}++test "session_id is a stable per-process UUIDv4, not a shared constant" {+ const io = std.testing.io;+ const a = sessionId(io);+ try std.testing.expectEqual(@as(usize, 36), a.len);+ // The value the backend partitions its prompt cache on used to be this+ // constant, identical for every session and every graff user.+ try std.testing.expect(!std.mem.eql(u8, a, "00000000-0000-0000-0000-000000000001"));+ for ([_]usize{ 8, 13, 18, 23 }) |i| try std.testing.expectEqual(@as(u8, '-'), a[i]);+ try std.testing.expectEqual(@as(u8, '4'), a[14]); // version nibble+ try std.testing.expect(a[19] == '8' or a[19] == '9' or a[19] == 'a' or a[19] == 'b'); // variant+ for (a, 0..) |c, i| {+ if (i == 8 or i == 13 or i == 18 or i == 23) continue;+ try std.testing.expect((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f'));+ }+ // Stable within the process: the header and prompt_cache_key must agree,+ // and the key must not move turn to turn or it partitions nothing.+ try std.testing.expectEqualStrings(a, sessionId(io));++ var buf: [12]std.http.Header = undefined;+ const p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6", .context = 272_000, .account = "acct" };+ const headers = providerHeaders(io, p, "Bearer k", &buf);+ for (headers) |h| {+ if (std.mem.eql(u8, h.name, "session_id")) {+ try std.testing.expectEqualStrings(a, h.value);+ return;+ }+ }+ return error.SessionIdHeaderMissing;+}