Skip to content

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

Python

session: persist the prompt-cache key so /resume keeps k3/codex cache affinity

Rach Pradhan7522fed877f3
diff --git a/src/http_headers.zig b/src/http_headers.zig
index a07a04ef..4ce37db6 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -42,6 +42,19 @@ pub fn sessionId(io: Io) []const u8 {
return session_id_buf[0..session_id_len];
}
+/// /resume adopts the persisted key so k3/codex prompt-cache affinity survives
+/// the process boundary — both upstreams key the cache on the durable
+/// conversation id (kimi-code's sessionContext.sessionId; codex's ModelClient
+/// default), not a per-process UUID. No-op once this process has minted its own.
+pub fn adoptSessionId(id: []const u8) void {
+ if (id.len != 36) return;
+ 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) return;
+ @memcpy(session_id_buf[0..36], id[0..36]);
+ session_id_len = 36;
+}
+
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 };
@@ -111,3 +124,11 @@ test "session_id is a stable per-process UUIDv4, not a shared constant" {
}
return error.SessionIdHeaderMissing;
}
+
+test "adoptSessionId validates length and never overwrites a minted id" {
+ const io = std.testing.io;
+ const before = sessionId(io); // minted by whichever test ran first
+ adoptSessionId("too-short");
+ adoptSessionId("00000000-0000-4000-8000-000000000000");
+ try std.testing.expectEqualStrings(before, sessionId(io));
+}
diff --git a/src/session.zig b/src/session.zig
index 0d99b2a8..8f731fc5 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -26,6 +26,7 @@ const goal_state = @import("goal_state.zig");
const session_writer = @import("session_writer.zig"); // #273: the fingerprint + the background write
const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resume
+const http_headers = @import("http_headers.zig"); // the k3/codex prompt-cache key survives one too
const session_transcript = @import("session_transcript.zig"); // #441: the append-only history this file's rewrites discard
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
@@ -321,6 +322,9 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64
// reissuing ids the supervisor has already read off the event log.
try s.objectField("event_seq");
try s.write(@min(protocol_seq.current(), @as(u64, std.math.maxInt(i64))));
+ // kimi-code/codex key cache affinity on the durable conversation id; persisting ours keeps /resume warm.
+ try s.objectField("cache_key");
+ try s.write(http_headers.sessionId(root.io));
try s.endObject();
// #289: two graffs in one workspace share this file — the writer makes the
@@ -378,6 +382,11 @@ fn contextTokensFromSession(obj: std.json.ObjectMap) u64 {
return @intCast(v.integer);
}
+/// The persisted prompt-cache key; absent/malformed in pre-cache sessions, whose resume mints a fresh one as before.
+pub fn cacheKeyFromSession(obj: std.json.ObjectMap) ?[]const u8 {
+ const v = obj.get("cache_key") orelse return null;
+ return if (v == .string and v.string.len == 36) v.string else null;
+}
/// The persisted --json sequence high-water mark (#330); 0 for sessions saved
/// before it existed, so a resume of one starts the numbering fresh.
fn eventSeqFromSession(obj: std.json.ObjectMap) u64 {
@@ -438,6 +447,7 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
// only ever raises the counter, so a legacy session (no field) or a corrupt
// negative value simply leaves this process's numbering alone.
protocol_seq.restore(eventSeqFromSession(obj));
+ if (cacheKeyFromSession(obj)) |k| http_headers.adoptSessionId(k);
root.ensureStoredKeys(keys);
if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
diff --git a/src/session_tests.zig b/src/session_tests.zig
index c469bf9f..2a8457dd 100644
--- a/src/session_tests.zig
+++ b/src/session_tests.zig
@@ -343,3 +343,25 @@ test "the autosave is where the transcript sees a new message (#441)" {
session.flushSaves();
try std.testing.expectEqual(@as(usize, 2), session_transcript.lineCount());
}
+
+test "cache_key round-trips: parsed on load, garbage and absence rejected" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const good = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"cache_key":"00000000-0000-4000-8000-000000000000"}
+ , .{});
+ try std.testing.expectEqualStrings("00000000-0000-4000-8000-000000000000", session.cacheKeyFromSession(good.object).?);
+ // Legacy sessions (no field), wrong types, and non-UUID strings all read
+ // as absent: the resume then mints a fresh key, exactly as before.
+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});
+ try std.testing.expect(session.cacheKeyFromSession(legacy.object) == null);
+ const short = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"cache_key":"short"}
+ , .{});
+ try std.testing.expect(session.cacheKeyFromSession(short.object) == null);
+ const wrong_type = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"cache_key":42}
+ , .{});
+ try std.testing.expect(session.cacheKeyFromSession(wrong_type.object) == null);
+}