Skip to content
Closed
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
73 changes: 53 additions & 20 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,22 @@ def shared(entry: Path) -> bool:
return entry.name not in CODEX_PRIVATE and not entry.name.endswith(".lock")


def sync_codex_home(home: Path) -> None:
class AccountLockTimeout(TimeoutError):
Comment thread
eowca marked this conversation as resolved.
Resolved
Comment thread
eowca marked this conversation as resolved.
Resolved
Comment thread
eowca marked this conversation as resolved.
Resolved
Comment thread
eowca marked this conversation as resolved.
Resolved
pass


def _acquire_lock(lock) -> None:
deadline = time.monotonic() + 60
while (remaining := deadline - time.monotonic()) > 0:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return
except BlockingIOError:
time.sleep(min(0.1, remaining))
raise AccountLockTimeout(f"{Path(lock.name).name} is busy; retry when the other command finishes")


def sync_codex_home(home: Path, *, create: bool = False) -> None:
"""Keep an extra CODEX_HOME a mirror of ~/.codex except its own auth.json.

Entries the account created itself move into ~/.codex (unless ~/.codex already has one),
Expand All @@ -173,7 +188,9 @@ def sync_codex_home(home: Path) -> None:
# Own lock (check() holds .lock while calling this); Codex may still create entries
# concurrently, so a lost race on one entry is skipped, not fatal.
with open(STATE / ".codex-sync.lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
if create:
home.mkdir(parents=True, exist_ok=True, mode=0o700)
for entry in home.iterdir():
target = CODEX_MAIN / entry.name
if shared(entry) and not entry.is_symlink() and not target.exists() \
Expand Down Expand Up @@ -719,19 +736,20 @@ def snapshot_fields(result: dict, instance: str, checked_at: float) -> None:
def check(quiet: bool = False) -> dict:
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(STATE / ".lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
try:
previous = json.loads((STATE / "status.json").read_text())
except (OSError, ValueError):
previous = {}
status = {"checked_at": now(), "providers": {},
"exhausted": previous.get("exhausted", {}),
"selections": previous.get("selections", {})}
codex_names = accounts("codex")
for name in codex_names:
if name != "main":
sync_codex_home(codex_home(name))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: A monitor timeout can leave earlier Codex homes modified

check acquires and releases .codex-sync.lock separately for each extra home. With two extra homes, the first sync can move files into ~/.codex and create links before another process takes the lock and stalls the second sync. The command then reports a timeout after changing account files. Acquire the existing home lock once for the sync batch under the state lock, and reuse the per-home sync logic while holding it.

for provider in PROVIDERS:
names = accounts(provider)
if provider == "codex":
for n in names[1:] if names[:1] == ["main"] else names:
sync_codex_home(codex_home(n))
names = codex_names if provider == "codex" else accounts(provider)
probe = check_claude if provider == "claude" else check_codex
results = {n: probe(n) for n in names}
if provider == "claude":
Expand Down Expand Up @@ -839,8 +857,7 @@ def cmd_add(provider: str, name: str) -> int:
print(f"stored claude account {name}; run `ai-accounts check`")
return 0
home = STATE / "codex/homes" / name
home.mkdir(parents=True, exist_ok=True, mode=0o700)
sync_codex_home(home)
sync_codex_home(home, create=True)
print(f"created {home} (shares ~/.codex except its own auth.json)")
print(f"now log in with the other ChatGPT account: CODEX_HOME={home} codex login")
return 0
Expand All @@ -854,7 +871,7 @@ def cmd_exec(providers: str, argv: list[str]) -> int:
if "claude" in providers.split(",") and not caller_credentials("claude", base):
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(STATE / ".lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
name = active("claude")
# The monitor switches only at the 95% margin; prefer any account under the reserve.
if claude_exec_refusal(name) is not None:
Expand Down Expand Up @@ -901,7 +918,7 @@ def launch(provider: str, model: str, env: dict[str, str]) -> dict:
if caller_credentials(provider, env) or not STATE.is_dir() or not accounts(provider):
return result("unmanaged")
with open(STATE / ".lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
try:
status = json.loads((STATE / "status.json").read_text())
except (OSError, ValueError):
Expand Down Expand Up @@ -943,14 +960,16 @@ def cmd_pinned_exec(provider: str, revision: str, argv: list[str]) -> int:
name = None
if provider in PROVIDERS and STATE.is_dir() and not caller_credentials(provider, env):
with open(STATE / ".lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
for candidate in accounts(provider):
try:
if identity(provider, candidate) == revision:
env.update(account_env(provider, candidate))
if env.get(marker(provider)) == revision:
name = candidate
break
except AccountLockTimeout:
raise
except (OSError, ValueError):
continue
if name is None or not argv:
Expand All @@ -963,7 +982,7 @@ def cmd_pinned_exec(provider: str, revision: str, argv: list[str]) -> int:
return 127


def exhausted(provider: str, failed_identity: str, model: str) -> dict:
def exhausted(provider: str, failed_identity: str, model: str, *, prepare=None) -> dict:
"""Compare-and-select for one exact provider/model, serialized with monitor checks.

The caller sends only the opaque managed revision from its effective environment.
Expand All @@ -980,7 +999,7 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict:
if not STATE.is_dir():
return result("unmanaged")
with open(STATE / ".lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
revisions = {}
for name in accounts(provider):
try:
Expand Down Expand Up @@ -1018,6 +1037,8 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict:
known = False
if usable or not known:
if usable:
if prepare is not None:
prepare(current)
selected[selection_key] = {"identity": current_id, "until": now() + 300}
write_private(STATE / "status.json", json.dumps(status) + "\n")
return result("already-switched" if usable else "unknown", current)
Expand All @@ -1037,6 +1058,8 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict:
unknown = True
if candidates:
chosen = min(candidates)[1]
if prepare is not None:
prepare(chosen)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: A retry can refresh standby credentials before the home lock times out

When cmd_run retries from main to an idle Codex account with a nearly expired token, candidate selection calls model_availability before prepare(chosen). Its check_codex probe can rotate the refresh token and rewrite the standby account’s auth.json. If .codex-sync.lock is held, preparation then times out after the credential update. The new test stubs model_availability, which hides this path. Make candidate probing read-only until the required home lock has been acquired, and cover a refresh-eligible standby with a held lock.

set_active(provider, chosen)
selected[selection_key] = {"identity": identity(provider, chosen), "until": now() + 300}
outcome = result("already-switched" if chosen == current else "switched", chosen)
Expand All @@ -1050,8 +1073,8 @@ def cmd_run(providers: str, argv: list[str], retry_exit: set[int] | None = None,
base: dict[str, str] | None = None, model: str | None = None,
retry_safe: bool = False) -> int:
"""Preserve stdout streaming; replay only one identified managed provider/model."""
env = with_accounts(providers, dict(os.environ) if base is None else base)
for attempt in (1, 2):
env = with_accounts(providers, dict(os.environ) if base is None else base)
proc = subprocess.Popen(argv, env=env, stderr=subprocess.PIPE)
seen: list[bytes] = []

Expand All @@ -1073,10 +1096,15 @@ def cmd_run(providers: str, argv: list[str], retry_exit: set[int] | None = None,
or not USAGE_LIMIT_RE.search(text) or managed_name(providers, env) is None):
return code
before = env[marker(providers)]
outcome = exhausted(providers, before, model)
after = with_accounts(providers, env)
if not retry_safe or not outcome["changed"] or after.get(marker(providers)) == before:
after = {}

def prepare(name):
after.update(account_env(providers, name))

outcome = exhausted(providers, before, model, prepare=prepare if retry_safe else None)
if not outcome["changed"] or not after or after.get(marker(providers)) == before:
return code
env.update(after)
print("ai-accounts: managed account changed; retrying once", file=sys.stderr)
return code

Expand Down Expand Up @@ -1160,7 +1188,7 @@ def main(argv: list[str]) -> int:
sys.exit(f"ai-accounts: unknown {argv[1]} account {argv[2]!r}")
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(STATE / ".lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
_acquire_lock(lock)
set_active(argv[1], argv[2])
log(f"{argv[1]}: manual -> {argv[2]}")
print(f"{argv[1]} active: {argv[2]}")
Expand Down Expand Up @@ -1202,4 +1230,9 @@ def main(argv: list[str]) -> int:

if __name__ == "__main__":
shim = Path(sys.argv[0]).name
sys.exit(cmd_shim(shim, sys.argv[1:]) if shim in SHIMS else main(sys.argv[1:]))
try:
code = cmd_shim(shim, sys.argv[1:]) if shim in SHIMS else main(sys.argv[1:])
except AccountLockTimeout as exc:
print(f"ai-accounts: {exc}", file=sys.stderr)
code = 1
sys.exit(code)
59 changes: 59 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,3 +491,62 @@ def test_status_prints_account_email_after_plan(helper, capsys, provider, email,
result = {'tier': 0, 'plan': 'max', 'email': email, 'windows': [], 'unknown_reason': 'no data'}
helper.print_status({'checked_at': helper.now(), 'providers': {provider: {'active': 'a', 'accounts': {'a': result}}}})
assert shown in capsys.readouterr().out


@pytest.mark.parametrize("name", [".lock", ".codex-sync.lock"])
def test_account_lock_wait_is_bounded(helper, tmp_path, monkeypatch, name):
elapsed = 0.0

def advance(seconds):
nonlocal elapsed
elapsed += seconds

monkeypatch.setattr(helper.time, "monotonic", lambda: elapsed)
monkeypatch.setattr(helper.time, "sleep", advance)
with (helper.STATE / name).open("a") as holder:
helper.fcntl.flock(holder, helper.fcntl.LOCK_EX)
with pytest.raises(helper.AccountLockTimeout, match=r"is busy.*retry"):
if name == ".lock":
helper.check(quiet=True)
else:
helper.sync_codex_home(tmp_path / "unreadable-home")
assert elapsed == 60
assert not (helper.STATE / "status.json").exists()


def test_home_lock_timeout_does_not_publish_selections(helper, monkeypatch):
for name in ("main", "b"):
auth = {"tokens": {"account_id": name, "access_token": "synthetic"}}
helper.write_private(helper.codex_home(name) / "auth.json", json.dumps(auth))
helper.set_active("codex", "main")
for key in (*helper.EXPLICIT_ROUTES["codex"], "CODEX_HOME"):
monkeypatch.delenv(key, raising=False)
elapsed = 0.0

def advance(seconds):
nonlocal elapsed
elapsed += seconds

monkeypatch.setattr(helper.time, "monotonic", lambda: elapsed)
monkeypatch.setattr(helper.time, "sleep", advance)
monkeypatch.setattr(helper, "model_availability", lambda *_: (True, True, 0.1))
monkeypatch.setattr(helper, "check_claude", lambda *_: pytest.fail("rotation started before home sync"))
with (helper.STATE / ".codex-sync.lock").open("a") as holder:
helper.fcntl.flock(holder, helper.fcntl.LOCK_EX)
operations = (
lambda: helper.check(quiet=True),
lambda: helper.cmd_add("codex", "new"),
lambda: helper.cmd_pinned_exec("codex", helper.identity("codex", "b"), ["unused"]),
lambda: helper.exhausted(
"codex", helper.identity("codex", "main"), "model",
prepare=lambda name: helper.account_env("codex", name),
),
)
for operation in operations:
with pytest.raises(helper.AccountLockTimeout, match=r"\.codex-sync\.lock is busy"):
operation()
assert elapsed == 240
assert not helper.codex_home("new").exists()
assert helper.active("codex") == "main"
assert helper.active("claude") == "a"
assert not (helper.STATE / "status.json").exists()
Loading