Skip to content

The agent that grows with you

fix(state): qualify lock/lease holder pid probes by PID namespace

aleesposito856c6ce6149e58
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index a1b410ab735..7946b7759a4 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1772,10 +1772,14 @@ def recover_rotated_compression_session(agent: Any) -> Optional[List[Dict[str, A
def _compression_lock_holder(agent: Any) -> str:
- """Build a unique lock holder id: ``pid:tid:agent-instance:uuid``.
+ """Build a unique lock holder id: ``pid[:pidns]:tid:agent-instance:uuid``.
pid+tid tell crashed holders apart in diagnostics; instance id and per-acquire uuid disambiguate
- co-resident agents on one thread or pooled compressions."""
- return f"pid={os.getpid()}:tid={threading.get_ident()}:agent={id(agent):x}:nonce={uuid.uuid4().hex[:8]}"
+ co-resident agents on one thread or pooled compressions. ``pidns`` (the PID-namespace id) keeps a
+ sibling sharing this state.db from reclaiming the lock on a local PID probe — see
+ ``hermes_state_pidns``."""
+ from hermes_state_pidns import holder_namespace_token
+ return (f"pid={os.getpid()}{holder_namespace_token()}:tid={threading.get_ident()}"
+ f":agent={id(agent):x}:nonce={uuid.uuid4().hex[:8]}")
def _supported_compression_kwargs(
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index 2f1b14bf397..1f0592fae82 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -257,8 +257,13 @@ def admit_durable_turn_lease(
# X-Hermes-Session-Id, /v1/runs session_id, fingerprint-derived chat ids) are not
# process-unique, and the first turn creates the row mid-turn, so a second writer would
# otherwise find the row, take an unheld lease and interleave its turn into this one.
+ # The pidns stamp keeps a sibling sharing this state.db (its own PID namespace, where
+ # this pid reads as absent) from reclaiming a live lease on a local PID probe — see
+ # hermes_state_pidns / hermes_state._compression_lock_holder_process_is_dead.
+ from hermes_state_pidns import holder_namespace_token
holder = (
- f"pid={os.getpid()}:turn={relay_turn_id}:platform={task_context['platform'] or 'unknown'}"
+ f"pid={os.getpid()}{holder_namespace_token()}:turn={relay_turn_id}"
+ f":platform={task_context['platform'] or 'unknown'}"
)
reload_needed = announced = False
diff --git a/hermes_state.py b/hermes_state.py
index 858e6675007..26361d843c9 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -136,11 +136,21 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool:
"""True only when a ``pid=<n>`` lock holder's local PID is provably gone.
Reclaim on kernel proof only: unstructured/same-process holders (another
thread's live lease) and any probe doubt keep the lease until TTL expiry
- (PID reuse must never steal a live lease; a wrongly-kept one self-heals)."""
+ (PID reuse must never steal a live lease; a wrongly-kept one self-heals).
+
+ A PID is namespace-relative: siblings sharing one state.db from different
+ PID namespaces (containers on one volume, systemd ``PrivatePIDs=``) see
+ disjoint PID sets, so a local absence is only proof for a holder stamped
+ with OUR namespace. Holders stamp ``pidns=<id>`` at write time
+ (``hermes_state_pidns``); a foreign or unstamped holder is never reclaimed
+ on a local PID probe — it releases by TTL expiry instead."""
match = re.search(r"(?:^|:)pid=(\d+)(?::|$)", holder or "")
pid = int(match.group(1)) if match else 0
if pid <= 0 or pid == os.getpid():
return False
+ from hermes_state_pidns import holder_pid_checkable
+ if not holder_pid_checkable(holder):
+ return False # foreign / unknown namespace: defer to TTL
if psutil is not None:
try:
return not psutil.pid_exists(pid) # recycled PIDs read as alive (conservative)
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 19260b42de2..8de1a64818c 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -1127,9 +1127,14 @@ def _write_lock_holder_record(handle) -> None:
from a live wedged one.
Written under the flock so contenders that time out can tell an orphaned-fd holder (recorded process
- dead, flock inherited by a forked child — issue #100108) from a live wedged holder.
+ dead, flock inherited by a forked child — issue #100108) from a live wedged holder. ``pidns`` is the
+ writer's PID-namespace id: the record outlives the process and is probed by contenders sharing the
+ lock file from possibly disjoint PID namespaces (containers on one volume), so a local probe alone
+ must never be treated as proof about a foreign holder.
"""
- record = {"pid": os.getpid(), "start_ticks": _proc_start_ticks(os.getpid()), "acquired_at": time.time()}
+ from hermes_state_pidns import pid_namespace_id
+ record = {"pid": os.getpid(), "pidns": pid_namespace_id(),
+ "start_ticks": _proc_start_ticks(os.getpid()), "acquired_at": time.time()}
_rewrite_lock_file(handle, json.dumps(record, sort_keys=True).encode("utf-8"))
@@ -1140,13 +1145,20 @@ def _clear_lock_holder_record(handle) -> None:
def _lock_holder_provably_dead(record) -> bool:
"""True ONLY when the recorded holder is provably dead or PID-recycled. Anything indeterminate
- (no/malformed record, PID owned by another user, /proc unavailable) is False: FAIL CLOSED and defer."""
+ (no/malformed record, PID owned by another user, /proc unavailable, foreign PID namespace)
+ is False: FAIL CLOSED and defer. An unstamped record (pre-upgrade writer) keeps main's
+ behavior on purpose — these records never expire, so refusing to probe them would
+ permanently disable orphaned-lock cleanup (the rollout boundary; see
+ ``hermes_state_pidns``)."""
try:
pid = int(record["pid"])
except (KeyError, TypeError, ValueError):
return False
if pid <= 0:
return False
+ from hermes_state_pidns import persistent_record_pidns_checkable
+ if not persistent_record_pidns_checkable(record.get("pidns")):
+ return False # foreign namespace: a local reading is not proof — defer
try:
os.kill(pid, 0)
except ProcessLookupError:
diff --git a/hermes_state_pidns.py b/hermes_state_pidns.py
new file mode 100644
index 00000000000..448eb8cab99
--- /dev/null
+++ b/hermes_state_pidns.py
@@ -0,0 +1,177 @@
+"""PID-namespace identity for state.db lock/lease holders (the probe-provenance owner).
+
+A ``pid=<n>`` lock holder (compression lock, session turn lease) is written by the
+process that owns it, relative to THAT process's PID namespace. Readers sharing
+one state.db from a different namespace — two containers on one volume, systemd
+``PrivatePIDs=``, any container-per-process layout — see a disjoint PID set, so
+a sibling's live ``pid=`` reads as absent and the namespace-blind probe (the
+historic ``psutil.pid_exists(pid)``) declares a live holder dead and reclaims
+its unexpired row. For a session turn lease that ends the sibling's in-flight
+turn ("another Hermes process took over this session"); for a compression lock
+it splits the compression lineage. The same class applies to the flock holder
+records in ``hermes_state_common`` (``pid=`` recorded by a holder that forks
+then dies).
+
+This module owns the identity resolution and the qualification every structured
+holder probe goes through. It is a leaf: it imports nothing from the
+``hermes_state*`` modules at load time, so ``hermes_state`` and
+``hermes_state_common`` can import it without a cycle. The identity is the
+``/proc/self/ns/pid`` inode — the kernel's own answer to "which PID namespace am
+I in" — the same identity the namespace-relative work for gateway records and
+scoped locks (issue #123081) resolves for its records.
+
+Two predicates, one qualification rule, two rollouts. A record STAMPED with a
+namespace is probed only where the stamp is ours; a foreign stamp is never
+probed (the reader's absence reading says nothing about a process in another
+namespace). What differs between the predicates is what an UNSTAMPED record —
+written by a build that predates the stamp — defaults to:
+
+* :func:`holder_pid_checkable` — STRICT, for TTL-bounded rows (compression
+ locks, session turn leases). Unstamped holders are not probed; they defer to
+ their own expiry — at most the remaining TTL (300 s), and a false defer
+ self-heals there. The asymmetry is deliberate (probe doubt already defers,
+ for the same reason): a false reclaim ends a live sibling's turn and cannot
+ be undone, while a false defer costs a bounded wait. Strictness is also what
+ makes the fix hold during a mixed-version rollout — the stealer side stops
+ stealing as soon as the READER restarts, no writer restart required.
+
+* :func:`persistent_record_pidns_checkable` — LEGACY ROLLOUT, for records with
+ no expiry (the flock holder records). An unstamped record keeps main's
+ behavior: those records never expire, so refusing to probe an unstamped one
+ would make it permanently unverifiable and silently disable orphaned-lock
+ cleanup on every install that had not yet restarted — the rollout boundary
+ the namespace-relative-identity work documents for gateway records.
+ Protection begins as writers restart and stamp; a foreign stamp is still
+ never probed.
+
+Tri-state, mirroring how the platform reports other facts:
+
+* ``supported=False`` — the platform has no PID-namespace concept (macOS,
+ Windows). There is exactly one namespace, so a numeric PID is still
+ evidence and every predicate returns True (main's semantics).
+* ``supported=True`` with an ``id`` — resolved.
+* ``supported=True`` with an ``id`` of None — Linux, but the lookup failed
+ (restricted or unmounted ``/proc``). A failed lookup is NOT cached and NOT
+ authority: absence of provenance cannot become provenance, so every
+ structured holder is unverifiable and defers.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from typing import NamedTuple, Optional
+
+# ``pidns=`` token inside a structured holder string (``pid=123:pidns=4026533184:turn=…``).
+_PIDNS_TOKEN_RE = re.compile(r"(?:^|:)pidns=(\d+)(?::|$)")
+
+
+class LocalPidNamespace(NamedTuple):
+ """What this process knows about its own PID namespace.
+
+ Three states, and the ``checkable`` predicates treat each differently:
+ ``supported`` False — the platform has no namespace identity at all;
+ ``supported`` True with an ``id`` — resolved; ``supported`` True with an
+ ``id`` of None — resolution failed, see the module docstring.
+ """
+
+ id: Optional[str]
+ supported: bool
+
+
+_UNSUPPORTED = LocalPidNamespace(None, False)
+
+# Cached once there is a definite answer: a process cannot move itself into
+# another PID namespace (``setns`` applies to its future children), so a
+# successful read never changes for us. A failed read is NOT cached — it may
+# be transient, and while it lasts every structured holder is unverifiable.
+_LOCAL_PID_NS: Optional[LocalPidNamespace] = None
+
+
+def _parse_pid_namespace_link(link: str) -> Optional[str]:
+ """``"pid:[4026532534]"`` -> ``"4026532534"``; None when unparseable.
+
+ Split out from the resolver so the parsing can be tested as the pure
+ string -> string mapping it is, on any host.
+ """
+ match = re.search(r"\[(\d+)\]", link or "")
+ return match.group(1) if match else None
+
+
+def _resolve_local_pid_namespace() -> LocalPidNamespace:
+ if sys.platform != "linux":
+ return _UNSUPPORTED
+ try:
+ link = os.readlink("/proc/self/ns/pid")
+ except OSError:
+ return LocalPidNamespace(None, True)
+ return LocalPidNamespace(_parse_pid_namespace_link(link), True)
+
+
+def _local_pid_namespace() -> LocalPidNamespace:
+ """This process' PID-namespace identity (see :class:`LocalPidNamespace`)."""
+ global _LOCAL_PID_NS
+ if _LOCAL_PID_NS is None:
+ local = _resolve_local_pid_namespace()
+ if local.id is not None or not local.supported:
+ _LOCAL_PID_NS = local
+ return local
+ return _LOCAL_PID_NS
+
+
+def pid_namespace_id() -> Optional[str]:
+ """What a holder records: the ``/proc/self/ns/pid`` inode on Linux, ``None``
+ where there is no namespace identity or the lookup failed. A holder never
+ asserts a namespace it cannot prove."""
+ return _local_pid_namespace().id
+
+
+def holder_namespace_token() -> str:
+ """The ``:pidns=<id>`` fragment to append to a new holder string, or ``""``.
+
+ Callers build ``f"pid={os.getpid()}{holder_namespace_token()}:turn=…"``.
+ """
+ ns = pid_namespace_id()
+ return f":pidns={ns}" if ns else ""
+
+
+def recorded_namespace(holder: str) -> Optional[str]:
+ """The ``pidns=`` stamp from a holder string, or None when it carries none."""
+ match = _PIDNS_TOKEN_RE.search(holder or "")
+ return match.group(1) if match else None
+
+
+def _qualify(recorded: Optional[str], *, unstamped_checkable: bool) -> bool:
+ """The shared matrix; *unstamped_checkable* is the policy for a record that
+ carries no namespace (see the module docstring for why there are two)."""
+ local = _local_pid_namespace()
+ if not local.supported:
+ return True # single-namespace platform: a pid is evidence on its own
+ if local.id is None:
+ return False # our own lookup failed: unknown authority is not authority
+ if recorded is None:
+ return unstamped_checkable
+ return str(recorded) == str(local.id)
+
+
+def holder_pid_checkable(holder: str) -> bool:
+ """STRICT: may a structured holder string's ``pid=`` be probed here?
+
+ The policy for TTL-bounded rows (compression locks, session turn leases):
+ a foreign-namespace or unstamped holder is never probed — it defers to the
+ row's own expiry instead (at most the remaining TTL; a false defer
+ self-heals, a false reclaim ends a live turn).
+ """
+ return _qualify(recorded_namespace(holder), unstamped_checkable=False)
+
+
+def persistent_record_pidns_checkable(recorded: Optional[str]) -> bool:
+ """LEGACY ROLLOUT: may a persistent record (no expiry) be probed here?
+
+ The policy for the flock holder records: a foreign-namespace record is
+ never probed, while an unstamped one keeps main's behavior — those records
+ never expire, so refusing to probe them would permanently disable
+ orphaned-lock cleanup (see the module docstring).
+ """
+ return _qualify(recorded, unstamped_checkable=True)
diff --git a/tests/hermes_state/test_hermes_state_compression_locks.py b/tests/hermes_state/test_hermes_state_compression_locks.py
index 710297a7df7..566d53b2fe5 100644
--- a/tests/hermes_state/test_hermes_state_compression_locks.py
+++ b/tests/hermes_state/test_hermes_state_compression_locks.py
@@ -94,8 +94,11 @@ def test_non_expired_lock_from_dead_pid_is_reclaimed(
# No ``os.name`` pin: the probe below injects a fake ``psutil``, and
# ``_process_is_gone`` consults psutil *before* its POSIX/nt split — the
# nt early-return is unreachable here on any host, so faking the platform
- # bought nothing.
- dead_holder = "pid=424242:tid=1:agent=abc:nonce=deadbeef"
+ # bought nothing. The holder is stamped with this process's own PID
+ # namespace (same-namespace kernel proof is still proof; foreign and
+ # unstamped holders defer to TTL — see test_lease_pid_namespace.py).
+ from hermes_state_pidns import holder_namespace_token
+ dead_holder = f"pid=424242{holder_namespace_token()}:tid=1:agent=abc:nonce=deadbeef"
assert db.try_acquire_compression_lock(
"sess1", dead_holder, ttl_seconds=300
) is True
@@ -122,7 +125,11 @@ def test_probe_doubt_keeps_lease_until_ttl(
db: SessionDB, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A probe that errors out is doubt, not proof of death → TTL protects."""
- holder = "pid=424242:tid=1:agent=abc:nonce=doubt"
+ # Stamped with this process's own namespace so the probe path is actually
+ # reached (unstamped holders are gated before the probe — see
+ # test_lease_pid_namespace.py).
+ from hermes_state_pidns import holder_namespace_token
+ holder = f"pid=424242{holder_namespace_token()}:tid=1:agent=abc:nonce=doubt"
assert db.try_acquire_compression_lock(
"sess1", holder, ttl_seconds=300
) is True
diff --git a/tests/hermes_state/test_lease_pid_namespace.py b/tests/hermes_state/test_lease_pid_namespace.py
new file mode 100644
index 00000000000..29ea487d66b
--- /dev/null
+++ b/tests/hermes_state/test_lease_pid_namespace.py
@@ -0,0 +1,308 @@
+"""PID-namespace qualification for state.db lock/lease holder probes.
+
+A ``pid=<n>`` holder is namespace-relative: siblings sharing one ``state.db``
+from different PID namespaces (the standard gateway + webui container layout
+on one volume, systemd ``PrivatePIDs=``) see disjoint PID sets, so a live
+sibling's holder reads as absent to a namespace-blind ``psutil.pid_exists()``
+probe — and the unexpired row is reclaimed under the sibling's feet. For a
+session turn lease that ends the sibling's in-flight turn ("another Hermes
+process took over this session"); for a compression lock it splits the
+compression lineage. For the flock holder records (``hermes_state_common``) it
+breaks a live holder's lock.
+
+``hermes_state_pidns`` stamps every structured holder with the writer's PID
+namespace (``pidns=``, the ``/proc/self/ns/pid`` inode) and qualifies each
+probe on it. Two policies, one rule:
+
+* :func:`holder_pid_checkable` — STRICT, the policy for TTL-bounded rows
+ (compression locks, session turn leases). A same-namespace reading is still
+ kernel proof and crash cleanup is unchanged; a foreign-namespace OR unstamped
+ holder is never probed — it defers to the row's own expiry (at most the
+ remaining TTL; a false defer self-heals, a false reclaim loses a reply).
+ Strictness is also what stops a steal during a mixed-version rollout as soon
+ as the reader restarts, before every writer has.
+
+* :func:`persistent_record_pidns_checkable` — LEGACY ROLLOUT, the policy for
+ records with no expiry (the flock holder records). A foreign-namespace
+ record is never probed; an unstamped one keeps main's behavior (refusing to
+ probe it would permanently disable orphaned-lock cleanup).
+
+These tests pin the qualification matrix and the behavioral halves, plus the
+sibling-shape regression that motivated the stamp.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import time
+
+import psutil
+import pytest
+
+import hermes_state
+import hermes_state_common
+import hermes_state_pidns
+from hermes_state import SessionDB
+from hermes_state_pidns import (
+ LocalPidNamespace,
+ _parse_pid_namespace_link,
+ holder_namespace_token,
+ holder_pid_checkable,
+ persistent_record_pidns_checkable,
+ pid_namespace_id,
+ recorded_namespace,
+)
+
+
+def _dead_pid() -> int:
+ """A PID that is provably gone: spawn, reap, verify absence."""
+ proc = subprocess.Popen([sys.executable, "-c", "pass"])
+ proc.wait(timeout=30)
+ pid = proc.pid
+ assert not psutil.pid_exists(pid), "reaped pid unexpectedly reused"
+ return pid
+
+
+def _sibling_pidns() -> str:
+ """A namespace id that is not ours (linux-gated callers only)."""
+ return str(int(pid_namespace_id()) + 12345)
+
+
+def _ttl_holder(pid, pidns=None, *, suffix="turn=t:platform=test") -> str:
+ """A structured TTL-row holder string in the production shape."""
+ stamp = f":pidns={pidns}" if pidns is not None else ""
+ return f"pid={pid}{stamp}:{suffix}"
+
+
+# ---------------------------------------------------------------------------
+# Identity resolution (pure parts)
+# ---------------------------------------------------------------------------
+
+
+def test_parse_pid_namespace_link() -> None:
+ assert _parse_pid_namespace_link("pid:[4026532534]") == "4026532534"
+ assert _parse_pid_namespace_link("pid:[123]") == "123"
+ assert _parse_pid_namespace_link("") is None
+ assert _parse_pid_namespace_link("pid:no-brackets") is None
+
+
+def test_recorded_namespace_extracts_only_a_segment_bounded_token() -> None:
+ assert recorded_namespace("pid=1:pidns=42:turn=x") == "42"
+ assert recorded_namespace("pidns=42") == "42"
+ assert recorded_namespace("pid=1:tid=2:agent=ab:nonce=cd") is None
+ assert recorded_namespace("") is None
+ assert recorded_namespace(None) is None
+ # The token must start at a segment boundary — not some other key's suffix.
+ assert recorded_namespace("apidns=7") is None
+ assert recorded_namespace("x-pidns=7") is None
+
+
+ ("local", "recorded", "strict", "legacy"),
+ [
+ # Platform has no namespace concept (macOS/Windows): a pid is still
+ # evidence and both predicates keep main's semantics.
+ (LocalPidNamespace(None, False), None, True, True),
+ (LocalPidNamespace(None, False), "123", True, True),
+ # The diverging row: unstamped on Linux — strict defers (TTL-bounded
+ # rows must be protected during mixed-version rollouts), legacy probes
+ # (no-expiry records must not become permanently unverifiable).
+ (LocalPidNamespace("111", True), None, False, True),
+ # Linux: our own namespace verifies.
+ (LocalPidNamespace("111", True), "111", True, True),
+ # Linux: a sibling's namespace is never probed, under either policy.
+ (LocalPidNamespace("111", True), "222", False, False),
+ # Linux with a failed lookup: no authority — nothing is verifiable.
+ (LocalPidNamespace(None, True), None, False, False),
+ (LocalPidNamespace(None, True), "111", False, False),
+ ],
+)
+def test_namespace_qualification_matrix(monkeypatch, local, recorded, strict, legacy) -> None:
+ monkeypatch.setattr(hermes_state_pidns, "_LOCAL_PID_NS", local)
+ assert holder_pid_checkable(_ttl_holder(123, recorded)) is strict
+ assert persistent_record_pidns_checkable(recorded) is legacy
+
+
+def test_holder_namespace_token_round_trips_on_this_host() -> None:
+ token = holder_namespace_token()
+ assert token.startswith(":pidns=") and token[len(":pidns="):].isdigit()
+ holder = f"pid=123{token}:tid=1:agent=abc:nonce=deadbeef"
+ assert recorded_namespace(holder) == pid_namespace_id()
+ assert holder_pid_checkable(holder) is True
+
+
+def test_failed_namespace_lookup_is_not_cached_and_defers(monkeypatch) -> None:
+ """A transient /proc failure must not be cached, and while it lasts every
+ structured holder is unverifiable (defer, never probe)."""
+ calls: list[str] = []
+ real_readlink = os.readlink
+
+ def readlink(path):
+ if path == "/proc/self/ns/pid":
+ calls.append(path)
+ raise OSError("simulated readlink failure")
+ return real_readlink(path)
+
+ monkeypatch.setattr(hermes_state_pidns, "_LOCAL_PID_NS", None)
+ monkeypatch.setattr(hermes_state_pidns.os, "readlink", readlink)
+
+ assert hermes_state_pidns.pid_namespace_id() is None
+ assert hermes_state_pidns.pid_namespace_id() is None
+ assert len(calls) == 2, "a failed lookup must be retried, not cached"
+ assert holder_pid_checkable(_ttl_holder(1, "111")) is False
+ assert holder_pid_checkable(_ttl_holder(1)) is False
+ assert persistent_record_pidns_checkable("111") is False
+ assert persistent_record_pidns_checkable(None) is False
+
+
+# ---------------------------------------------------------------------------
+# Probe gate (the choke-point both lease kinds share)
+# ---------------------------------------------------------------------------
+
+
+def test_probe_gate_matrix() -> None:
+ dead = _dead_pid()
+ probe = hermes_state._compression_lock_holder_process_is_dead
+
+ # Same namespace + provably gone: still reclaimable on kernel proof.
+ assert probe(_ttl_holder(dead, pid_namespace_id())) is True
+ # Foreign namespace: our absence reading says nothing — defer (the bug).
+ assert probe(_ttl_holder(dead, _sibling_pidns())) is False
+ # Unstamped (pre-upgrade writer): TTL rows defer — see the module docstring.
+ assert probe(_ttl_holder(dead)) is False
+ # Unstructured and own-pid holders: never probed (existing contract).
+ assert probe("legacy_holder") is False
+ assert probe(_ttl_holder(os.getpid(), _sibling_pidns())) is False
+
+
+# ---------------------------------------------------------------------------
+# Behavioral: compression locks
+# ---------------------------------------------------------------------------
+
+
+def test_sibling_namespace_holder_survives_dead_local_pid(tmp_path) -> None:
+ """A sibling container's holder is invisible to our PID probe — the lock
+ must be kept (TTL still bounds it) instead of stolen."""
+ db = SessionDB(tmp_path / "state.db")
+ dead = _dead_pid()
+ sibling = f"pid={dead}:pidns={_sibling_pidns()}:tid=1:agent=sibling:nonce=aaaaaaaa"
+ assert db.try_acquire_compression_lock("sess1", sibling, ttl_seconds=300) is True
+
+ contender = f"pid={os.getpid()}:pidns={pid_namespace_id()}:tid=2:agent=us:nonce=bbbbbbbb"
+ assert db.try_acquire_compression_lock("sess1", contender, ttl_seconds=300) is False
+ assert db.get_compression_lock_holder("sess1") == sibling
+
+
+def test_unstamped_legacy_holder_defers_to_ttl(tmp_path) -> None:
+ """TTL rows written before the stamp cannot be told apart from a live
+ sibling's — defer, never steal; the row's own expiry is the release path."""
+ db = SessionDB(tmp_path / "state.db")
+ dead = _dead_pid()
+ legacy = f"pid={dead}:tid=1:agent=old:nonce=cccccccc"
+ assert db.try_acquire_compression_lock("sess1", legacy, ttl_seconds=0.2) is True
+
+ contender = f"pid={os.getpid()}:pidns={pid_namespace_id()}:tid=2:agent=us:nonce=dddddddd"
+ assert db.try_acquire_compression_lock("sess1", contender, ttl_seconds=300) is False
+ assert db.get_compression_lock_holder("sess1") == legacy
+
+ time.sleep(0.35)
+ assert db.try_acquire_compression_lock("sess1", contender, ttl_seconds=300) is True
+
+
+def test_same_namespace_dead_holder_is_still_reclaimed(tmp_path) -> None:
+ """The conservative rule must not regress crash cleanup: a holder that
+ died in OUR namespace is still reclaimed ahead of TTL."""
+ db = SessionDB(tmp_path / "state.db")
+ dead = _dead_pid()
+ holder = f"pid={dead}:pidns={pid_namespace_id()}:tid=1:agent=crash:nonce=eeeeeeee"
+ assert db.try_acquire_compression_lock("sess1", holder, ttl_seconds=300) is True
+
+ contender = f"pid={os.getpid()}:pidns={pid_namespace_id()}:tid=2:agent=us:nonce=ffffffff"
+ assert db.try_acquire_compression_lock("sess1", contender, ttl_seconds=300) is True
+
+
+# ---------------------------------------------------------------------------
+# Behavioral: session turn leases (the reported incident shape)
+# ---------------------------------------------------------------------------
+
+
+def test_turn_lease_of_sibling_namespace_is_not_stolen(tmp_path) -> None:
+ """The incident: the sibling's turn is still in flight; a dead local
+ reading must not end it early. The lease releases at TTL."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("shared", source="test")
+ dead = _dead_pid()
+
+ sibling = f"pid={dead}:pidns={_sibling_pidns()}:turn=webui-turn:platform=webui"
+ assert db.try_acquire_session_turn_lease("shared", sibling, ttl_seconds=0.3) is True
+
+ contender = f"pid={os.getpid()}:pidns={pid_namespace_id()}:turn=gw-turn:platform=cli"
+ assert db.try_acquire_session_turn_lease("shared", contender, ttl_seconds=300) is False
+
+ time.sleep(0.4)
+ assert db.try_acquire_session_turn_lease("shared", contender, ttl_seconds=300) is True
+
+
+def test_turn_lease_same_namespace_dead_holder_is_reclaimed(tmp_path) -> None:
+ """A turn owner that crashed in OUR namespace is reclaimed ahead of TTL —
+ the e2e crash-resume path (test_compaction_kill9) depends on this."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("shared", source="test")
+ dead = _dead_pid()
+
+ crashed = f"pid={dead}:pidns={pid_namespace_id()}:turn=crashed:platform=cli"
+ assert db.try_acquire_session_turn_lease("shared", crashed, ttl_seconds=300) is True
+
+ contender = f"pid={os.getpid()}:pidns={pid_namespace_id()}:turn=resumer:platform=cli"
+ assert db.try_acquire_session_turn_lease("shared", contender, ttl_seconds=300) is True
+
+
+# ---------------------------------------------------------------------------
+# Behavioral: flock holder records (hermes_state_common)
+# ---------------------------------------------------------------------------
+
+
+def test_flock_holder_record_qualifies_pid_namespaces() -> None:
+ dead = _dead_pid()
+ provably_dead = hermes_state_common._lock_holder_provably_dead
+
+ # Same namespace + provably gone: break the orphaned lock (unchanged).
+ assert provably_dead(
+ {"pid": dead, "pidns": pid_namespace_id(), "start_ticks": 1, "acquired_at": 0.0}
+ ) is True
+ # Foreign namespace: a local absence is not proof — defer.
+ assert provably_dead(
+ {"pid": dead, "pidns": _sibling_pidns(), "start_ticks": 1, "acquired_at": 0.0}
+ ) is False
+ # Unstamped (pre-upgrade record): LEGACY rollout — these records never
+ # expire, so refusing to probe would permanently disable cleanup.
+ assert provably_dead({"pid": dead, "start_ticks": 1, "acquired_at": 0.0}) is True
+ # No/malformed record: defer (existing contract).
+ assert provably_dead(None) is False
+
+ # A live same-namespace holder stays unbroken; a recycled reading (its
+ # start ticks disagree) still breaks — both proofs survive the stamp.
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
+ try:
+ ticks = hermes_state_common._proc_start_ticks(child.pid)
+ assert ticks is not None
+ assert provably_dead(
+ {"pid": child.pid, "pidns": pid_namespace_id(), "start_ticks": ticks, "acquired_at": 0.0}
+ ) is False
+ assert provably_dead(
+ {"pid": child.pid, "pidns": pid_namespace_id(), "start_ticks": ticks + 1, "acquired_at": 0.0}
+ ) is True
+ finally:
+ child.kill()
+ child.wait(timeout=30)
diff --git a/tests/hermes_state/test_session_turn_lease.py b/tests/hermes_state/test_session_turn_lease.py
index 33860377360..6968eac5331 100644
--- a/tests/hermes_state/test_session_turn_lease.py
+++ b/tests/hermes_state/test_session_turn_lease.py
@@ -438,11 +438,16 @@ def test_acquire_turn_lease_reraises_non_lock_sqlite_error(tmp_path, monkeypatch
def test_non_expired_turn_lease_from_dead_pid_is_reclaimed(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
- """A holder whose structured pid= no longer exists can be reclaimed early."""
+ """A holder whose structured pid= no longer exists can be reclaimed early.
+
+ Stamped with this process's own PID namespace: same-namespace kernel proof
+ is still proof (a foreign or unstamped holder would defer to TTL instead —
+ see tests/hermes_state/test_lease_pid_namespace.py)."""
db = SessionDB(tmp_path / "state.db")
db.create_session("shared", source="test")
- dead_holder = "pid=424242:turn=dead:platform=test"
+ from hermes_state_pidns import holder_namespace_token
+ dead_holder = f"pid=424242{holder_namespace_token()}:turn=dead:platform=test"
assert db.try_acquire_session_turn_lease(
"shared", dead_holder, ttl_seconds=300
) is True