Skip to content

The agent that grows with you

refactor(process): the spawn ledger's cross-process lock reuses active_sessions._FileLock

kshitijk4poor0ce0c4337ee3
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.py
index d23c157bbce..987ddbaa433 100644
--- a/hermes_cli/process_identity.py
+++ b/hermes_cli/process_identity.py
@@ -23,7 +23,7 @@ import subprocess
import sys
import threading
import time
-from contextlib import contextmanager, suppress
+from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
from dataclasses import asdict, dataclass
from pathlib import Path
@@ -460,34 +460,6 @@ def _new_entry(
)
-@contextmanager
-def _ledger_file_lock(lock_path: Path) -> Iterator[None]:
- """Hold an exclusive lock on ``lock_path`` for the ledger's read-modify-write. Best-effort like the
- write itself: a lock file that cannot be opened or locked leaves the thread lock as the only guard."""
- from hermes_cli.active_sessions import _flock
-
- try:
- from hermes_constants import mkdir_under_hermes_home
- mkdir_under_hermes_home(lock_path.parent)
- fh = open(lock_path, "a+", encoding="utf-8")
- except OSError:
- logger.debug("spawn ledger lock unavailable", exc_info=True)
- yield
- return
- with fh:
- try:
- _flock(fh, lock=True)
- except OSError:
- logger.debug("spawn ledger lock failed", exc_info=True)
- yield
- return
- try:
- yield
- finally:
- with suppress(OSError):
- _flock(fh, lock=False)
-
-
def _append_entry(entry: LedgerEntry) -> bool:
"""Prune dead entries and append ``entry`` — the ONLY ledger write path.
@@ -497,8 +469,15 @@ def _append_entry(entry: LedgerEntry) -> bool:
See #91660.
"""
+ from hermes_cli.active_sessions import _FileLock
+
path = _ledger_path()
- with _LEDGER_LOCK, _ledger_file_lock(path.with_name(path.name + ".lock")):
+ with _LEDGER_LOCK, ExitStack() as held:
+ try:
+ held.enter_context(_FileLock(path.with_name(path.name + ".lock")))
+ except (RuntimeError, OSError):
+ # Best-effort like the write itself: the thread lock is then the only guard.
+ logger.debug("spawn ledger lock unavailable", exc_info=True)
entries = _read_ledger_or_quarantine(path) or []
# Drop malformed entries, our own stale entry, and provably dead pids.
pruned = [