Skip to content

The agent that grows with you

fix(gateway): treat pid=None lifecycle sentinel as unknown ownership in mark_exited

Tekniuma65494ed0099
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.py
index c76a9edac85..594da94e5ca 100644
--- a/gateway/lifecycle_ledger.py
+++ b/gateway/lifecycle_ledger.py
@@ -275,14 +275,17 @@ def mark_exited(
) -> None:
"""Mark the current life as cleanly exited. Idempotent, never raises.
- Only rewrites the sentinel when it is still owned by this process —
+ Only rewrites the sentinel when it is provably owned by this process —
during a ``--replace`` takeover the replacement claims the sentinel
before the old process finishes teardown, and the old life must not
- clobber the new owner's ``running`` phase on its way out.
+ clobber the new owner's ``running`` phase on its way out. A sentinel
+ with ``pid=None`` (or a malformed pid) has *unknown* ownership and is
+ likewise left alone: we must not overwrite evidence we cannot prove is
+ ours with a ``clean exit`` claim.
"""
try:
sentinel = _read_json(get_lifecycle_sentinel_path(home))
- if sentinel and sentinel.get("pid") not in (None, os.getpid()):
+ if sentinel is not None and sentinel.get("pid") != os.getpid():
return
_write_sentinel(
{
diff --git a/tests/gateway/test_lifecycle_ledger.py b/tests/gateway/test_lifecycle_ledger.py
index 298bf3a1b70..e859cd2c292 100644
--- a/tests/gateway/test_lifecycle_ledger.py
+++ b/tests/gateway/test_lifecycle_ledger.py
@@ -240,6 +240,24 @@ def test_mark_exited_without_prior_sentinel_writes_exited(tmp_path: Path) -> Non
assert _read_sentinel(tmp_path)["phase"] == "exited"
+def test_mark_exited_leaves_pid_none_sentinel_alone(tmp_path: Path) -> None:
+ """A sentinel with pid=None has unknown ownership — mark_exited must not
+ clobber it with a clean-exit claim it cannot prove is its own."""
+ _write_sentinel(tmp_path, {"phase": "running", "pid": None, "start_time": 2000.0})
+ mark_exited(0, reason="graceful_shutdown", home=tmp_path)
+ sentinel = _read_sentinel(tmp_path)
+ assert sentinel["phase"] == "running"
+ assert sentinel["pid"] is None
+
+
+def test_mark_exited_rewrites_own_sentinel(tmp_path: Path) -> None:
+ _write_sentinel(tmp_path, {
+ "phase": "running", "pid": os.getpid(), "start_time": 2000.0,
+ })
+ mark_exited(0, reason="graceful_shutdown", home=tmp_path)
+ assert _read_sentinel(tmp_path)["phase"] == "exited"
+
+
# ---------------------------------------------------------------------------
# read_prior_exit_label (container-boot annotation)
# ---------------------------------------------------------------------------