Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -607,10 +607,13 @@ def refresh_codex(auth_file: Path, auth: dict) -> tuple[str, dict]:
fresh = json.loads(raw)
tokens.update({k: fresh[k] for k in ("id_token", "access_token", "refresh_token") if fresh.get(k)})
auth["last_refresh"] = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
# Rewrite in place like Codex: reviewers bind-mount this inode, so os.replace would detach them.
with open(auth_file, "r+", encoding="utf-8") as fh:
fh.write(json.dumps(auth, indent=2) + "\n")
fh.truncate()
# Reviewers bind-mount this inode. Pad shorter JSON with whitespace so
# the completed write is readable without a second, interruptible truncate.
payload = (json.dumps(auth, indent=2) + "\n").encode("utf-8")
with auth_file.open("r+b", buffering=0) as fh:
payload = payload.ljust(os.fstat(fh.fileno()).st_size, b" ")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Auth file never shrinks after a refresh, so it keeps its largest size

Because ljust(st_size) pads every refresh to the current file size, auth.json stays at the largest size it has ever had, and trailing spaces build up. This is safe: json.loads in identity() and the other readers, and Codex's serde_json, all accept trailing whitespace, and the padding overwrites the old token bytes, so nothing stale is left behind. The size is also capped by the largest payload written. Still, a future reader that compares raw bytes or checks the length would see unexpected padding. A short note in the comment saying the size is intentionally monotonic would make this clear. Optionally, the test could also cover a refresh whose payload is longer than the existing file, so the extend path is exercised too.

if os.pwrite(fh.fileno(), payload, 0) != len(payload):
raise OSError("incomplete Codex auth write")
log(f"codex: refreshed {auth_file}")
return tokens["access_token"], tokens

Expand Down
18 changes: 16 additions & 2 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,25 @@ def test_codex_select_reserves_current_at_85_without_churn(helper):
def test_codex_refresh_keeps_managed_binding_and_exhaustion_selection(helper, monkeypatch):
auth = helper.CODEX_MAIN / 'auth.json'
principal = {'account_id': 'account-a', 'id_token': 'e30.eyJzdWIiOiJ1c2VyLWEiLCJpc3MiOiJpc3N1ZXIifQ.x'}
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old'}}))
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old' * 100, 'refresh_token': 'old-refresh'}}))
helper.write_private(helper.STATE / 'codex/homes/b/auth.json', json.dumps({'tokens': {'account_id': 'account-b', 'access_token': 'other'}}))
helper.set_active('codex', 'main')
inherited = helper.with_accounts('codex', {})
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'fresh', 'refresh_token': 'rotated'}}))
refreshed = {"access_token": "fresh", "refresh_token": "rotated"}
monkeypatch.setattr(helper, "_http", lambda _: (200, {}, json.dumps(refreshed)))
write = helper.os.pwrite

def interrupt(fd, data, offset):
write(fd, data, offset)
raise KeyboardInterrupt

with auth.open("rb") as pinned, monkeypatch.context() as patch:
patch.setattr(helper.os, "pwrite", interrupt)
patch.setattr(helper, "jwt_claims", lambda _: {"client_id": "test"})
with pytest.raises(KeyboardInterrupt):
helper.refresh_codex(auth, json.loads(auth.read_text()))
assert json.load(pinned)["tokens"] == {**principal, **refreshed}
assert auth.stat().st_ino == helper.os.fstat(pinned.fileno()).st_ino
revision = inherited['AI_ACCOUNTS_CODEX_IDENTITY']
assert helper.managed_name('codex', inherited) == 'main'
monkeypatch.setattr(helper, 'check_codex', lambda name: {'tier': 2, 'util': 0, 'models': {'m': True}})
Expand Down
Loading