graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): prove the #402 proactive re-read, and stop it growing a child's arena
Rach Pradhan7584dca52df6
diff --git a/scripts/test-codex-auth-recovery.py b/scripts/test-codex-auth-recovery.pyindex 91fc7688..5a72fa24 100644--- a/scripts/test-codex-auth-recovery.py+++ b/scripts/test-codex-auth-recovery.py@@ -10,12 +10,19 @@ Driven through a real graff process on a PTY, against the codex mock:the mock rewrites ``$CODEX_HOME/auth.json`` — standing in for the ``/login``(or a second graff, or the real ``codex`` CLI) that re-authenticates whilethis session is live.- 3. graff must adopt that credential without a restart and resend the turn.--Asserted on the wire: a second request exists, it carries the NEW bearer and the-new chatgpt-account-id, and the session prints the reply. Before #402 the turn-died on the 401 body and every later turn re-fired the same expired token, which-is exactly what the issue reports.+ 3. graff must adopt that credential without a restart and resend the turn+ (the REACTIVE half: the ``.responses`` 401 arm).+ 4. While serving that retry the mock rewrites auth.json once more, and the user+ sends a second message. That turn never 401s, so only the PROACTIVE+ per-request re-read can pick the new credential up — codex-rs's STEP 1 run+ preemptively. It is also the half that regressed the reported symptom: a+ proactive read pointed at a different directory than the login writer+ silently reverts a ``/login`` that just succeeded.++Asserted on the wire: the retry carries the NEW bearer and the account id, the+turn after it carries the NEXT one, and the session prints both replies. Before+#402 the turn died on the 401 body and every later turn re-fired the same expired+token, which is exactly what the issue reports.$CODEX_HOME deliberately is NOT ``$HOME/.codex``: the credential the recoveryreads has to be the one the login flows write, and this scenario only passes when@@ -36,8 +43,10 @@ _arg = sys.argv[1] if len(sys.argv) > 1 else "graff"GRAFF = os.path.abspath(_arg) if os.sep in _arg else _argFINAL_REPLY = "AUTH_RECOVERY_OK"+SECOND_REPLY = "AUTH_PROACTIVE_OK"EXPIRED_TOKEN = "tok-expired-402"FRESH_TOKEN = "tok-fresh-402"+RELOGIN_TOKEN = "tok-relogin-402"EXPIRED_ACCOUNT = "acct-402"EXPIRED_BODY = json.dumps({@@ -88,23 +97,29 @@ def main() -> None:return unauthorized()def events(request: RecordedRequest) -> list[dict]:+ if request.ordinal == 2:+ # The retry is in flight and will succeed. Re-authenticate AGAIN+ # behind graff's back: no later request 401s, so only the+ # proactive per-request re-read can notice this one.+ write_auth(codex_home, RELOGIN_TOKEN)+ reply = FINAL_REPLY if request.ordinal <= 2 else SECOND_REPLYreturn [{"type": "response.output_item.done","item": {"type": "message",- "id": "msg_auth_ok",+ "id": f"msg_auth_ok_{request.ordinal}","status": "completed","role": "assistant","content": [- {"type": "output_text", "text": FINAL_REPLY, "annotations": []}+ {"type": "output_text", "text": reply, "annotations": []}],},},{"type": "response.completed","response": {- "id": "resp_auth_ok",+ "id": f"resp_auth_ok_{request.ordinal}","usage": {"input_tokens": 100,"input_tokens_details": {"cached_tokens": 0},@@ -150,6 +165,10 @@ def main() -> None:session.send_line("say hello")session.wait_for_literal(FINAL_REPLY, start=cursor)session.wait_for_literal("] ›", start=cursor)+ cursor = len(session.raw)+ session.send_line("say hello again")+ session.wait_for_literal(SECOND_REPLY, start=cursor)+ session.wait_for_literal("] ›", start=cursor)session.send_key("ctrl-d")result = session.read_until_exit(5.0)if result.timed_out or result.exit_code != 0:@@ -158,9 +177,9 @@ def main() -> None:)requests = mock.recorded_requests()- if len(requests) < 2:+ if len(requests) < 3:raise AssertionError(- f"the 401 was terminal — no retry was sent: {[r.ordinal for r in requests]!r}"+ f"expected a retry and a second turn, got: {[r.ordinal for r in requests]!r}")first = requests[0].headers.get("authorization", "")if first != f"Bearer {EXPIRED_TOKEN}":@@ -173,18 +192,24 @@ def main() -> None:account = requests[1].headers.get("chatgpt-account-id", "")if account != EXPIRED_ACCOUNT:raise AssertionError(f"account header lost on the retry: {account!r}")- # The adopted credential must also be the one every LATER request uses,- # not just this one retry.- for request in requests[1:]:+ # The PROACTIVE half: nothing 401'd after the retry, so the only way+ # request 3 can carry the credential written during request 2 is the+ # per-request re-read — and only if it resolves the file the login+ # flows write.+ for request in requests[2:]:token = request.headers.get("authorization", "")- if token != f"Bearer {FRESH_TOKEN}":+ if token != f"Bearer {RELOGIN_TOKEN}":+ raise AssertionError(+ f"request {request.ordinal} did not pick up the out-of-band login: {token!r}"+ )+ if request.headers.get("chatgpt-account-id", "") != EXPIRED_ACCOUNT:raise AssertionError(- f"request {request.ordinal} fell back to a stale token: {token!r}"+ f"request {request.ordinal} lost the account header")finally:mock.stop()- print("ok an expired codex token is adopted mid-turn and the retry carries it")+ print("ok an expired codex token is adopted mid-turn, and an out-of-band login mid-session")if __name__ == "__main__":diff --git a/src/agent_request.zig b/src/agent_request.zigindex 1461038a..240343dc 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -10,7 +10,6 @@ const Value = std.json.Value;const main_mod = @import("main.zig");const Agent = @import("agent.zig").Agent;-const oauth = @import("oauth.zig");const messages_mod = @import("messages.zig");const sanitizeMessagesUtf8 = messages_mod.sanitizeMessagesUtf8;@@ -96,31 +95,18 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {var stream_usage = true; // openai stream_options; dropped if rejectedvar auth_refreshed = false; // #148: at most one forced token refresh + retry// #124: reclaim last request's transient parse garbage FIRST, so everything- // below (oauth refresh internals, per-event parse trees, tool-arg parses)- // can use the scratch arena for this request. Safe: all scratch data is+ // below (per-event parse trees, tool-arg parses) can use the scratch arena+ // for this request. Safe: all scratch data is// consumed before the next request(); messages/todos/prompts live on the// session arena.if (self.scratch_arena) |sa| resetRequestScratch(sa);- // #148: a login-sourced OAuth token (kimi/xai, ~1h) expires mid-session and- // is minted only at startup; refresh it in place before the call when near- // expiry so a long session — or a subagent that inherited the on-disk token —- // never 401s. Login-sourced keys only (env keys untouched); a cheap disk read- // unless actually near expiry. The refresh internals (file read + JSON parse,- // ~1-2KB) are scratch (#124); only the token itself is duped to survive- // future requests.- // #402: codex joins this path. Its on-disk read is unconditional (a ChatGPT- // token carries no expiry we can cheaply check), which is also codex-rs's- // STEP 1 — a `graff login` in another terminal is picked up here, without- // waiting for a 401. It reads the ONE credential dir every login flow writes- // (oauth.codexHomeDir), so this can no longer revert a login that just- // succeeded, and it needs neither the root's catalog nor a `home`.- if (self.provider.source == .login) {- if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false, null, self.provider.account)) |fresh| {- // Only adopt on a real change: this runs every request, and the- // session arena is never reclaimed.- if (!std.mem.eql(u8, fresh.key, self.provider.api_key)) policy.adoptFreshAuth(self, fresh);- }- }+ // #148/#402: a login-sourced OAuth token expires mid-session and is minted+ // only at startup; pick up whatever is currently on disk before the call, so+ // a long session — or a subagent that inherited the token — never 401s over+ // a credential somebody has already replaced. Login-sourced keys only (env+ // keys untouched), and see refreshLoginKeyBeforeSend for why its transients+ // do NOT go on the scratch arena.+ policy.refreshLoginKeyBeforeSend(self);// #95: scrub any malformed function_call_output before it hits the wire.const message_arena = self.messageMutationAlloc();sanitizeMessagesUtf8(message_arena, &self.messages); // invalid UTF-8 (any source/format) -> '?' so content never serializes as a byte-int array the API rejectsdiff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 582a2ee6..e0876075 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -64,6 +64,84 @@ fn warnUnpersistedRefresh(self: *Agent) void {self.say("[⚠ refreshed the Codex token but could not save it ({s}) — run `graff login codex` before your next session]\n", .{name}) catch {};}+/// #148/#402: adopt a credential another writer has already produced BEFORE the+/// request goes out — codex-rs's STEP 1, run preemptively instead of only after+/// a rejection, so a `graff login` in another terminal (or the real codex CLI)+/// heals a live session without waiting for it to 401 first. Runs for the root+/// and for subagents alike: the credential resolver needs neither the root's+/// model catalog nor a `home`, and it resolves the ONE directory every login+/// flow writes (oauth.codexHomeDir), so this read can no longer revert a+/// `/login` that just succeeded — the reported #402 symptom.+///+/// kimi/xai refresh only near expiry; the codex read is unconditional, because a+/// ChatGPT access token carries no expiry field we could check cheaply.+///+/// The read + JSON parse are scoped to a LOCAL arena rather than+/// `self.scratchAlloc()`. This runs on every single request, and a subagent has+/// no scratch arena — scratchAlloc() falls back to the session arena, which is+/// never reclaimed, so the ~1-2KB per request would accumulate for the whole+/// life of the child. adoptFreshAuth dupes what it keeps onto the session arena,+/// so nothing here outlives this frame.+pub fn refreshLoginKeyBeforeSend(self: *Agent) void {+ if (self.provider.source != .login) return;+ var scratch = std.heap.ArenaAllocator.init(self.gpa);+ defer scratch.deinit();+ const fresh = oauth.refreshOAuthKey(self.io, self.gpa, scratch.allocator(), self.home, self.provider.id, false, null, self.provider.account) orelse return;+ // Only adopt on a real CHANGE: an unchanged credential must not churn the+ // session arena, nor hand the WS transport latch back on every request.+ if (std.mem.eql(u8, fresh.key, self.provider.api_key)) return;+ adoptFreshAuth(self, fresh);+}++test "refreshLoginKeyBeforeSend (#402): an out-of-band login heals a live session, at no per-request cost" {+ const io = std.testing.io;+ var session = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer session.deinit();+ var scratch_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer scratch_state.deinit();+ const arena = scratch_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ try writeTestAuth(io, arena, codex_home, "startup-tok", "", "acct-1");++ const saved = oauth_helpers.g_codex_home;+ defer oauth_helpers.g_codex_home = saved;+ oauth_helpers.g_codex_home = codex_home;++ // A CHILD: no catalog, no home, and no scratch arena — everything it+ // allocates lands on the session arena below and is never reclaimed.+ var agent = testChildAgent(io, session.allocator(), "acct-1");+ agent.provider.api_key = "startup-tok";++ // Nothing changed on disk: every request re-reads, and none of it may stick.+ const settled = blk: {+ var i: usize = 0;+ while (i < 4) : (i += 1) refreshLoginKeyBeforeSend(&agent);+ break :blk session.queryCapacity();+ };+ var i: usize = 0;+ while (i < 200) : (i += 1) refreshLoginKeyBeforeSend(&agent);+ try std.testing.expectEqual(settled, session.queryCapacity());+ try std.testing.expectEqualStrings("startup-tok", agent.provider.api_key);++ // `graff login` in another terminal, mid-session: picked up on the very next+ // request, with its account id, without waiting for a 401 — and the WS+ // transport the dead credential latched off is handed back.+ try writeTestAuth(io, arena, codex_home, "relogin-tok", "", "acct-1");+ refreshLoginKeyBeforeSend(&agent);+ try std.testing.expectEqualStrings("relogin-tok", agent.provider.api_key);+ try std.testing.expect(!agent.ws_off);++ // An env-sourced key has no login file behind it and must never be touched.+ agent.provider.source = .environment;+ try writeTestAuth(io, arena, codex_home, "third-tok", "", "acct-1");+ refreshLoginKeyBeforeSend(&agent);+ try std.testing.expectEqualStrings("relogin-tok", agent.provider.api_key);+}+/// #148/#402: a login-sourced credential was rejected. Adopt a token an/// in-session `/login` (or another process) has already written to disk, else/// spend the refresh grant — then retry the request once with the new bearer.