From 84a45db962030042103ac9e6f0ee904439ff2413 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:18:34 +0200 Subject: [PATCH 1/3] fix(efficacy): keep a token a trial refreshed when the credential link is remade A trial's CLI saves a refreshed token as a new file, which breaks the scratch home's hard link to the account's credentials. The next re-link discarded that file and handed the next trial the rotated-out refresh token, so the trial failed at its first call and the run waited for a login. refresh_credentials now writes a home file that expires later back over the account's file, in place, before remaking the link. Closes #83 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xPB8YTAMW2Msp4aPTX --- docs/architecture/06-runtime-view.md | 6 ++- tests/efficacy/harness.py | 74 ++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/docs/architecture/06-runtime-view.md b/docs/architecture/06-runtime-view.md index dbf81e4..8ab4708 100644 --- a/docs/architecture/06-runtime-view.md +++ b/docs/architecture/06-runtime-view.md @@ -100,7 +100,11 @@ every trial, so a stopped run keeps every trial it finished. owner. The judge strips the copy with the context file. - **The credential file** in the scratch home is a hard link to the account's live one, remade before every trial, because another client of the - account rotates the tokens and an earlier copy would be revoked. + account rotates the tokens and an earlier copy would be revoked. A trial's + CLI that refreshes an expired token saves it as a new file, breaking the + link, so before the link is remade a home file that expires later is + written back over the account's. Dropping it ended `hybrid-1` and + `reference-4` of round 5c at their first call (#83). - **The temporary directory.** Git Bash maps `/tmp` to the machine's temporary directory whatever `TEMP` says, so an entry that appeared there during a trial and that a tool call names is moved into the trial's own. diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index f034181..58f2a81 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -607,7 +607,18 @@ def prepare_workspace(arm, trial, root, spec=SPEC): CREDENTIALS = os.path.join(".claude", ".credentials.json") -def refresh_credentials(home): +def expires_at(path): + """When a credentials file's access token expires, or 0 where it says + nothing readable.""" + try: + with io.open(path, encoding="utf-8") as handle: + stamp = json.load(handle)["claudeAiOauth"]["expiresAt"] + except (OSError, ValueError, KeyError, TypeError): + return 0 + return stamp if isinstance(stamp, (int, float)) else 0 + + +def refresh_credentials(home, account=None): """Give the scratch home the account's live credentials; say how. A hard link to the real file rather than a copy. Another client of the @@ -616,14 +627,26 @@ def refresh_credentials(home): ended a trial eighteen minutes in. Through the link a rotation written in place reaches the trial's CLI as it happens. Where no link can be made the file is copied, and the copy is taken again before every - trial and every probe, so at worst a trial starts fresh. + trial and every probe, so at worst a trial starts fresh. `account` + names the real file, for a test; it defaults to the user's own. """ - source = os.path.join(os.path.expanduser("~"), CREDENTIALS) + source = account or os.path.join(os.path.expanduser("~"), CREDENTIALS) target = os.path.join(home, CREDENTIALS) if not os.path.exists(source): return None os.makedirs(os.path.dirname(target), exist_ok=True) if os.path.lexists(target): + + # A trial's CLI that refreshes an expired token saves the new one as + # a new file, which breaks the link: the home then holds the only + # live refresh token, and the account's has been rotated out. It is + # written back over the account's file in place, keeping that file + # and its other links, before the link is remade; dropping it would + # hand the next trial a revoked token, and it ended two trials at + # their first call. + if (not os.path.samefile(source, target) + and expires_at(target) > expires_at(source)): + shutil.copyfile(target, source) os.remove(target) try: os.link(source, target) @@ -2798,6 +2821,48 @@ def hang_checks(): return checks +def credential_rotation_checks(): + """A token a trial refreshed into a file of its own reaches the account's + file before the link is remade, and an older one never does.""" + scratch = os.path.join(tempfile.gettempdir(), + "efficacy-credential-rotation-self-test") + remove_tree(scratch) + home = os.path.join(scratch, "home") + account = os.path.join(scratch, "account", ".credentials.json") + os.makedirs(os.path.dirname(account)) + target = os.path.join(home, CREDENTIALS) + + def write(path, expires): + # A new file each time, as the CLI saves a refreshed token. + if os.path.lexists(path): + os.remove(path) + with io.open(path, "w", encoding="utf-8") as handle: + json.dump({"claudeAiOauth": {"expiresAt": expires}}, handle) + + write(account, 1000) + refresh_credentials(home, account) + checks = [("the home links the account's file", + os.path.samefile(account, target))] + write(target, 2000) + refresh_credentials(home, account) + checks.append(("a token refreshed into a new file reaches the account's", + expires_at(account) == 2000 + and os.path.samefile(account, target))) + write(target, 500) + refresh_credentials(home, account) + checks.append(("an older home file leaves the account's as it was", + expires_at(account) == 2000 + and os.path.samefile(account, target))) + write(target, 3000) + write(account, 4000) + refresh_credentials(home, account) + checks.append(("an account file refreshed elsewhere is kept", + expires_at(account) == 4000 + and os.path.samefile(account, target))) + remove_tree(scratch) + return checks + + def credential_link_checks(): """The scratch home reads the account's live credentials, and gets them back before a trial where they went missing.""" @@ -3183,7 +3248,8 @@ def self_test(): """Prove the naming, isolation, outcome, resume, change and vendoring rules before a trial.""" checks = (naming_checks() + environment_checks() + credential_checks() - + credential_link_checks() + outcome_checks() + hang_checks() + + credential_link_checks() + credential_rotation_checks() + + outcome_checks() + hang_checks() + resume_checks() + change_checks() + dry_run_checks() + process_checks() + claim_checks() + leftover_checks() + reach_checks() + outside_checks() From 8e7bd7585fe3f25b6d103783b10d662d577ccad6 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:34:30 +0200 Subject: [PATCH 2/3] fix(efficacy): lock the credential write-back against a concurrent run The expiry comparison and the copy back were separate steps, so a second run could write a newer token between them and the first then overwrote it with its older one, in the account's file and every home linked to it. The compare, the write and the re-link now hold a lock file beside the account's credentials; a lock older than a minute, left by a dead run, is broken. Two self-test checks: the race, paused between the reads and the write, and a stale lock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xPB8YTAMW2Msp4aPTX --- docs/architecture/06-runtime-view.md | 4 +- tests/efficacy/harness.py | 110 ++++++++++++++++++++++----- 2 files changed, 95 insertions(+), 19 deletions(-) diff --git a/docs/architecture/06-runtime-view.md b/docs/architecture/06-runtime-view.md index 8ab4708..22cef0d 100644 --- a/docs/architecture/06-runtime-view.md +++ b/docs/architecture/06-runtime-view.md @@ -104,7 +104,9 @@ every trial, so a stopped run keeps every trial it finished. CLI that refreshes an expired token saves it as a new file, breaking the link, so before the link is remade a home file that expires later is written back over the account's. Dropping it ended `hybrid-1` and - `reference-4` of round 5c at their first call (#83). + `reference-4` of round 5c at their first call (#83). The compare, the + write and the re-link hold a lock file beside the account's, so two runs + writing back at once cannot leave the older token. - **The temporary directory.** Git Bash maps `/tmp` to the machine's temporary directory whatever `TEMP` says, so an entry that appeared there during a trial and that a tool call names is moved into the trial's own. diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index 58f2a81..b82a162 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -635,25 +635,60 @@ def refresh_credentials(home, account=None): if not os.path.exists(source): return None os.makedirs(os.path.dirname(target), exist_ok=True) - if os.path.lexists(target): - - # A trial's CLI that refreshes an expired token saves the new one as - # a new file, which breaks the link: the home then holds the only - # live refresh token, and the account's has been rotated out. It is - # written back over the account's file in place, keeping that file - # and its other links, before the link is remade; dropping it would - # hand the next trial a revoked token, and it ended two trials at - # their first call. - if (not os.path.samefile(source, target) - and expires_at(target) > expires_at(source)): - shutil.copyfile(target, source) - os.remove(target) + + # Two runs on one machine share the account's file. Without the lock one + # can read the expiries, the other write a newer token back, and the + # first then overwrite it with its older one. A CLI saving its own token + # takes no lock, but it replaces the file rather than writing into it, + # so a write racing it lands on the file it replaced. + with credential_lock(source): + if os.path.lexists(target): + + # A trial's CLI that refreshes an expired token saves the new one + # as a new file, which breaks the link: the home then holds the + # only live refresh token, and the account's has been rotated + # out. It is written back over the account's file in place, + # keeping that file and its other links, before the link is + # remade; dropping it would hand the next trial a revoked token, + # and it ended two trials at their first call. + if (not os.path.samefile(source, target) + and expires_at(target) > expires_at(source)): + shutil.copyfile(target, source) + os.remove(target) + try: + os.link(source, target) + return "linked" + except OSError: + shutil.copyfile(source, target) + return "copied" + + +@contextlib.contextmanager +def credential_lock(source, stale_s=60, poll_s=0.05): + """Hold the lock file beside the account's credentials while inside.""" + lock = source + ".lock" + while True: + try: + os.close(os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)) + break + except FileExistsError: + + # The lock is held for milliseconds, so one this old was left by + # a run that died holding it. + try: + if time.time() - os.path.getmtime(lock) > stale_s: + os.remove(lock) + continue + except OSError: + continue + time.sleep(poll_s) try: - os.link(source, target) - return "linked" - except OSError: - shutil.copyfile(source, target) - return "copied" + yield + finally: + try: + os.remove(lock) + except OSError: + pass def prepare_home(root): @@ -2859,6 +2894,45 @@ def write(path, expires): checks.append(("an account file refreshed elsewhere is kept", expires_at(account) == 4000 and os.path.samefile(account, target))) + + # Two runs refresh at once: this home holds 5000 and the other 6000. + # The other is started after this one has read the expiries and before + # it writes, the order that let the older token overwrite the newer. + other = os.path.join(scratch, "other") + refresh_credentials(other, account) + write(target, 5000) + write(os.path.join(other, CREDENTIALS), 6000) + plain = globals()["expires_at"] + racer = threading.Thread(target=refresh_credentials, + args=(other, account)) + + def paused(path): + stamp = plain(path) + if (path == account and racer.ident is None + and threading.current_thread() is threading.main_thread()): + racer.start() + time.sleep(0.5) + return stamp + + globals()["expires_at"] = paused + try: + refresh_credentials(home, account) + finally: + globals()["expires_at"] = plain + racer.join(30) + checks.append(("a newer token written back at the same time wins", + expires_at(account) == 6000 + and os.path.samefile(account, target) + and os.path.samefile(account, + os.path.join(other, CREDENTIALS)))) + + # A run that died holding the lock leaves it behind. + left = account + ".lock" + io.open(left, "w").close() + os.utime(left, (time.time() - 3600, time.time() - 3600)) + checks.append(("a lock left by a dead run is broken, not waited on", + refresh_credentials(home, account) == "linked" + and not os.path.exists(left))) remove_tree(scratch) return checks From d5c1430956cb58f21a8ec17c6e55b4814768545f Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:41:32 +0200 Subject: [PATCH 3/3] fix(efficacy): compare the account's credentials through the handle that writes them The lock holds off a second run, not the CLI, which saves its token by replacing the account's file. A save landing between the expiry comparison and copyfile() had its newer token overwritten, since copyfile() opened the replacement. write_back() now reads the account's expiry through the handle it then writes, and after writing checks the path still names that file; where a save replaced it, it compares again against the save rather than overwriting it. A self-test check races a replacement against the write-back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xPB8YTAMW2Msp4aPTX --- docs/architecture/06-runtime-view.md | 4 +- tests/efficacy/harness.py | 103 +++++++++++++++++++++------ 2 files changed, 86 insertions(+), 21 deletions(-) diff --git a/docs/architecture/06-runtime-view.md b/docs/architecture/06-runtime-view.md index 22cef0d..9e1d3f7 100644 --- a/docs/architecture/06-runtime-view.md +++ b/docs/architecture/06-runtime-view.md @@ -106,7 +106,9 @@ every trial, so a stopped run keeps every trial it finished. written back over the account's. Dropping it ended `hybrid-1` and `reference-4` of round 5c at their first call (#83). The compare, the write and the re-link hold a lock file beside the account's, so two runs - writing back at once cannot leave the older token. + writing back at once cannot leave the older token. The CLI takes no lock, + so the account's file is compared through the handle that writes it, and a + save that replaces it meanwhile is compared again rather than overwritten. - **The temporary directory.** Git Bash maps `/tmp` to the machine's temporary directory whatever `TEMP` says, so an entry that appeared there during a trial and that a tool call names is moved into the trial's own. diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index b82a162..9ba7704 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -607,15 +607,59 @@ def prepare_workspace(arm, trial, root, spec=SPEC): CREDENTIALS = os.path.join(".claude", ".credentials.json") +def expiry_of(data): + """When the access token in a credentials file's bytes expires, or 0 + where they say nothing readable.""" + try: + stamp = json.loads(data.decode("utf-8"))["claudeAiOauth"]["expiresAt"] + except (ValueError, KeyError, TypeError, AttributeError): + return 0 + return stamp if isinstance(stamp, (int, float)) else 0 + + def expires_at(path): """When a credentials file's access token expires, or 0 where it says nothing readable.""" try: - with io.open(path, encoding="utf-8") as handle: - stamp = json.load(handle)["claudeAiOauth"]["expiresAt"] - except (OSError, ValueError, KeyError, TypeError): + with io.open(path, "rb") as handle: + return expiry_of(handle.read()) + except OSError: return 0 - return stamp if isinstance(stamp, (int, float)) else 0 + + +def write_back(source, target, attempts=5): + """Write the home's credentials over the account's, in place, where they + expire later; True when they were written.""" + for _ in range(attempts): + try: + with io.open(target, "rb") as handle: + fresh = handle.read() + except OSError: + return False + expiry = expiry_of(fresh) + + # The account's file is compared through the handle that is then + # written, so the comparison is with the very file overwritten, not + # one a CLI's save has since put in its place. + with io.open(source, "r+b") as handle: + if expiry_of(handle.read()) >= expiry: + return False + handle.seek(0) + handle.write(fresh) + handle.truncate() + written = os.fstat(handle.fileno()) + + # A save that replaced the file after it was opened leaves the write + # on the file it replaced, and the account's is the save's. The next + # attempt compares against that one. + try: + current = os.stat(source) + except OSError: + continue + if (current.st_ino, current.st_dev) == (written.st_ino, + written.st_dev): + return True + return False def refresh_credentials(home, account=None): @@ -636,11 +680,9 @@ def refresh_credentials(home, account=None): return None os.makedirs(os.path.dirname(target), exist_ok=True) - # Two runs on one machine share the account's file. Without the lock one - # can read the expiries, the other write a newer token back, and the - # first then overwrite it with its older one. A CLI saving its own token - # takes no lock, but it replaces the file rather than writing into it, - # so a write racing it lands on the file it replaced. + # Two runs on one machine share the account's file, and the lock keeps + # one's write-back and re-link from interleaving with the other's. A CLI + # saving its own token takes no lock; the write-back guards against it. with credential_lock(source): if os.path.lexists(target): @@ -651,9 +693,8 @@ def refresh_credentials(home, account=None): # keeping that file and its other links, before the link is # remade; dropping it would hand the next trial a revoked token, # and it ended two trials at their first call. - if (not os.path.samefile(source, target) - and expires_at(target) > expires_at(source)): - shutil.copyfile(target, source) + if not os.path.samefile(source, target): + write_back(source, target) os.remove(target) try: os.link(source, target) @@ -2896,29 +2937,29 @@ def write(path, expires): and os.path.samefile(account, target))) # Two runs refresh at once: this home holds 5000 and the other 6000. - # The other is started after this one has read the expiries and before - # it writes, the order that let the older token overwrite the newer. + # The other is started after this one has read its home's file and + # before it writes. other = os.path.join(scratch, "other") refresh_credentials(other, account) write(target, 5000) write(os.path.join(other, CREDENTIALS), 6000) - plain = globals()["expires_at"] + plain = globals()["expiry_of"] racer = threading.Thread(target=refresh_credentials, args=(other, account)) - def paused(path): - stamp = plain(path) - if (path == account and racer.ident is None + def paused(data): + stamp = plain(data) + if (stamp == 5000 and racer.ident is None and threading.current_thread() is threading.main_thread()): racer.start() time.sleep(0.5) return stamp - globals()["expires_at"] = paused + globals()["expiry_of"] = paused try: refresh_credentials(home, account) finally: - globals()["expires_at"] = plain + globals()["expiry_of"] = plain racer.join(30) checks.append(("a newer token written back at the same time wins", expires_at(account) == 6000 @@ -2926,6 +2967,28 @@ def paused(path): and os.path.samefile(account, os.path.join(other, CREDENTIALS)))) + # A CLI's save replaces the account's file, taking no lock, after this + # run has read its home's file and before it writes. + write(target, 6500) + fresh = os.path.join(scratch, "saved.json") + with io.open(fresh, "w", encoding="utf-8") as handle: + json.dump({"claudeAiOauth": {"expiresAt": 7000}}, handle) + + def replaced(data): + stamp = plain(data) + if stamp == 6500 and os.path.exists(fresh): + os.replace(fresh, account) + return stamp + + globals()["expiry_of"] = replaced + try: + refresh_credentials(home, account) + finally: + globals()["expiry_of"] = plain + checks.append(("a CLI's save racing the write-back is not overwritten", + expires_at(account) == 7000 + and os.path.samefile(account, target))) + # A run that died holding the lock leaves it behind. left = account + ".lock" io.open(left, "w").close()