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
40 changes: 23 additions & 17 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ from __future__ import annotations

import argparse
import base64
import ctypes
import datetime as dt
import errno
from email.utils import parsedate_to_datetime
Expand Down Expand Up @@ -201,9 +202,20 @@ 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
def _rename_noreplace(source: Path, target: Path) -> None:
"""Publish a shared entry atomically, including directories."""
libc = ctypes.CDLL(None, use_errno=True)

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: libc handle and renameat2 lookup are repeated for every entry

ctypes.CDLL(None, use_errno=True) and the renameat2 lookup run on every promoted entry. Resolve them once, either lazily at module level or with functools.cache, and set argtypes/restype (c_int, c_char_p, c_int, c_char_p, c_uint) so the call ABI is explicit and does not depend on ctypes' default int conversion. This also gives one place to decide the unsupported-platform behaviour raised in the other finding.

renameat2 = getattr(libc, "renameat2", None)
if renameat2 is None:
Comment thread
eowca marked this conversation as resolved.
Resolved
raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2")
renameat2.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint)
at_fdcwd, rename_noreplace = -100, 1
if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace):
error = ctypes.get_errno()
raise OSError(error, os.strerror(error), source, None, target)


def _copy_across_devices(entry: Path, target: Path) -> None:
# 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:
Expand All @@ -214,16 +226,7 @@ def _copy_across_devices(entry: Path, target: Path) -> None:
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)
_rename_noreplace(staged, target)
if is_directory:
shutil.rmtree(entry)
else:
Expand All @@ -237,13 +240,16 @@ def _sync_codex_home(home: Path) -> None:
if shared(entry) and not entry.is_symlink() and not target.exists() \
and not target.is_symlink():
try:
os.rename(entry, target)
except FileNotFoundError:
pass
try:
_rename_noreplace(entry, target)
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
_copy_across_devices(entry, target)
except OSError as exc:
if exc.errno != errno.EXDEV:
if exc.errno not in {errno.EEXIST, errno.ENOENT, errno.ENOSYS, errno.EINVAL,

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: Unsupported no-replace silently stops promotion with no warning

If renameat2 is missing (ENOSYS) or the filesystem rejects RENAME_NOREPLACE (EINVAL/EOPNOTSUPP), or the homes are on different filesystems (EXDEV), every shared entry created in an extra home stays local on every sync. Nothing tells the user, so the homes can drift apart permanently while sync appears to succeed. Leaving the entry in place is the safe choice. But these errnos mean the setup can't promote, not that another writer got there first. The smallest fix is to keep swallowing EEXIST/ENOENT silently and print a one-line warning to stderr for the unsupported or cross-device errnos.

errno.EOPNOTSUPP}:
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 @@ -618,3 +618,28 @@ def stage(src, dst, **kwargs):
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])


@pytest.mark.parametrize("unsupported", [None, "ENOSYS", "EINVAL"])
def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch, unsupported):
home = helper.codex_home("extra")
home.mkdir(parents=True)
helper.CODEX_MAIN.mkdir()
source = home / "sessions"
source.mkdir()
(source / "old").write_text("keep local")
(home / "notes").write_text("promote")
rename = helper._rename_noreplace

def create_destination(entry, target):
if entry == source:
target.mkdir()
if unsupported:

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: Unsupported-errno cases only run with a destination that already exists

In the ENOSYS/EINVAL cases, the stub creates target and then raises. So the test never covers the main unsupported scenario: the destination is still absent and promotion fails. In that case the source should stay local and unlinked, and other entries should still be mirrored. Add one case where the stub raises before creating the target, then check that source is still a real directory in the extra home, nothing was created in CODEX_MAIN, and notes is still promoted.

raise OSError(getattr(helper.errno, unsupported), "no-replace unsupported")
rename(entry, target)

monkeypatch.setattr(helper, "_rename_noreplace", create_destination)
helper.sync_codex_home(home)
assert (source / "old").read_text() == "keep local"
assert list((helper.CODEX_MAIN / "sessions").iterdir()) == []
assert (home / "notes").is_symlink() and (home / "notes").read_text() == "promote"
Loading