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
23 changes: 15 additions & 8 deletions hermes_cli/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,7 @@ def _auth_lock_path() -> Path:


_auth_lock_holder = threading.local()
_global_root_lock_holder = threading.local()


@contextmanager
Expand Down Expand Up @@ -4037,14 +4038,20 @@ def _write_through_xai_oauth_to_global_root(state: Dict[str, Any]) -> None:
except Exception:
return
try:
if global_path.exists():
global_store = _load_auth_store(global_path)
else:
global_store = {}
if not isinstance(global_store, dict):
return
_store_provider_state(global_store, "xai-oauth", dict(state), set_active=False)
_save_auth_store(global_store, global_path)
with _file_lock(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This lock protects only the non-pool helper. agent/credential_pool.py:529-537 performs the same global-root read-modify-write for xai-oauth without taking this sidecar lock, so a pool refresh can still race this code. Please share the global-root locking mechanism with that helper.

global_path.with_suffix(".lock"),
_global_root_lock_holder,
AUTH_LOCK_TIMEOUT_SECONDS,
"Timed out waiting for global root auth store lock",
):
if global_path.exists():
global_store = _load_auth_store(global_path)
else:
global_store = {}
if not isinstance(global_store, dict):
return
_store_provider_state(global_store, "xai-oauth", dict(state), set_active=False)
_save_auth_store(global_store, global_path)
except Exception as exc: # pragma: no cover - best effort
logger.debug("xAI OAuth: write-through to global root failed: %s", exc)

Expand Down
62 changes: 62 additions & 0 deletions tests/hermes_cli/test_xai_oauth_writethrough.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"""

import json
import threading

import pytest

Expand Down Expand Up @@ -167,3 +168,64 @@ def _exploding_save(store, target_path=None):

profile = _read_store(profile_path)
assert profile["providers"]["xai-oauth"]["tokens"]["refresh_token"] == "r"


def test_concurrent_write_through_does_not_lose_second_token(profile_and_root):
"""Concurrent write-throughs must serialize; final root holds one complete token set."""
profile_path, root_path = profile_and_root
_write_store(profile_path, {"version": 1, "providers": {}})
_write_store(
root_path,
{
"version": 1,
"providers": {
"xai-oauth": {
"tokens": {"access_token": "old-access", "refresh_token": "old-refresh"}
}
},
},
)

state_a = {
"tokens": {"access_token": "token-A-access", "refresh_token": "token-A-refresh"},
"auth_mode": "oauth_pkce",
}
state_b = {
"tokens": {"access_token": "token-B-access", "refresh_token": "token-B-refresh"},
"auth_mode": "oauth_pkce",
}

errors = []
barrier = threading.Barrier(2)

def write_a():
try:
barrier.wait()
auth._write_through_xai_oauth_to_global_root(state_a)
except Exception as exc:
errors.append(exc)

def write_b():
try:
barrier.wait()
auth._write_through_xai_oauth_to_global_root(state_b)
except Exception as exc:
errors.append(exc)

t1 = threading.Thread(target=write_a)
t2 = threading.Thread(target=write_b)
t1.start()
t2.start()
t1.join()
t2.join()

assert not errors, f"Threads raised exceptions: {errors}"

root = _read_store(root_path)
final_tokens = root["providers"]["xai-oauth"]["tokens"]

token_a = {"access_token": "token-A-access", "refresh_token": "token-A-refresh"}
token_b = {"access_token": "token-B-access", "refresh_token": "token-B-refresh"}
assert final_tokens == token_a or final_tokens == token_b, (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This accepts the pre-fix last-writer-wins result as well: _save_auth_store already atomically replaces a complete JSON payload. Please make the test observe mutual exclusion or assert preservation of independent concurrent root-store updates.

f"Expected one complete token set (A or B), got corrupted mix: {final_tokens}"
)
Loading