The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): share the drift-tolerant start-time comparator across every owner-liveness check
teknium136ede56a66ca
diff --git a/cron/executions.py b/cron/executions.pyindex 75ec666249d..2f53c3b7e1c 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -30,12 +30,6 @@ MAX_TERMINAL_EXECUTIONS = 1000HANDOFF_ADOPTION_GRACE_SECONDS = 30.0# Floor for the live-owner stale-claim bound (#115692); see _live_owner_stale_after_seconds.LIVE_OWNER_STALE_CLAIM_FLOOR_SECONDS = 7200.0-# Same-host start-time readings can drift by ~1 s between the claim-time and recovery-time reads-# (macOS ``kern.boottime`` adjustment, #117505). Both fingerprint scales are ×100 (Linux /proc-# ticks, psutil centiseconds), so 200 means 2 s on either platform — a recycled PID is essentially-# never that close to the original's start time, and a live misread is still bounded by the-# stale-claim sweep above.-_OWNER_START_TIME_DRIFT_TOLERANCE = 200_TERMINAL_STATES = ("completed", "failed", "unknown")_lock = threading.RLock()_PROCESS_ID = uuid.uuid4().hex@@ -144,7 +138,10 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:current = _process_start_time(pid)if current is None:return True # cannot compare -> cannot prove death; a misread must not rewrite state- return abs(current - started_at) <= _OWNER_START_TIME_DRIFT_TOLERANCE+ # Drifted same-host readings (#117505) are not proof of death; a live misread is still+ # bounded by the stale-claim sweep below.+ from gateway.status import start_time_fingerprints_match+ return start_time_fingerprints_match(started_at, current)def _live_owner_stale_after_seconds() -> Optional[float]:diff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.pyindex 255ca60d097..afe180c46d0 100644--- a/gateway/delivery_ledger.py+++ b/gateway/delivery_ledger.py@@ -251,7 +251,8 @@ def _owner_alive(pid: Any, started_at: Any) -> bool:except Exception:return Falsetry:- return started_at is None or int(current_start) == int(started_at)+ from gateway.status import start_time_fingerprints_match+ return started_at is None or start_time_fingerprints_match(started_at, current_start)except (TypeError, ValueError):return Truediff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex e9df3e66231..f018926c39c 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -336,9 +336,10 @@ def _check_run_auth(self, request: "web.Request", *, permission: str, _api_servedef _owner_alive(owner_pid: int, owner_started: int) -> bool:"""True when the recorded owner pid still exists and is the same process incarnation."""try:- from gateway.status import _pid_exists, get_process_start_time+ from gateway.status import _pid_exists, get_process_start_time, start_time_fingerprints_matchreturn owner_pid > 0 and bool(_pid_exists(owner_pid)) and (- not owner_started or int(get_process_start_time(owner_pid) or 0) == owner_started)+ not owner_started+ or start_time_fingerprints_match(owner_started, get_process_start_time(owner_pid) or 0))except Exception:return Falsediff --git a/gateway/status.py b/gateway/status.pyindex c1e326d2c94..98374bd5770 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -423,6 +423,20 @@ def _start_times_agree(current: Any, *recorded: Any) -> bool:return cur > 0 and all(r > 0 and abs(r - cur) <= 0.001 for r in map(float, recorded))+# Same-host start-time readings can drift by ~1 s between the claim-time and a later liveness read+# (macOS ``kern.boottime`` adjustment, #117505). Both fingerprint scales are ×100 (Linux /proc ticks,+# psutil centiseconds), so 200 means 2 s on either platform — a recycled PID is essentially never+# that close to the original's start time.+START_TIME_DRIFT_TOLERANCE = 200+++def start_time_fingerprints_match(recorded: Any, current: Any, tolerance: int = START_TIME_DRIFT_TOLERANCE) -> bool:+ """Liveness-reconciliation comparator for :func:`get_process_start_time` fingerprints: the+ recorded owner and the current reading are the same incarnation when they agree within+ ``tolerance``. Raises on junk; callers decide what an unreadable (``None``) side means."""+ return abs(int(current) - int(recorded)) <= tolerance++def _scope_hash(identity: str) -> str:return hashlib.sha256(identity.encode("utf-8")).hexdigest()[:16]diff --git a/tests/gateway/test_owner_liveness_drift.py b/tests/gateway/test_owner_liveness_drift.pynew file mode 100644index 00000000000..358d57693a1--- /dev/null+++ b/tests/gateway/test_owner_liveness_drift.py@@ -0,0 +1,64 @@+"""Sibling owner-liveness checks tolerate a drifted start-time fingerprint (#117505).++``cron.executions`` is not the only reconciler that compares a recorded owner fingerprint with+a fresh ``get_process_start_time`` reading: the delivery ledger, API-server durable runs and the+async-delegation ledger did the same exact-equality test and reconciled a live owner to+dead/unknown under the same ~1 s same-host drift. All of them now share+``gateway.status.start_time_fingerprints_match``.+"""++from __future__ import annotations++import pytest++from gateway import status++RECORDED = 178864182760++[email protected](autouse=True)+def _live_pid_with_drift(monkeypatch):+ monkeypatch.setattr(status, "_pid_exists", lambda pid: True)+ monkeypatch.setattr(status, "get_process_start_time", lambda pid: RECORDED + 100)+++def _delivery_ledger_alive() -> bool:+ from gateway import delivery_ledger++ return delivery_ledger._owner_alive(4242, RECORDED)+++def _api_server_run_alive() -> bool:+ from gateway.platforms import api_server_runs++ return api_server_runs._owner_alive(4242, RECORDED)+++def _async_delegation_alive(monkeypatch, tmp_path) -> bool:+ import tools.async_delegation as ad++ monkeypatch.setattr(ad, "_db_path", lambda: tmp_path / "state.db")+ with ad._DB_LOCK, ad._transaction() as conn:+ conn.execute(+ "INSERT INTO async_delegations (delegation_id, origin_session, state, dispatched_at, updated_at, "+ "delivery_state, delivery_attempts, owner_pid, owner_started_at, task_json) "+ "VALUES ('d-drift', 's', 'running', 1, 1, 'pending', 0, 4242, ?, '{}')",+ (RECORDED,),+ )+ return ad.recover_abandoned_delegations() == 0++[email protected]("site", ["delivery_ledger", "api_server_runs", "async_delegation"])+def test_one_second_drift_keeps_owner_live(site, monkeypatch, tmp_path):+ if site == "delivery_ledger":+ assert _delivery_ledger_alive() is True+ elif site == "api_server_runs":+ assert _api_server_run_alive() is True+ else:+ assert _async_delegation_alive(monkeypatch, tmp_path) is True+++def test_far_fingerprint_is_still_a_recycled_pid(monkeypatch):+ monkeypatch.setattr(status, "get_process_start_time", lambda pid: RECORDED + 3600)+ assert _delivery_ledger_alive() is False+ assert _api_server_run_alive() is Falsediff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex ddbd37921cb..6ca34ba6d27 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -225,7 +225,7 @@ def recover_abandoned_delegations() -> int:"""Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had alreadyrecorded (``record_unit_child``) are replayed with their real results."""try:- from gateway.status import _pid_exists, get_process_start_time+ from gateway.status import _pid_exists, get_process_start_time, start_time_fingerprints_matchexcept Exception:return 0now, recovered = time.time(), 0@@ -236,7 +236,9 @@ def recover_abandoned_delegations() -> int:FROM async_delegations WHERE state IN ('running','finalizing')""").fetchall()for row in rows:delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json, last_state = row- if pid and _pid_exists(int(pid)) and (started is None or get_process_start_time(int(pid)) == int(started)):+ if pid and _pid_exists(int(pid)) and (+ started is None or start_time_fingerprints_match(started, get_process_start_time(int(pid)) or 0)+ ):continuetask = json.loads(task_json or "{}")error = "Delegation owner exited before recording a terminal result; outcome unknown."