Skip to content

The agent that grows with you

fix(auth): detect the lock holder for real and route permanent lock failures

liuhao1024d67278cd882b
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 3c5ae498919..70a13529ac4 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -12,6 +12,7 @@
from __future__ import annotations
from pm import install_hint
+import errno
import json
import logging
import os
@@ -601,6 +602,63 @@ def _kernel_lock(lock_file: Any, acquire: bool) -> None:
msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1)
+# Errnos that mean the lock is held rather than broken. POSIX flock contention is a
+# ``BlockingIOError`` (EAGAIN); msvcrt reports contention as EACCES — which a real ACL denial
+# also uses, so EACCES stays retried rather than aborting every Windows lock. Anything else
+# (ENOSYS, EOPNOTSUPP, EIO, ...) cannot clear by retrying and must propagate immediately.
+_LOCK_CONTENTION_ERRNOS = frozenset(
+ code for code in (errno.EACCES, errno.EAGAIN, getattr(errno, "EDEADLK", None)) if code is not None)
+
+
+def _is_lock_contention(exc: OSError) -> bool:
+ if isinstance(exc, BlockingIOError):
+ return True
+ return exc.errno in _LOCK_CONTENTION_ERRNOS
+
+
+def _lock_holder_hint(lock_path: Path) -> str:
+ """Live-holder hint from the pid a holder stamps into the lock file; empty when there is none.
+
+ Holders stamp their pid on acquire and clear it on release, so a leftover pid from a dead
+ process is filtered by a liveness probe — stay silent instead of blaming a ghost."""
+ try:
+ first_token = lock_path.read_text(encoding="utf-8", errors="replace").split()[0]
+ pid = int(first_token)
+ except (OSError, ValueError, IndexError):
+ return ""
+ if pid <= 0 or pid == os.getpid():
+ return ""
+ if os.name == "posix":
+ try:
+ os.kill(pid, 0) # existence probe only; on Windows sig 0 would terminate the process
+ except ProcessLookupError:
+ return ""
+ except OSError:
+ pass # exists but is not signalable (e.g. EPERM): still a live holder
+ return (f"another hermes process (pid {pid}) probably still holds it "
+ "(e.g. a dashboard or a slow credential refresh)")
+
+
+def _stamp_lock_holder_pid(lock_file: Any) -> None:
+ """Best-effort pid stamp so a timing-out waiter can name the holder (#124533)."""
+ try:
+ lock_file.truncate(0)
+ lock_file.write(f"{os.getpid()}\n") # "a+" writes land at the (now empty) end
+ lock_file.flush()
+ except OSError:
+ pass
+
+
+def _clear_stamped_lock_holder_pid(lock_file: Any) -> None:
+ try:
+ lock_file.truncate(0)
+ if msvcrt:
+ lock_file.write(" ") # msvcrt.locking needs a non-empty file
+ lock_file.flush()
+ except OSError:
+ pass
+
+
@contextmanager
def _file_lock(
lock_path: Path, holder: threading.local, timeout_seconds: float, timeout_message: str):
@@ -636,17 +694,26 @@ def _file_lock(
try:
_kernel_lock(lock_file, True)
break
- except (BlockingIOError, OSError, PermissionError):
+ except (BlockingIOError, OSError, PermissionError) as exc:
+ if not _is_lock_contention(exc):
+ # Permanent failure (flock-unsupported filesystem, bad fd, ...): retrying
+ # to the deadline would burn the timeout blaming a holder that does not
+ # exist. Let the original error through instead.
+ raise
if time.monotonic() >= deadline:
- raise TimeoutError(timeout_message)
+ hint = _lock_holder_hint(lock_path)
+ raise TimeoutError(f"{timeout_message}; {hint}" if hint else timeout_message)
time.sleep(0.05)
holder.depth = 1
try:
+ if lock_file is not None:
+ _stamp_lock_holder_pid(lock_file)
yield
finally:
holder.depth = 0
if lock_file is not None:
+ _clear_stamped_lock_holder_pid(lock_file)
try:
_kernel_lock(lock_file, False)
except (OSError, IOError):
@@ -662,9 +729,10 @@ def _auth_store_lock(
reentrancy tracker and kernel lock. Lock ordering invariant: ``_auth_store_lock`` FIRST (outer),
``_nous_shared_store_lock`` SECOND (inner), else deadlock against a concurrent shared import."""
auth_path = target_path if target_path is not None else _auth_file_path()
+ lock_path = auth_path.with_suffix(".lock")
with _file_lock(
- auth_path.with_suffix(".lock"), _auth_lock_holder_for(auth_path), timeout_seconds,
- "Timed out waiting for auth store lock"):
+ lock_path, _auth_lock_holder_for(auth_path), timeout_seconds,
+ f"Timed out waiting for auth store lock ({lock_path})"):
yield
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index 9e79f39e50a..23d3489587f 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -376,7 +376,7 @@ def _nous_shared_store_lock(timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS):
return
with _file_lock(
lock_path, _nous_shared_lock_holder, timeout_seconds,
- "Timed out waiting for shared Nous auth lock"):
+ f"Timed out waiting for shared Nous auth lock ({lock_path})"):
yield
diff --git a/tests/hermes_cli/test_auth_lock_timeout_diagnosis.py b/tests/hermes_cli/test_auth_lock_timeout_diagnosis.py
new file mode 100644
index 00000000000..ca8b50ffe86
--- /dev/null
+++ b/tests/hermes_cli/test_auth_lock_timeout_diagnosis.py
@@ -0,0 +1,105 @@
+"""The auth-store lock timeout must name the lock file, and a holder only when one is real.
+
+``_auth_store_lock`` serializes auth.json transactions across processes, but a holder can keep
+the lock across a slow OAuth refresh POST, so a waiter (e.g. a Desktop assistant start) times out
+after ~15s while every credential is perfectly fine (#124533). The TimeoutError names the lock
+file, and names the holder only when the lock file carries a live foreign pid — never as an
+unconditional literal for a timeout with no holder. Permanent lock failures (flock-unsupported
+filesystem, ENOSYS/EOPNOTSUPP) must propagate immediately instead of burning the deadline
+telling the user to kill a process that does not exist.
+"""
+
+from __future__ import annotations
+
+import errno
+import os
+
+import pytest
+
+
+def _busy_kernel_lock(*args, **kwargs):
+ raise BlockingIOError()
+
+
+def test_lock_timeout_names_the_lock_file_and_a_live_holder(tmp_path, monkeypatch):
+ import hermes_cli.auth as auth
+
+ monkeypatch.setattr(auth, "_kernel_lock", _busy_kernel_lock)
+ holder_pid = os.getppid() # the test runner's parent: a live foreign process by construction
+ auth_path = tmp_path / "profiles" / "coder" / "auth.json"
+ auth_path.parent.mkdir(parents=True, exist_ok=True)
+ auth_path.with_suffix(".lock").write_text(f"{holder_pid}\n", encoding="utf-8")
+
+ with pytest.raises(TimeoutError) as excinfo:
+ with auth._auth_store_lock(timeout_seconds=0.01, target_path=auth_path):
+ pass
+
+ message = str(excinfo.value)
+ assert "Timed out waiting for auth store lock" in message
+ assert str(auth_path.with_suffix(".lock")) in message # which file is contended
+ assert f"pid {holder_pid}" in message # and who is holding it — detected, not assumed
+
+
+def test_lock_timeout_without_a_holder_stays_silent_about_one(tmp_path, monkeypatch):
+ import hermes_cli.auth as auth
+
+ monkeypatch.setattr(auth, "_kernel_lock", _busy_kernel_lock)
+ auth_path = tmp_path / "profiles" / "coder" / "auth.json"
+
+ with pytest.raises(TimeoutError) as excinfo:
+ with auth._auth_store_lock(timeout_seconds=0.01, target_path=auth_path):
+ pass
+
+ message = str(excinfo.value)
+ assert str(auth_path.with_suffix(".lock")) in message
+ assert "another hermes process" not in message # no holder detected: no one to blame
+
+
[email protected](os.name != "posix", reason="holder liveness probe is POSIX-only (os.kill sig 0)")
+def test_lock_timeout_ignores_a_stale_pid_from_a_dead_holder(tmp_path, monkeypatch):
+ import hermes_cli.auth as auth
+
+ monkeypatch.setattr(auth, "_kernel_lock", _busy_kernel_lock)
+ stale_pid = 2 ** 22 # far beyond any pid namespace: probe must report "no such process"
+ real_kill = os.kill
+
+ def _no_such_process(pid, sig):
+ if pid == stale_pid:
+ raise ProcessLookupError()
+ return real_kill(pid, sig)
+
+ monkeypatch.setattr(os, "kill", _no_such_process)
+ auth_path = tmp_path / "profiles" / "coder" / "auth.json"
+ auth_path.parent.mkdir(parents=True, exist_ok=True)
+ auth_path.with_suffix(".lock").write_text(f"{stale_pid}\n", encoding="utf-8")
+
+ with pytest.raises(TimeoutError) as excinfo:
+ with auth._auth_store_lock(timeout_seconds=0.01, target_path=auth_path):
+ pass
+
+ assert f"pid {stale_pid}" not in str(excinfo.value)
+
+
+def test_permanent_lock_failure_propagates_instead_of_burning_the_deadline(tmp_path, monkeypatch):
+ import hermes_cli.auth as auth
+
+ def _unsupported(*args, **kwargs):
+ raise OSError(errno.ENOSYS, "flock not supported on this filesystem")
+
+ monkeypatch.setattr(auth, "_kernel_lock", _unsupported)
+ auth_path = tmp_path / "profiles" / "coder" / "auth.json"
+
+ with pytest.raises(OSError) as excinfo:
+ with auth._auth_store_lock(timeout_seconds=0.01, target_path=auth_path):
+ pass
+
+ assert excinfo.value.errno == errno.ENOSYS # the original error, not a lock-holder blame
+
+
+def test_lock_timeout_message_still_matches_the_documented_prefix():
+ # Downstream diagnosis (tui_gateway.user_messages) matches on this prefix; keep it stable.
+ import hermes_cli.auth as auth
+ import inspect
+
+ source = inspect.getsource(auth._auth_store_lock)
+ assert "Timed out waiting for auth store lock" in source
diff --git a/tests/tui_gateway/test_user_messages.py b/tests/tui_gateway/test_user_messages.py
new file mode 100644
index 00000000000..cbbeaf08221
--- /dev/null
+++ b/tests/tui_gateway/test_user_messages.py
@@ -0,0 +1,39 @@
+"""User-facing copy for assistant-start failures must match the failure's actual cause.
+
+When init dies waiting for a cross-process auth lock — the profile auth-store lock or the shared
+Nous store lock, both on the ``resolve_nous_access_token`` init path (#124533) — the cause is
+contention with another hermes process (a dashboard or a slow credential refresh), so the generic
+/model / `hermes setup` hints would send the user re-checking credentials that are fine.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tui_gateway.user_messages import agent_init_failed_message
+
+
[email protected]("exc_text", [
+ "Timed out waiting for auth store lock (/home/u/.hermes/profiles/coder/auth.lock); "
+ "another hermes process (pid 4242) probably still holds it "
+ "(e.g. a dashboard or a slow credential refresh)",
+ "Timed out waiting for auth store lock (/home/u/.hermes/profiles/coder/auth.lock)",
+ "Timed out waiting for shared Nous auth lock (/home/u/.hermes/shared/nous.lock)",
+], ids=["auth-store-with-holder", "auth-store-no-holder", "shared-nous-store"])
+def test_auth_lock_timeout_contention_gets_the_wait_copy(exc_text):
+ message = agent_init_failed_message(TimeoutError(exc_text))
+ assert "/model" not in message
+ assert "hermes setup" not in message
+ assert "lock" in message and "dashboard" in message # actionable: what holds it, what to do
+
+
+def test_generic_timeout_keeps_the_model_setup_hints():
+ # A TimeoutError that is NOT an auth lock (e.g. a network connect timeout) must not
+ # be misread as lock contention.
+ message = agent_init_failed_message(TimeoutError("connect timed out"))
+ assert "/model" in message and "hermes setup" in message
+
+
+def test_other_init_failures_keep_the_model_setup_hints():
+ message = agent_init_failed_message(RuntimeError("provider bootstrap failed"))
+ assert "/model" in message and "hermes setup" in message
diff --git a/tui_gateway/user_messages.py b/tui_gateway/user_messages.py
index 7822c058746..877fd6d183a 100644
--- a/tui_gateway/user_messages.py
+++ b/tui_gateway/user_messages.py
@@ -91,7 +91,23 @@ def busy_message(command: str) -> str:
f"or Ctrl+C in a terminal), then run /{command.lstrip('/')}.")
+# Prefixes of the TimeoutErrors raised by ``hermes_cli.auth._auth_store_lock`` (profile
+# auth.json) and ``hermes_cli.auth_nous._nous_shared_store_lock`` (cross-profile shared store)
+# when the advisory lock times out (#124533). Both sit on the assistant-init path
+# (``resolve_nous_access_token`` acquires the shared lock inside the profile lock), and init
+# died on lock contention there — the generic /model /setup hints would send the user
+# debugging credentials that are perfectly fine.
+_AUTH_LOCK_TIMEOUT_PREFIXES = (
+ "Timed out waiting for auth store lock",
+ "Timed out waiting for shared Nous auth lock",
+)
+
+
def agent_init_failed_message(exc: Any) -> str:
+ if any(prefix in str(exc) for prefix in _AUTH_LOCK_TIMEOUT_PREFIXES):
+ return (f"Hermes could not start the assistant for this session. Details: {exc}. "
+ "Wait for the other process to release the lock (or exit it — check for a running "
+ "dashboard or background hermes process), then retry.")
return (f"Hermes could not start the assistant for this session. Details: {exc}. "
"Check the model and provider with /model, or run `hermes setup` in a terminal to reconfigure.")