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
34 changes: 34 additions & 0 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ from __future__ import annotations
import argparse
import base64
import datetime as dt
import errno
from email.utils import parsedate_to_datetime
import fcntl
import hashlib
Expand Down Expand Up @@ -200,6 +201,35 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None:
_sync_codex_home(home)


def _copy_across_devices(entry: Path, target: Path) -> None:
import ctypes

# The private staging directory is also excluded from future mirroring
# by shared() if the process is interrupted before cleanup.
with tempfile.TemporaryDirectory(dir=target.parent, prefix=".codex-sync-", suffix=".lock") as directory:

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: Staging directories left by an interrupted sync accumulate in ~/.codex

shared() excludes the .codex-sync-*.lock staging directories from mirroring, but nothing ever deletes them. A SIGKILL or power loss during a large copytree leaves a full copy of the entry in CODEX_MAIN. While still holding the sync lock, consider removing stale .codex-sync-*.lock directories at the start of _sync_codex_home.

staged = Path(directory) / entry.name
is_directory = entry.is_dir()
if is_directory:
shutil.copytree(entry, staged, symlinks=True)
else:
shutil.copy2(entry, staged, follow_symlinks=False)

# Linux/WSL renameat2 with RENAME_NOREPLACE publishes the complete
# entry in one operation without replacing a competing destination.
rename = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None)
if rename is None:
raise OSError(errno.ENOSYS, "Atomic cross-device publication is unavailable", target)
if rename(-100, os.fsencode(staged), -100, os.fsencode(target), 1):
error = ctypes.get_errno()
if error == errno.EEXIST:
return
raise OSError(error, os.strerror(error), target)
if is_directory:

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: Copy-then-delete can drop writes that a running Codex process makes to the original

A same-device os.rename keeps the inode, so a Codex process that already has the entry open (for example, appending to session-index.jsonl or writing under sessions/) keeps writing into what becomes the shared file. On EXDEV the code copies first and then runs shutil.rmtree(entry) / entry.unlink(). Anything written to the original after the copy starts is lost when the original is removed. .codex-sync.lock only stops two syncs from running at once; it does not stop Codex from writing. If another Codex process can use the same extra home while an account is being selected, either document this limitation or check that nothing changed (size/mtime) before deleting the original.

shutil.rmtree(entry)
else:

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: A failure partway through removing the original leaves a partial private copy that is never repaired

If shutil.rmtree(entry) fails after publication (permission error, busy file), the shared target exists but the extra home keeps a partly deleted real directory. On later syncs that entry is skipped (target.exists()), and the mirror step also skips it (dst.exists()), so the account keeps seeing the incomplete copy for good. A crash between renameat2 and the removal leaves the same state with a full copy. One fix is to first rename the original to a hidden name in its own home (same device) and then remove it, or to remove an existing non-symlink entry on a later sync when the shared target already exists.

entry.unlink()


def _sync_codex_home(home: Path) -> None:
"""Mirror shared Codex files while holding the home lock."""
for entry in home.iterdir():
Expand All @@ -210,6 +240,10 @@ def _sync_codex_home(home: Path) -> None:
os.rename(entry, target)
except FileNotFoundError:
pass
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
_copy_across_devices(entry, target)
for src in CODEX_MAIN.iterdir():
dst = home / src.name
if shared(src) and not dst.exists() and not dst.is_symlink():
Expand Down
25 changes: 25 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import importlib.machinery
import importlib.util
import json
import tempfile
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -593,3 +594,27 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper):
with pytest.raises(OSError), helper._locked(".codex-sync.lock"):
pytest.fail("redirected lock opened")
assert lock.read_text() == "preserve"


@pytest.mark.parametrize("outcome", ["published", "copy failed"])

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: The new test covers only files, and the copy-failure stub cannot reach the directory path

The test moves only a regular file. shutil.copytree binds copy_function=copy2 when the module is defined, so monkeypatching helper.shutil.copy2 would not interrupt a directory copy anyway. As a result, the copytree/rmtree branch has no automated coverage. Add a directory case, for example a nested sessions/ directory, and interrupt it by patching helper.shutil.copytree. Also, PEP 8 expects two blank lines before the new top-level decorator.

def test_account_env_moves_shared_entry_across_devices(helper, monkeypatch, outcome):
if not Path("/dev/shm").is_dir() or Path("/dev/shm").stat().st_dev == helper.STATE.stat().st_dev:
pytest.skip("requires two filesystems")
entry = helper.codex_home("extra") / "session-index.jsonl"
helper.write_private(entry, "original")
helper.write_private(entry.with_name("auth.json"), "{}")
copy = helper.shutil.copy2
with tempfile.TemporaryDirectory(dir="/dev/shm") as main:
monkeypatch.setattr(helper, "CODEX_MAIN", Path(main))
def stage(src, dst, **kwargs):
copy(src, dst, **kwargs)
if outcome == "copy failed":
raise OSError("copy interrupted")
monkeypatch.setattr(helper.shutil, "copy2", stage)
if outcome == "copy failed":
with pytest.raises(OSError, match="copy interrupted"):
helper.account_env("codex", "extra")
else:
helper.account_env("codex", "extra")
assert entry.read_text() == "original" and entry.is_symlink() == (outcome == "published")
assert list(Path(main).iterdir()) == ([] if outcome == "copy failed" else [Path(main) / entry.name])
Loading