Skip to content

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

Python

fix: key prompt-cache affinity on the git root, not cwd

Cursor Agenta126713108ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f362f6e..192b9ed3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,9 @@ current is part of cutting a release.
## Unreleased
+- Prompt-cache affinity is the git root, or one scratch seed when there is
+ no `.git`. Eval sandboxes and worktrees can reuse a warm system+tools
+ prefix instead of paying it on every leaf cwd. ADR 0069.
- `#753`: a background-agent handle survives a recoverable API interruption.
`agent_output` replays a finished report, or says the launch ended with the
parent turn, instead of "it may never have started". The ids ride in the
diff --git a/docs/adr/0069-cache-affinity-is-the-git-root.md b/docs/adr/0069-cache-affinity-is-the-git-root.md
new file mode 100644
index 00000000..f810f64d
--- /dev/null
+++ b/docs/adr/0069-cache-affinity-is-the-git-root.md
@@ -0,0 +1,28 @@
+# 0069. Prompt-cache affinity is the git root, not the leaf cwd
+
+Status: accepted 2026-09-06
+
+## Context
+
+The in-house 12-task remasure on 289 held 12/12 and beat the 284 wall pin
+(179.6s vs 219.6s) but list$ rose $0.3169 → $0.4205. Uncached input went
+95k → 150k. `projectRootId` hashed the real cwd, so every eval sandbox
+and worktree was its own xAI cache partition and paid the system+tools
+prefix at `$2/M` instead of a cache read at `$0.50/M`. The
+`cache-gitroot` fixture already named this: a temp dir with no `.git`
+must not seed on its leaf cwd.
+
+## Decision
+
+The durable project cache id hashes the git root when one exists, otherwise
+the constant scratch seed `graff-scratch`. Nested dirs in one repo share a
+key. Scratch trees share one key. Do not hash the leaf cwd. Do not turn
+`x_search` off or shrink the catalog to close list$ (ADR 0024 / 0031).
+
+## Consequences
+
+First request after the seed change is a one-time miss, then sibling
+`-p` evals and worktrees can reuse the warm prefix. Unrelated scratch
+jobs share a routing id and may evict each other's tails; the prefix
+still hits when the bytes match. Revisit only if a same-session table
+shows pass or wall regressing to buy the cache.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 669f4efe..878e3ae0 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -79,6 +79,7 @@ record only when you need the evidence or the edge cases.
| [0066](0066-publication-policy-and-ledger-authority.md) | Publication safeguards survive custom prompts; recaps cannot change ledger authority, and constraint writes refresh active prompts atomically. |
| [0067](0067-recorded-constraints-are-ledger-state.md) | Recorded constraints are live ledger JSON in the root prefix; recap prose is not authority, and a write refreshes instructions in the same turn. |
| [0068](0068-background-agent-handles-survive-interrupt.md) | Background-agent ids are a session ledger; an interrupted parent turn must not report them as never started (#753). |
+| [0069](0069-cache-affinity-is-the-git-root.md) | Prompt-cache affinity is the git root (or a shared scratch seed), not the leaf cwd. |
## When to write one
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index dc9b8ff1..396a6488 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 1989,
+ "test_count_baseline": 1992,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/cache_affinity.zig b/src/cache_affinity.zig
new file mode 100644
index 00000000..b77f5816
--- /dev/null
+++ b/src/cache_affinity.zig
@@ -0,0 +1,103 @@
+//! Prompt-cache affinity seed (ADR 0069).
+//!
+//! xAI routes `prompt_cache_key` / `x-grok-conv-id` per server. Hashing the
+//! leaf cwd made every eval sandbox and worktree a unique partition, so the
+//! expensive system+tools prefix never warmed. The seed is the git root when
+//! one exists, otherwise the constant scratch token — never the leaf of a
+//! throwaway tree (the in-house `cache-gitroot` fixture).
+
+const std = @import("std");
+const Io = std.Io;
+
+pub const scratch_seed = "graff-scratch";
+
+/// Directory that owns `.git` (file or dir), walking parents of `cwd_abs`.
+/// `buf` holds the returned path. Null if the walk hits the filesystem root.
+pub fn gitRootOf(io: Io, cwd_abs: []const u8, buf: []u8) ?[]const u8 {
+ if (cwd_abs.len == 0 or cwd_abs.len >= buf.len) return null;
+ @memcpy(buf[0..cwd_abs.len], cwd_abs);
+ var cur: []const u8 = buf[0..cwd_abs.len];
+ while (cur.len > 1 and (cur[cur.len - 1] == '/' or cur[cur.len - 1] == '\\'))
+ cur = cur[0 .. cur.len - 1];
+
+ var git_buf: [4096]u8 = undefined;
+ while (true) {
+ const git_path = std.fmt.bufPrint(&git_buf, "{s}/.git", .{cur}) catch return null;
+ if (Io.Dir.cwd().access(io, git_path, .{})) |_| {
+ if (cur.ptr != buf.ptr) {
+ if (cur.len > buf.len) return null;
+ @memcpy(buf[0..cur.len], cur);
+ return buf[0..cur.len];
+ }
+ return cur;
+ } else |_| {}
+ const parent = std.fs.path.dirname(cur) orelse return null;
+ if (parent.len == 0 or std.mem.eql(u8, parent, cur)) return null;
+ cur = parent;
+ }
+}
+
+/// Seed hashed into the durable project cache id. Repo trees share the git
+/// root; a temp dir with no `.git` uses `scratch_seed`.
+pub fn affinitySeed(io: Io, cwd_abs: []const u8, buf: []u8) []const u8 {
+ return gitRootOf(io, cwd_abs, buf) orelse scratch_seed;
+}
+
+test "affinity: nested dirs under one repo share the git root" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDirPath(io, ".git");
+ try tmp.dir.createDirPath(io, "a/b");
+
+ var root_buf: [4096]u8 = undefined;
+ const root = root_buf[0..try tmp.dir.realPath(io, &root_buf)];
+ var child_buf: [4096]u8 = undefined;
+ const child = try std.fmt.bufPrint(&child_buf, "{s}/a/b", .{root});
+
+ var a_buf: [4096]u8 = undefined;
+ var b_buf: [4096]u8 = undefined;
+ try std.testing.expectEqualStrings(root, gitRootOf(io, root, &a_buf).?);
+ try std.testing.expectEqualStrings(root, gitRootOf(io, child, &b_buf).?);
+ try std.testing.expectEqualStrings(
+ affinitySeed(io, root, &a_buf),
+ affinitySeed(io, child, &b_buf),
+ );
+}
+
+test "affinity: a .git file counts as a repo root (worktree)" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = ".git", .data = "gitdir: /tmp/main.git\n" });
+ var root_buf: [4096]u8 = undefined;
+ const root = root_buf[0..try tmp.dir.realPath(io, &root_buf)];
+ var seed_buf: [4096]u8 = undefined;
+ try std.testing.expectEqualStrings(root, gitRootOf(io, root, &seed_buf).?);
+}
+
+test "affinity: scratch trees without .git share one seed, not the leaf cwd" {
+ if (@import("builtin").os.tag == .windows) return;
+ const io = std.testing.io;
+ // std.testing.tmpDir lives under the repo `.zig-cache`, so a parent walk
+ // would find /workspace/.git. Use /tmp so the walk is a real scratch.
+ const a_base = "/tmp/graff-aff-scratch-a";
+ const b_base = "/tmp/graff-aff-scratch-b";
+ Io.Dir.cwd().createDirPath(io, a_base ++ "/leaf") catch return error.SkipZigTest;
+ defer Io.Dir.cwd().deleteTree(io, a_base) catch {};
+ Io.Dir.cwd().createDirPath(io, b_base ++ "/other") catch return error.SkipZigTest;
+ defer Io.Dir.cwd().deleteTree(io, b_base) catch {};
+
+ var a_path: [160]u8 = undefined;
+ var b_path: [160]u8 = undefined;
+ const a = try std.fmt.bufPrint(&a_path, "{s}/leaf", .{a_base});
+ const b = try std.fmt.bufPrint(&b_path, "{s}/other", .{b_base});
+
+ var a_buf: [4096]u8 = undefined;
+ var b_buf: [4096]u8 = undefined;
+ try std.testing.expect(gitRootOf(io, a, &a_buf) == null);
+ try std.testing.expect(gitRootOf(io, b, &b_buf) == null);
+ try std.testing.expectEqualStrings(scratch_seed, affinitySeed(io, a, &a_buf));
+ try std.testing.expectEqualStrings(scratch_seed, affinitySeed(io, b, &b_buf));
+ try std.testing.expect(!std.mem.eql(u8, a, scratch_seed));
+}
diff --git a/src/cli.zig b/src/cli.zig
index b44bea84..445c4a2b 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -23,6 +23,7 @@ pub const changelog_text =
\\──────────
\\0.0.289
\\ • background-agent handles survive an interrupted API turn (#753)
+ \\ • prompt-cache affinity is the git root, not the leaf cwd
\\
\\0.0.288
\\ • Gemini is a first-class provider on Google's Interactions API
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 7a3ffb05..3ce9e6f1 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -5,6 +5,7 @@ const Io = std.Io;
const Provider = @import("provider.zig").Provider;
const root = @import("main.zig");
const kimi_catalog = @import("kimi_catalog.zig");
+const cache_affinity = @import("cache_affinity.zig"); // ADR 0069: git-root / scratch seed
var session_id_buf: [36]u8 = undefined;
var session_id_len: usize = 0;
@@ -95,7 +96,7 @@ var project_id_buf: [36]u8 = undefined;
var project_id_len: usize = 0;
var project_id_lock: std.atomic.Value(bool) = .init(false);
-/// Durable per-project id (cwd-derived UUIDv5, no state to persist). A new
+/// Durable per-project id (affinity-seed UUIDv5, no state to persist). A new
/// session in the same repo reuses the bucket the last session wrote, so
/// turn 1 can hit the warm system+tools prefix if the provider still has
/// it. Different models do not share a cache (the server keys by model);
@@ -114,10 +115,12 @@ pub fn projectRootId(io: Io) []const u8 {
break :blk 1;
};
const cwd = cwd_buf[0..n];
+ var seed_buf: [4096]u8 = undefined;
+ const seed = cache_affinity.affinitySeed(io, cwd, &seed_buf);
var digest: [32]u8 = undefined;
var h = std.crypto.hash.sha2.Sha256.init(.{});
h.update("graff-kimi-project-cache-v1");
- h.update(cwd);
+ h.update(seed);
h.final(&digest);
@memcpy(&raw, digest[0..16]);
raw[6] = (raw[6] & 0x0f) | 0x50; // version 5: name-derived
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 949212cc..9c5c771e 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -357,4 +357,5 @@ test {
_ = @import("net_efficiency_test.zig");
_ = @import("codex_tool_search.zig"); // hosted tool_search on gpt-5.4+ Codex
_ = @import("tool_call_args.zig"); // #752: truncated tool-call arguments must not poison history
+ _ = @import("cache_affinity.zig"); // ADR 0069: git-root / scratch cache seed
}