The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): /proc/locks readers no longer lose entries to other processes' lock churn
teknium135272ce28b29
diff --git a/hermes_state_lockowners.py b/hermes_state_lockowners.pyindex 01594c669e1..0db40bb2453 100644--- a/hermes_state_lockowners.py+++ b/hermes_state_lockowners.py@@ -93,15 +93,20 @@ def state_db_write_lock_holders(db_path) -> List[str]:except OSError:continueinodes[(st.st_dev, st.st_ino)] = sidecar- try:- with open("/proc/locks", encoding="ascii", errors="replace") as handle:- text = handle.read()- except OSError:- return []+ # /proc/locks is host-wide and served over several read()s: lock churn in other processes+ # shifts it mid-read and can skip the holder. A skip rarely repeats, so union three passes.+ held: List[Tuple[int, str, str]] = []+ for _ in range(3):+ try:+ with open("/proc/locks", encoding="ascii", errors="replace") as handle:+ text = handle.read()+ except OSError:+ return []+ held.extend(entry for entry in parse_proc_locks(text, inodes) if entry not in held)from hermes_state_holders import describe_holder_pidlines = []- for pid, kind, sidecar in parse_proc_locks(text, inodes):+ for pid, kind, sidecar in held:who = describe_holder_pid(pid) if pid > 0 else "OFD lock, owner pid not exported by the kernel"lines.append(f"{who} holds {kind} lock on {Path(base + sidecar).name}")return linesdiff --git a/tests/agent/test_live_db_preview_locks.py b/tests/agent/test_live_db_preview_locks.pyindex 007c56b72e9..8d1a6e121ec 100644--- a/tests/agent/test_live_db_preview_locks.py+++ b/tests/agent/test_live_db_preview_locks.py@@ -12,6 +12,7 @@ from fastapi import HTTPExceptionfrom agent.context_references import _expand_path_reference, parse_context_referencesfrom hermes_state import SessionDBfrom hermes_cli.web_routers.files import fs_download, fs_read_text+from tests.posix_lock_probe import own_posix_locks@pytest.mark.platforms("linux")@@ -43,12 +44,6 @@ def test_preview_preserves_live_database_locks(tmp_path, route, target_kind):lock_fd = os.open(path, os.O_RDONLY)fcntl.lockf(lock_fd, fcntl.LOCK_SH, 1, 4096)- def posix_locks(file):- inode = file.stat().st_ino- return sorted(line.split(": ", 1)[1] for line in Path("/proc/locks").read_text(encoding="utf-8").splitlines()- if f":{inode} " in line and "POSIX ADVISORY" in line- and f" {os.getpid()} " in line)-def rival_locked():code = ("import sqlite3,sys; c=sqlite3.connect(sys.argv[1], timeout=0); ""c.execute('BEGIN IMMEDIATE'); c.rollback(); c.close()")@@ -56,7 +51,7 @@ def test_preview_preserves_live_database_locks(tmp_path, route, target_kind):capture_output=True, text=True, timeout=10)return result.returncode != 0 and "database is locked" in result.stderr- before = (posix_locks(path), posix_locks(shm))+ before = (own_posix_locks(path), own_posix_locks(shm))assert all(before), "fixture must hold POSIX main and WAL-sidecar locks"assert rival_locked(), "second process must be excluded before the preview"@@ -81,7 +76,7 @@ def test_preview_preserves_live_database_locks(tmp_path, route, target_kind):warning, block = _expand_path_reference(ordinary, tmp_path.parent)assert warning is None and block is not None and "ordinary readable text" in block- assert (posix_locks(path), posix_locks(shm)) == before+ assert (own_posix_locks(path), own_posix_locks(shm)) == beforeassert rival_locked(), "second process entered a still-open write transaction"conn.commit()code = (diff --git a/tests/hermes_state/test_state_db_file_identity.py b/tests/hermes_state/test_state_db_file_identity.pyindex c4dd51bcdba..8b945ab6be7 100644--- a/tests/hermes_state/test_state_db_file_identity.py+++ b/tests/hermes_state/test_state_db_file_identity.py@@ -13,6 +13,8 @@ from pathlib import Pathimport pytest+from tests.posix_lock_probe import own_posix_locks+from hermes_state import (SessionDB,StateDbReplacedError,@@ -185,7 +187,7 @@ def test_divert_session_transcript_jsonl_appends(tmp_path, monkeypatch):[{"role": "user", "content": "hello-jsonl"}],)assert path == tmp_path / "sessions" / "sess-jsonl.jsonl"- lines = path.read_text(encoding="utf-8").strip().splitlines()+ lines = path.read_text(encoding="utf-8-sig").strip().splitlines()assert json.loads(lines[-1])["content"] == "hello-jsonl"assert divert_session_transcript_jsonl("sess-jsonl", []) is None@@ -202,35 +204,10 @@ def _stat_changed(path: Path, recorded) -> bool:# Before the _pread_db_header fix it did open("rb")/read/close, and that# close() cancelled every POSIX advisory lock this process held on the file# — including the WAL-mode DMS shared lock of the writer connection. These-# tests measure the actual kernel lock table (/proc/locks), so they are+# tests measure this process's kernel lock table (/proc/self/fdinfo), so they are# Linux-only; the hazard itself is POSIX-only.# ----------------------------------------------------------------------------def _posix_locks_on(paths):- """Set of (inode, type, mode, start, end) locks held by this pid."""- import sys as _sys- if not _sys.platform.startswith("linux"):- pytest.skip("lock-table probe requires /proc/locks (Linux)")- inodes = {}- for p in paths:- try:- inodes[os.stat(p).st_ino] = str(p)- except OSError:- continue- pid = os.getpid()- held = set()- for line in Path("/proc/locks").read_text().splitlines():- parts = line.split()- try:- lpid = int(parts[4])- ino = int(parts[5].split(":")[2])- except (IndexError, ValueError):- continue- if lpid == pid and ino in inodes:- held.add((ino, parts[1], parts[3], parts[6], parts[7]))- return held--@pytest.mark.platforms("linux")def test_identity_probe_does_not_cancel_live_posix_locks(tmp_path):"""The on-write header probe must not drop the writer's DMS lock."""@@ -247,13 +224,13 @@ def test_identity_probe_does_not_cancel_live_posix_locks(tmp_path):db._conn.execute("UPDATE sessions SET source = source WHERE id = 'probe-sess'")- before = _posix_locks_on([live])+ before = own_posix_locks(live)assert before, "expected in-transaction WAL connection to lock state.db"for _ in range(3):_read_sqlite_application_id(live)- after = _posix_locks_on([live])+ after = own_posix_locks(live)db._conn.rollback()# Only locks on the main file prove the header probe safe. WAL-index# read-lock slots on -shm may legitimately move while SQLite runs, anddiff --git a/tests/hermes_state/test_write_lock_owner_attribution.py b/tests/hermes_state/test_write_lock_owner_attribution.pyindex 5cd869d7288..b8acc1d1336 100644--- a/tests/hermes_state/test_write_lock_owner_attribution.py+++ b/tests/hermes_state/test_write_lock_owner_attribution.py@@ -5,6 +5,7 @@ identified the victim only; every Hermes process has the DB open, so the descripsingle out the writer. ``/proc/locks`` can."""+import ioimport osimport sqlite3import subprocess@@ -33,6 +34,22 @@ def test_parse_proc_locks_keeps_only_write_locks_on_our_inodes_and_decodes_the_w][email protected]("linux")+def test_holder_skipped_by_one_proc_locks_pass_is_still_named(tmp_path, monkeypatch):+ """/proc/locks is served over several read()s, so churn elsewhere can skip an entry in one pass."""+ import hermes_state_lockowners++ db = tmp_path / "state.db"+ db.write_bytes(b"")+ st = os.stat(db)+ held = (f"1: POSIX ADVISORY WRITE {os.getpid()} "+ f"{os.major(st.st_dev):02x}:{os.minor(st.st_dev):02x}:{st.st_ino} 1073741825 1073741825\n")+ passes = iter(["", held, ""])+ monkeypatch.setattr(hermes_state_lockowners, "open", lambda *a, **k: io.StringIO(next(passes)), raising=False)+ lines = state_db_write_lock_holders(db)+ assert len(lines) == 1 and f"PID {os.getpid()} " in lines[0] and "RESERVED" in lines[0], lines++@pytest.mark.platforms("linux")def test_live_writer_in_another_process_is_named_by_pid(tmp_path):db = tmp_path / "state.db"diff --git a/tests/posix_lock_probe.py b/tests/posix_lock_probe.pynew file mode 100644index 00000000000..85216da04e5--- /dev/null+++ b/tests/posix_lock_probe.py@@ -0,0 +1,31 @@+"""This process's POSIX advisory locks on a file, read from ``/proc/self/fdinfo`` (Linux).++Not ``/proc/locks``: that table is host-wide and the kernel serves it over several ``read()``+calls, so lock churn in other processes (a parallel test run) shifts it mid-read and silently+skips entries — a lock this process still holds reads as cancelled. ``fdinfo`` lists this+process's locks per open file and is read in one call.+"""+import os+from pathlib import Path+++def own_posix_locks(*paths) -> list[str]:+ """Sorted ``"POSIX ADVISORY <type> <pid> <dev>:<ino> <start> <end>"`` lines this process holds on *paths*."""+ targets = set()+ for path in paths:+ try:+ st = os.stat(path)+ except OSError:+ continue+ targets.add((st.st_dev, st.st_ino))+ found = set()+ for fd in os.listdir("/proc/self/fd"):+ try:+ st = os.stat(f"/proc/self/fd/{fd}")+ info = Path(f"/proc/self/fdinfo/{fd}").read_text(encoding="utf-8")+ except OSError:+ continue+ if (st.st_dev, st.st_ino) in targets:+ found.update(line.split(": ", 1)[1] for line in info.splitlines()+ if line.startswith("lock:") and "POSIX ADVISORY" in line)+ return sorted(found)