Skip to content

The agent that grows with you

fix(gateway): expire orphaned drain markers past a max-age so a leaked marker can't wedge the gateway (#85433)

kshitij88557667162f
diff --git a/gateway/drain_control.py b/gateway/drain_control.py
index 998de85092e..ba7d9f6bf74 100644
--- a/gateway/drain_control.py
+++ b/gateway/drain_control.py
@@ -46,6 +46,20 @@ epoch check is deliberately **lenient**: it ignores a marker only on a
*definite* epoch mismatch. A marker with no epoch (legacy/corrupt/contentless),
or an environment where the epoch cannot be computed (non-Linux, no ``/proc``),
both degrade to the original presence-only behaviour — never fail-closed.
+
+Why the max-age (#85433). The epoch handles the restart case, but it bakes in
+the assumption that the action a drain protects always ends in a machine
+restart. When a drain-gated action completes *without* recreating the container
+and the writer never cancels the drain (writer crash, forgotten cleanup), the
+orphaned marker still carries the *current* epoch — so the epoch check honours
+it and the gateway bounces every inbound message forever (observed in the
+field: a cloud instance refused all Telegram turns for ~3 days). The marker's
+``requested_at`` timestamp is therefore also checked: a marker older than
+:data:`DRAIN_REQUEST_MAX_AGE_SECONDS` reads as stale. Same leniency contract as
+the epoch — only a *definite* expiry (timestamp present, parseable, and too
+old) is ignored; a missing/corrupt timestamp still reads as drain-active. A
+deliberately long drain has a sanctioned keep-alive: re-calling
+:func:`write_drain_request` refreshes ``requested_at``.
"""
from __future__ import annotations
@@ -63,6 +77,21 @@ _log = logging.getLogger(__name__)
_DRAIN_REQUEST_FILENAME = ".drain_request.json"
+# Max-age fallback for a same-epoch orphaned marker (#85433). Drain-gated
+# lifecycle actions complete in minutes; an hour is comfortably past any
+# legitimate drain while still bounding the wedge a leaked marker can cause
+# (vs. the unbounded outage observed in the field). Long-running drains
+# refresh the marker via write_drain_request() (idempotent re-write bumps
+# ``requested_at``) rather than raising this bound.
+DRAIN_REQUEST_MAX_AGE_SECONDS = 3600.0
+
+# Dedup guard for the expired-marker warning: the drain watcher re-reads the
+# marker every second, and an expired orphan sits on disk until removed, so
+# an unconditional warning would fire ~86k times/day. Keyed by the marker's
+# ``requested_at`` string — a keep-alive re-write (new timestamp) that later
+# expires again logs again, which is the desired behaviour.
+_expiry_logged_for: Optional[str] = None
+
@functools.lru_cache(maxsize=1)
def current_instantiation_epoch() -> str:
@@ -141,8 +170,9 @@ def write_drain_request(
"""Write the begin-drain marker. Returns the payload written.
Atomic write so the gateway watcher never reads a half-written file.
- Idempotent: re-writing while a drain is already in progress just refreshes
- ``requested_at`` (harmless — the watcher keys off presence, not content).
+ Idempotent: re-writing while a drain is already in progress refreshes
+ ``requested_at`` — the sanctioned keep-alive for a drain that legitimately
+ needs longer than :data:`DRAIN_REQUEST_MAX_AGE_SECONDS`.
Stamps the marker with :func:`current_instantiation_epoch` so a marker that
later survives a machine restart on the durable HERMES_HOME volume can be
@@ -207,6 +237,67 @@ def _marker_epoch_is_stale(body: dict[str, Any]) -> bool:
return marker_epoch != current
+def _marker_is_expired(body: dict[str, Any]) -> bool:
+ """True iff ``body``'s ``requested_at`` is *definitely* too old (#85433).
+
+ The max-age fallback for a same-epoch orphan: a drain-gated action that
+ completes WITHOUT a machine restart leaves a marker the epoch check cannot
+ reject, and if the writer never cancels the drain the gateway is wedged in
+ ``draining`` for the life of the container. Bounding the marker's lifetime
+ by :data:`DRAIN_REQUEST_MAX_AGE_SECONDS` converts that unbounded outage
+ into a self-healing one.
+
+ Same leniency contract as :func:`_marker_epoch_is_stale` — returns False
+ ("not expired, honour it") whenever it can't be sure:
+ * the marker carries no ``requested_at`` (legacy/corrupt/contentless
+ body), OR
+ * the timestamp isn't a parseable ISO-8601 string.
+ Only a timestamp that parses AND lies more than the max-age in the past is
+ considered expired. A future-dated timestamp (clock skew) is honoured. The
+ expiry is logged loudly — but once per marker, not per poll: the gateway's
+ drain watcher re-reads the marker every second, and an expired orphan stays
+ on disk until an operator or writer removes it, so an unconditional warning
+ would repeat ~86k times/day. This path only fires when a writer leaked a
+ marker, and the log is the operator's breadcrumb.
+ """
+ global _expiry_logged_for
+ raw = body.get("requested_at")
+ if not isinstance(raw, str) or not raw:
+ return False
+ try:
+ requested_at = datetime.fromisoformat(raw)
+ except ValueError:
+ return False
+ if requested_at.tzinfo is None:
+ requested_at = requested_at.replace(tzinfo=timezone.utc)
+ age = (datetime.now(timezone.utc) - requested_at).total_seconds()
+ if age <= DRAIN_REQUEST_MAX_AGE_SECONDS:
+ return False
+ if _expiry_logged_for != raw:
+ _expiry_logged_for = raw
+ _log.warning(
+ "drain-control: ignoring expired drain marker (requested_at=%s, "
+ "age=%.0fs > max %.0fs, principal=%s) — the drain that wrote it "
+ "was never cancelled; treating as stale so the gateway keeps "
+ "accepting turns.",
+ raw,
+ age,
+ DRAIN_REQUEST_MAX_AGE_SECONDS,
+ body.get("principal"),
+ )
+ return True
+
+
+def _marker_is_stale(body: dict[str, Any]) -> bool:
+ """True iff the marker is definitely from a drain that is already over.
+
+ Two independent, individually-lenient signals (either suffices):
+ * epoch mismatch — the marker survived a machine restart (NS-570);
+ * expiry — a same-epoch orphan outlived any legitimate drain (#85433).
+ """
+ return _marker_epoch_is_stale(body) or _marker_is_expired(body)
+
+
def drain_requested(*, home: Optional[Path] = None) -> bool:
"""True iff a begin-drain marker for THIS instantiation is present.
@@ -214,14 +305,19 @@ def drain_requested(*, home: Optional[Path] = None) -> bool:
treated as absent: it survived a container/VM restart (HERMES_HOME is a
durable Fly volume on Hermes Cloud) and the lifecycle action that triggered
the drain has already completed — honouring it would wedge the
- freshly-restarted gateway in ``draining`` (NS-570). The staleness check is
- lenient (see :func:`_marker_epoch_is_stale`): a legacy/corrupt marker with
- no epoch, or an environment without ``/proc``, still reads as drain-active.
+ freshly-restarted gateway in ``draining`` (NS-570). A marker whose
+ ``requested_at`` is older than :data:`DRAIN_REQUEST_MAX_AGE_SECONDS` is
+ likewise treated as absent: it is a same-epoch orphan whose drain-gated
+ action completed without a restart and was never cancelled (#85433). Both
+ staleness checks are lenient (see :func:`_marker_epoch_is_stale` /
+ :func:`_marker_is_expired`): a legacy/corrupt marker with no epoch and no
+ timestamp, or an environment without ``/proc``, still reads as
+ drain-active.
"""
body = read_drain_request(home=home)
if body is None:
return False
- if _marker_epoch_is_stale(body):
+ if _marker_is_stale(body):
return False
return True
@@ -230,8 +326,9 @@ def drain_notification_suppressed(*, home: Optional[Path] = None) -> bool:
"""True iff an ACTIVE drain marker asks to suppress the shutdown broadcast.
"Active" means exactly what :func:`drain_requested` means — a marker present
- AND stamped with the current instantiation epoch. A stale (other-epoch)
- marker that survived a machine restart on the durable HERMES_HOME volume is
+ AND stamped with the current instantiation epoch AND not past its max-age.
+ A stale (other-epoch) marker that survived a machine restart on the durable
+ HERMES_HOME volume, or an expired same-epoch orphan (#85433), is
ignored here just as it is for drain state (NS-570): we must never let an
orphaned marker's flag silence a *fresh* gateway's legitimate shutdown
broadcast.
@@ -246,7 +343,7 @@ def drain_notification_suppressed(*, home: Optional[Path] = None) -> bool:
body = read_drain_request(home=home)
if body is None:
return False
- if _marker_epoch_is_stale(body):
+ if _marker_is_stale(body):
return False
return bool(body.get("suppress_notification"))
diff --git a/tests/gateway/test_external_drain_control.py b/tests/gateway/test_external_drain_control.py
index df3e1689405..0b8050df8c7 100644
--- a/tests/gateway/test_external_drain_control.py
+++ b/tests/gateway/test_external_drain_control.py
@@ -12,6 +12,7 @@ Q-B, exercises a real `hermes gateway run`); these lock the unit contract.
from __future__ import annotations
import asyncio
+import json
from pathlib import Path
from unittest.mock import MagicMock
@@ -121,6 +122,120 @@ class TestInstantiationEpoch:
dc.current_instantiation_epoch.cache_clear()
+# ---------------------------------------------------------------------------
+# requested_at max-age (#85433: same-epoch orphaned marker, no restart)
+# ---------------------------------------------------------------------------
+
+
+class TestMarkerMaxAge:
+ def test_fresh_marker_honoured(self, home):
+ dc.write_drain_request(principal="nas")
+ assert dc.drain_requested() is True
+
+ def test_expired_marker_reads_as_absent(self, home):
+ # THE #85433 REGRESSION. A drain-gated action completes WITHOUT a
+ # machine restart, so the epoch still matches — but the writer never
+ # cancelled the drain. The orphan must not wedge the gateway forever.
+ from datetime import datetime, timedelta, timezone
+
+ dc.write_drain_request(principal="nas", suppress_notification=True)
+ body = dc.read_drain_request()
+ assert body is not None
+ body["requested_at"] = (
+ datetime.now(timezone.utc)
+ - timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
+ ).isoformat()
+ dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
+
+ # The marker file is still physically present, with the CURRENT epoch…
+ assert dc.drain_request_path().exists() is True
+ # …but it is ignored because it outlived any legitimate drain.
+ assert dc.drain_requested() is False
+ # The suppression flag of an expired orphan is likewise ignored.
+ assert dc.drain_notification_suppressed() is False
+
+ def test_marker_without_timestamp_still_honoured(self, home):
+ # Leniency contract: no requested_at (legacy/corrupt body) must fail
+ # toward quiescing, exactly like the epoch check.
+ payload = {"action": "drain", "epoch": dc.current_instantiation_epoch()}
+ dc.drain_request_path().write_text(json.dumps(payload), encoding="utf-8")
+ assert dc.drain_requested() is True
+
+ def test_unparseable_timestamp_still_honoured(self, home):
+ payload = {
+ "action": "drain",
+ "epoch": dc.current_instantiation_epoch(),
+ "requested_at": "not-a-timestamp",
+ }
+ dc.drain_request_path().write_text(json.dumps(payload), encoding="utf-8")
+ assert dc.drain_requested() is True
+
+ def test_naive_timestamp_treated_as_utc(self, home):
+ # A writer that stamped a tz-naive ISO string must still expire.
+ from datetime import datetime, timedelta, timezone
+
+ stale_naive = (
+ datetime.now(timezone.utc)
+ - timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
+ ).replace(tzinfo=None)
+ payload = {
+ "action": "drain",
+ "epoch": dc.current_instantiation_epoch(),
+ "requested_at": stale_naive.isoformat(),
+ }
+ dc.drain_request_path().write_text(json.dumps(payload), encoding="utf-8")
+ assert dc.drain_requested() is False
+
+ def test_expiry_warning_logged_once_per_marker(self, home, caplog):
+ # The watcher polls every 1s; an expired orphan must warn ONCE, not
+ # once per tick (~86k/day). A refreshed marker that expires again
+ # warns again (new requested_at).
+ import logging
+ from datetime import datetime, timedelta, timezone
+
+ def _write_expired(offset_seconds):
+ dc.write_drain_request(principal="nas")
+ body = dc.read_drain_request()
+ assert body is not None
+ body["requested_at"] = (
+ datetime.now(timezone.utc)
+ - timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + offset_seconds)
+ ).isoformat()
+ dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
+
+ _write_expired(60)
+ with caplog.at_level(logging.WARNING, logger="gateway.drain_control"):
+ assert dc.drain_requested() is False
+ assert dc.drain_requested() is False # second poll tick
+ assert dc.drain_requested() is False # third poll tick
+ expired_logs = [r for r in caplog.records if "expired drain marker" in r.message]
+ assert len(expired_logs) == 1
+
+ caplog.clear()
+ _write_expired(120) # a DIFFERENT requested_at that is also expired
+ with caplog.at_level(logging.WARNING, logger="gateway.drain_control"):
+ assert dc.drain_requested() is False
+ expired_logs = [r for r in caplog.records if "expired drain marker" in r.message]
+ assert len(expired_logs) == 1
+
+ def test_rewrite_refreshes_the_clock(self, home):
+ # The sanctioned keep-alive: re-writing the marker bumps requested_at,
+ # so a deliberately long drain stays honoured.
+ from datetime import datetime, timedelta, timezone
+
+ dc.write_drain_request(principal="nas")
+ body = dc.read_drain_request()
+ assert body is not None
+ body["requested_at"] = (
+ datetime.now(timezone.utc)
+ - timedelta(seconds=dc.DRAIN_REQUEST_MAX_AGE_SECONDS + 60)
+ ).isoformat()
+ dc.drain_request_path().write_text(json.dumps(body), encoding="utf-8")
+ assert dc.drain_requested() is False # expired…
+ dc.write_drain_request(principal="nas") # …keep-alive re-write
+ assert dc.drain_requested() is True
+
+
# ---------------------------------------------------------------------------
# Gateway state machine (enter / exit / idempotency)
# ---------------------------------------------------------------------------