Skip to content

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

Python

perf(prompt-cache): mark the GPT-5.6 stable prefix

Rach Pradhan8b4939081712
diff --git a/docs/adr/0009-gpt-5-6-explicit-prompt-cache-boundary.md b/docs/adr/0009-gpt-5-6-explicit-prompt-cache-boundary.md
new file mode 100644
index 00000000..3a7dd330
--- /dev/null
+++ b/docs/adr/0009-gpt-5-6-explicit-prompt-cache-boundary.md
@@ -0,0 +1,56 @@
+# 0009. GPT-5.6 Platform gets an explicit prompt-cache boundary
+
+Status: accepted 2026-08-18
+
+## Context
+
+GPT-5.6 caches only at eligible breakpoints and no longer falls back to the
+longest matching unmarked prefix. Graff's large instructions/tool prefix is
+stable, but separate sessions and sibling agents begin with different user
+messages, so the default latest-message breakpoint can repeatedly write the
+variable suffix instead of reusing the common prefix.
+
+xAI has a different contract: caching is automatic over an exact append-only
+message prefix, and `x-grok-conv-id` / `prompt_cache_key` provide per-conversation
+server affinity. OpenAI-only breakpoint fields must not leak onto that wire.
+
+A live OpenAI Platform GPT-5.6 Luna probe over the same 6,307-token prompt
+wrote 6,304 cache tokens cold; the immediate repeat read 6,002 tokens and wrote
+zero. The Codex subscription backend rejected `prompt_cache_options` as an
+unsupported parameter, so its supported automatic/keyed path must remain.
+
+## Decision
+
+- OpenAI Platform Responses requests on `gpt-5.6*` prepend one stable developer
+ `input_text` cache anchor after top-level instructions and mark it with an
+ explicit breakpoint. Codex subscription, xAI, and older models receive
+ neither the anchor nor Platform-only options.
+- Root sessions use `prompt_cache_options.mode = "implicit"`: the explicit
+ stable prefix remains reusable while append-only conversation turns keep the
+ useful latest-message checkpoint. Subagents use `mode = "explicit"` so their
+ unique task suffix is not written at 1.25× input price. Both use the documented
+ 30-minute TTL.
+- Root OpenAI/Codex requests keep the durable project key. Child prefix traffic
+ is deterministically spread over four stable role lanes to stay below the
+ documented approximately 15 requests/minute per-key guidance while preserving
+ reuse across repeated workflow roles. Codex uses this supported keyed,
+ automatic path without explicit options.
+- xAI keeps automatic caching and distinct child conversation ids; its header
+ and body continue to carry the same affinity value. It never receives OpenAI
+ Platform breakpoint/options fields.
+- Cache writes are parsed separately from reads and ordinary input, shown in the
+ cost summary, and billed at the documented 1.25× rate for GPT-5.6 and
+ Anthropic ephemeral cache creation.
+
+## Consequences
+
+The cold request pays one cache write and adds a short, stable developer anchor;
+warm sessions and repeated workflow roles can reuse the expensive instructions
+and tool catalog even when their first user message differs. Exact-prefix
+matching still prevents a stale prompt or tool catalog from being reused.
+
+Provider/model gating is load-bearing: globally enabling these fields breaks
+the current Codex subscription backend and would be unsupported on xAI/older
+routes. Revisit the synthetic anchor if the API permits a breakpoint directly
+on top-level instructions, or if live cache-write/read
+measurements stop justifying the extra cold-write cost.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index cf85a8a1..af0aea93 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -19,6 +19,7 @@ record only when you need the evidence or the edge cases.
| [0006](0006-workspace-switch-is-a-tool.md) | Mid-session worktree switch is a real `workspace` tool; a skill cannot move file-tool cwd. |
| [0007](0007-plugins-are-read-in-place.md) | Cursor/Claude/Grok/Codex plugins and MCP are read in place (Claude/Cursor cache via installed_plugins.json, Codex via config.toml PluginStore, never walked); skills stay on-demand; MCP stays consent-gated. |
| [0008](0008-synthetic-evals-use-external-verifiers.md) | Synthetic coding evals promote only external-verifier passes; model judges may tiebreak correctness, never decide it. |
+| [0009](0009-gpt-5-6-explicit-prompt-cache-boundary.md) | GPT-5.6 OpenAI Platform marks the stable prefix explicitly; Codex and xAI stay on their supported keyed automatic-cache paths. |
## When to write one
diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zig
index 8340bba8..849185d8 100644
--- a/src/agent_request_body_responses.zig
+++ b/src/agent_request_body_responses.zig
@@ -19,14 +19,28 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
const is_codex = std.mem.eql(u8, self.provider.id, "codex");
try s.objectField("instructions");
try s.write(try schemaAwarePrompt(self));
- // Sticky cache partition from the first request. Codex/OpenAI document
- // prompt_cache_key; xAI uses the same id as x-grok-conv-id (routes the
- // request to the server that already has the prefix). Root = project
- // id, child = suffix. Effort is NOT flipped per turn — that would miss
- // the prefix.
+ // Sticky cache partition from the first request. xAI's key is a true
+ // per-conversation routing id. OpenAI/Codex instead share deterministic
+ // prefix lanes so repeated workflow roles can reuse the stable prompt.
var ckbuf: [96]u8 = undefined;
try s.objectField("prompt_cache_key");
- try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
+ if (std.mem.eql(u8, self.provider.id, "xai"))
+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf))
+ else
+ try s.write(http_headers.promptPrefixCacheKey(self.io, self.label, &ckbuf));
+ const explicit_cache = supportsExplicitPromptCache(self);
+ if (explicit_cache) {
+ try s.objectField("prompt_cache_options");
+ try s.beginObject();
+ try s.objectField("mode");
+ // Root conversations grow append-only, so retain the useful implicit
+ // latest-message breakpoint. One-shot children cache only the shared
+ // system+tools prefix and avoid paying to write each unique task suffix.
+ try s.write(if (self.sub) "explicit" else "implicit");
+ try s.objectField("ttl");
+ try s.write("30m");
+ try s.endObject();
+ }
// Held-socket delta: previous_response_id + only the new items. xAI's
// published WS contract supports this with store:false via the in-memory
// connection cache; a not-found / 25-min close / drop re-anchors.
@@ -36,13 +50,15 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
try s.write(self.codex_prev_id.?);
}
try s.objectField("input");
- if (chain) {
- var delta = std.json.Array.init(self.arena);
- for (self.messages.items[self.codex_sent_upto..]) |m| try delta.append(m);
- try s.write(Value{ .array = delta });
- } else {
- try s.write(Value{ .array = self.messages });
- }
+ try s.beginArray();
+ // Top-level `instructions` cannot carry a GPT-5.6 breakpoint. A stable,
+ // semantically neutral developer block after it marks the reusable boundary;
+ // tools are also part of the rendered prefix. Chained requests already hold
+ // this item server-side, so only a full anchor writes it.
+ if (!chain and explicit_cache) try writeCacheAnchor(s);
+ const from = if (chain) self.codex_sent_upto else 0;
+ for (self.messages.items[from..]) |m| try s.write(m);
+ try s.endArray();
if (tools) |t| {
try s.objectField("tools");
try serde.writeOpenAITools(s, self.scratchAlloc(), t); // #261 follow-up
@@ -80,6 +96,33 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
try s.write(true);
}
+fn supportsExplicitPromptCache(self: *const Agent) bool {
+ return std.mem.eql(u8, self.provider.id, "openai") and std.mem.startsWith(u8, self.provider.model, "gpt-5.6");
+}
+
+fn writeCacheAnchor(s: *std.json.Stringify) !void {
+ try s.beginObject();
+ try s.objectField("type");
+ try s.write("message");
+ try s.objectField("role");
+ try s.write("developer");
+ try s.objectField("content");
+ try s.beginArray();
+ try s.beginObject();
+ try s.objectField("type");
+ try s.write("input_text");
+ try s.objectField("text");
+ try s.write("The preceding instructions and available tools are the stable operating context for this session.");
+ try s.objectField("prompt_cache_breakpoint");
+ try s.beginObject();
+ try s.objectField("mode");
+ try s.write("explicit");
+ try s.endObject();
+ try s.endObject();
+ try s.endArray();
+ try s.endObject();
+}
+
/// With --output-schema the strict grammar tempts the model to answer
/// immediately instead of touching tools (graff-evals caught grok-4.6
/// answering a file-inspection task without reading the file). One standing
@@ -243,7 +286,7 @@ fn testAgentFor(arena: std.mem.Allocator, id: []const u8, kind: @import("provide
};
}
-test "openai/codex Responses send prompt_cache_key and leave cache mode to the API" {
+test "GPT-5.6 Platform marks the stable prefix; Codex and older routes do not" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
@@ -251,15 +294,28 @@ test "openai/codex Responses send prompt_cache_key and leave cache mode to the A
const ob = try oai.buildBody(null, false, true, true);
defer std.testing.allocator.free(ob);
try std.testing.expect(std.mem.indexOf(u8, ob, "\"prompt_cache_key\":\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, ob, "prompt_cache_breakpoint") == null);
- try std.testing.expect(std.mem.indexOf(u8, ob, "prompt_cache_options") == null);
+ try std.testing.expect(std.mem.indexOf(u8, ob, "\"prompt_cache_options\":{\"mode\":\"implicit\",\"ttl\":\"30m\"}") != null);
+ try std.testing.expect(std.mem.indexOf(u8, ob, "\"role\":\"developer\",\"content\":[{\"type\":\"input_text\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, ob, "\"prompt_cache_breakpoint\":{\"mode\":\"explicit\"}") != null);
+
+ var worker = try testAgentFor(a, "openai", .responses, "gpt-5.6-luna");
+ worker.sub = true;
+ worker.label = "implement";
+ const wb = try worker.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(wb);
+ try std.testing.expect(std.mem.indexOf(u8, wb, "\"prompt_cache_options\":{\"mode\":\"explicit\",\"ttl\":\"30m\"}") != null);
var codex = try testAgentFor(a, "codex", .responses, "gpt-5.6-sol");
const cb = try codex.buildBody(null, false, true, true);
defer std.testing.allocator.free(cb);
- try std.testing.expect(std.mem.indexOf(u8, cb, "\"prompt_cache_key\":\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, cb, "prompt_cache_breakpoint") == null);
try std.testing.expect(std.mem.indexOf(u8, cb, "prompt_cache_options") == null);
+ try std.testing.expect(std.mem.indexOf(u8, cb, "prompt_cache_breakpoint") == null);
+
+ var older = try testAgentFor(a, "openai", .responses, "gpt-5.5");
+ const old = try older.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(old);
+ try std.testing.expect(std.mem.indexOf(u8, old, "prompt_cache_breakpoint") == null);
+ try std.testing.expect(std.mem.indexOf(u8, old, "prompt_cache_options") == null);
}
test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (#502)" {
@@ -275,6 +331,7 @@ test "xai Responses body is bearer-clean: no codex-isms, xAI-legal fields only (
try std.testing.expect(std.mem.indexOf(u8, body, "\"prompt_cache_key\":\"") != null); // xAI caches on it (+ x-grok-conv-id header)
try std.testing.expect(std.mem.indexOf(u8, body, "service_tier") == null);
try std.testing.expect(std.mem.indexOf(u8, body, "prompt_cache_breakpoint") == null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "prompt_cache_options") == null);
try std.testing.expect(std.mem.indexOf(u8, body, "context_management") == null);
try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);
}
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 22e9014a..cad7ea25 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -39,15 +39,25 @@ pub fn sessionId(io: Io) []const u8 {
return session_id_buf[0..session_id_len];
}
-/// Prompt-cache affinity for one agent. xAI routes `x-grok-conv-id` (Chat
+/// Conversation affinity for one agent. xAI routes `x-grok-conv-id` (Chat
/// Completions) and `prompt_cache_key` (Responses) to the same server — that
-/// is how a prefix written earlier can still hit. Root is the durable
-/// per-project id; children get a suffix so interleaved root/sub prefixes
-/// do not evict each other.
+/// is how an append-only conversation can keep finding its cached prefix.
+/// Root is the durable project id; each concurrent child gets its own suffix.
pub fn promptCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {
return projectCacheKey(io, label, agent, buf);
}
+/// OpenAI/Codex cache affinity for requests sharing a stable prompt prefix.
+/// Root keeps the durable project id. Children use four deterministic lanes:
+/// enough sharing for repeated workflow roles, without pushing one key past
+/// OpenAI's documented ~15 requests/minute cache-routing guidance during fanout.
+pub fn promptPrefixCacheKey(io: Io, label: []const u8, buf: []u8) []const u8 {
+ const base = projectRootId(io);
+ if (std.mem.eql(u8, label, "main")) return std.fmt.bufPrint(buf, "{s}", .{base}) catch base;
+ const lane = std.hash.Wyhash.hash(0, label) & 3;
+ return std.fmt.bufPrint(buf, "{s}-child-{d}", .{ base, lane }) catch base;
+}
+
var project_id_buf: [36]u8 = undefined;
var project_id_len: usize = 0;
var project_id_lock: std.atomic.Value(bool) = .init(false);
@@ -218,9 +228,11 @@ test "official OpenAI Responses uses Platform headers, not ChatGPT backend ident
try std.testing.expectEqualStrings("Bearer k", headers[0].value);
}
-test "projectCacheKey is a durable per-project v5 UUID, stable across calls" {
+test "project and prefix cache keys preserve conversation and sharing boundaries" {
var fake: usize = 0;
+ var sibling_fake: usize = 1;
const agent: *const anyopaque = @ptrCast(&fake);
+ const sibling: *const anyopaque = @ptrCast(&sibling_fake);
var buf: [96]u8 = undefined;
const a = projectCacheKey(std.testing.io, "main", agent, &buf);
try std.testing.expectEqual(@as(usize, 36), a.len);
@@ -229,14 +241,24 @@ test "projectCacheKey is a durable per-project v5 UUID, stable across calls" {
const b = projectCacheKey(std.testing.io, "main", agent, &buf2);
try std.testing.expectEqualStrings(a, b); // durable: no per-process randomness
try std.testing.expectEqualStrings(a, projectRootId(std.testing.io));
- // Prompt-cache routing is this project id, not the per-process session UUID.
try std.testing.expect(!std.mem.eql(u8, a, sessionId(std.testing.io)));
- var pbuf: [96]u8 = undefined;
- try std.testing.expectEqualStrings(a, promptCacheKey(std.testing.io, "main", agent, &pbuf));
- // Subagents get a per-agent suffix off the same partition (eviction rule).
+
+ // xAI conversation affinity stays distinct for concurrent children.
var buf3: [96]u8 = undefined;
+ var buf4: [96]u8 = undefined;
const sub = projectCacheKey(std.testing.io, "sub", agent, &buf3);
- try std.testing.expect(std.mem.startsWith(u8, sub, a));
+ const sibling_sub = projectCacheKey(std.testing.io, "sub", sibling, &buf4);
+ try std.testing.expect(!std.mem.eql(u8, sub, sibling_sub));
+
+ // OpenAI/Codex prefix affinity is stable for a workflow role, but spreads
+ // different roles over four lanes to stay below the per-key traffic guide.
+ var pbuf1: [96]u8 = undefined;
+ var pbuf2: [96]u8 = undefined;
+ const prefix1 = promptPrefixCacheKey(std.testing.io, "implement", &pbuf1);
+ const prefix2 = promptPrefixCacheKey(std.testing.io, "implement", &pbuf2);
+ try std.testing.expectEqualStrings(prefix1, prefix2);
+ try std.testing.expect(std.mem.startsWith(u8, prefix1, a));
+ try std.testing.expect(!std.mem.eql(u8, prefix1, a));
}
test "x-grok-conv-id with no explicit conv still uses the project root id" {