Skip to content

The agent that grows with you

refactor(state): hoist pidns imports and trim duplicated call-site prose

kshitijk4poor815f03abd4fa
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 7946b7759a4..4168d4812ed 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -35,6 +35,7 @@ from agent.model_metadata import estimate_messages_tokens_rough, estimate_reques
from agent.session_activity import ActivityProvenance, normalize_activity_provenance
from agent.usage_anchor import set_usage_anchor
from hermes_state_ids import new_session_id as mint_session_id
+from hermes_state_pidns import holder_namespace_token
logger = logging.getLogger(__name__)
@@ -1772,14 +1773,9 @@ 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[: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. ``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]}")
+ """Build a unique lock holder id: ``pid[:pidns]:tid:agent-instance:uuid`` (pidns: see ``hermes_state_pidns``).
+ pid+tid tell crashed holders apart; instance id and per-acquire uuid disambiguate co-resident/pooled agents."""
+ return f"pid={os.getpid()}{holder_namespace_token()}:tid={threading.get_ident()}: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 1f0592fae82..3347f05f382 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -14,6 +14,8 @@ from contextlib import nullcontext
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
+from hermes_state_pidns import holder_namespace_token
+
# Same logger name as the origin module so log records / caplog filters are unchanged.
logger = logging.getLogger("run_agent")
@@ -257,10 +259,7 @@ 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
+ # pidns stamp: see hermes_state_pidns.
holder = (
f"pid={os.getpid()}{holder_namespace_token()}:turn={relay_turn_id}"
f":platform={task_context['platform'] or 'unknown'}"
diff --git a/hermes_state.py b/hermes_state.py
index 26361d843c9..0f59bf0992f 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -33,6 +33,7 @@ from hermes_state_common import (
escape_like as _escape_like, stat_db_file_identity as _stat_db_file_identity,
)
from hermes_state_holders import read_only_db_uri
+from hermes_state_pidns import holder_pid_checkable
from hermes_state_health import (
STORAGE_CORRUPT, mark_storage_corrupt, note_storage_error, storage_corrupt_reason, storage_state,
)
@@ -137,18 +138,11 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool:
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).
-
- 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."""
+ Foreign/unstamped PID namespaces defer to TTL: see ``hermes_state_pidns``."""
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:
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 8de1a64818c..33a35606368 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -11,6 +11,7 @@ import time
from typing import Any
from hermes_cli.timefmt import EPOCH_MAX, EPOCH_MIN
+from hermes_state_pidns import persistent_record_pidns_checkable, pid_namespace_id
from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE, SKILL_EXCERPT_JOINT, SKILL_SCAFFOLD_SQL_LIKE, describe_skill_invocation
from agent.context_compressor import (LEGACY_SUMMARY_PREFIX, SUMMARY_PREFIX, _MERGED_PRIOR_CONTEXT_HEADER,
_MERGED_SUMMARY_DELIMITER, _SUMMARY_END_MARKER)
@@ -1127,12 +1128,9 @@ 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. ``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.
+ dead, flock inherited by a forked child — issue #100108) from a live wedged holder. ``pidns``: see
+ ``hermes_state_pidns``.
"""
- 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"))
@@ -1146,17 +1144,13 @@ 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, 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``)."""
+ is False: FAIL CLOSED and defer. Unstamped records keep probing: 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:
diff --git a/hermes_state_pidns.py b/hermes_state_pidns.py
index 1aadf28975b..17b5178a805 100644
--- a/hermes_state_pidns.py
+++ b/hermes_state_pidns.py
@@ -87,7 +87,7 @@ def holder_namespace_token() -> str:
return f":pidns={ns}" if ns else ""
-def recorded_namespace(holder: str) -> Optional[str]:
+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
@@ -103,7 +103,7 @@ def _qualify(recorded: Optional[str], *, unstamped_checkable: bool) -> bool:
return unstamped_checkable
if local.id is None:
return False # our own lookup failed: unknown authority is not authority
- return str(recorded) == str(local.id)
+ return recorded == local.id
def holder_pid_checkable(holder: str) -> bool:
@@ -114,7 +114,7 @@ def holder_pid_checkable(holder: str) -> bool:
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)
+ return _qualify(_recorded_namespace(holder), unstamped_checkable=False)
def persistent_record_pidns_checkable(recorded: Optional[str]) -> bool: