Skip to content

The agent that grows with you

fix(gateway): drain a restart-safe worker's cron delivery when it is queued, not on the next tick

Christophereb2781dd2f27
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.py
index a55e1a36d24..4569b1b726a 100644
--- a/cron/delivery_queue.py
+++ b/cron/delivery_queue.py
@@ -72,8 +72,16 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
)
+def queue_path(home: Optional[Path] = None) -> Path:
+ """The queue file of ``home`` (the active home when None); a test override wins."""
+ if DELIVERY_DB is not None:
+ return DELIVERY_DB
+ root = Path(home) if home is not None else get_hermes_home()
+ return root.resolve() / "cron" / "deliveries.db"
+
+
def _path() -> Path:
- return DELIVERY_DB or (get_hermes_home().resolve() / "cron" / "deliveries.db")
+ return queue_path()
def _initialize_schema(conn: sqlite3.Connection) -> None:
diff --git a/gateway/run.py b/gateway/run.py
index 6e12bd02022..cb3a2bbb214 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4666,6 +4666,7 @@ def _start_gateway_housekeeping(
"""Background thread for gateway-only periodic chores (NOT cron). Separate from the cron trigger
so chores run under any ``CronScheduler`` provider (external scale-to-zero has no 60s loop).
Cadences are ticks of ``interval``; inner gates own the real cadence."""
+ from gateway.run_delivery_queue_watch import DRAIN_LABEL, DeliveryQueueWatch, wait_for_next_tick
from gateway.run_profile_reconcile import _mcp_config_reconciler, profile_scoped_chore
chores: list[tuple[int, str, Any]] = [
# First every tick: re-stamp ``updated_at`` in gateway_state.json so it is a real heartbeat.
@@ -4676,8 +4677,7 @@ def _start_gateway_housekeeping(
if adapters is not None or runner is not None:
# Restart-safe cron workers run outside the gateway cgroup and queue their final send for
# whichever gateway is live; drained here (not the scheduler tick) so external providers get it too.
- chores.append((1, "Cron durable delivery queue drain",
- lambda: _drain_restart_safe_cron_deliveries(adapters, loop, runner)))
+ chores.append((1, DRAIN_LABEL, lambda: _drain_restart_safe_cron_deliveries(adapters, loop, runner)))
chores += [
(5, "Channel directory refresh", lambda: adapters and _housekeeping_channel_directory(adapters, loop)),
(60, "Media cache cleanup", _housekeeping_media_caches),
@@ -4700,6 +4700,16 @@ def _start_gateway_housekeeping(
# Last: a real prune can hold this thread for a while; every other chore of the tick runs first.
(1, "Checkpoint prune tick", _housekeeping_checkpoint_prune)]
+ # Between ticks the queue file is watched so a worker's send goes out when it is queued,
+ # not up to ``interval`` later (#117307); the tick's drain above remains the fallback.
+ queue_watch = None
+ if adapters is not None or runner is not None:
+ def served_homes() -> list:
+ return [home for _name, home in _handoff_watch_scopes(runner)] if runner is not None else [None]
+
+ queue_watch = DeliveryQueueWatch(
+ served_homes, lambda: _drain_restart_safe_cron_deliveries(adapters, loop, runner))
+
logger.info("Gateway housekeeping started (interval=%ds)", interval)
tick_count = 0
while not stop_event.is_set():
@@ -4707,7 +4717,7 @@ def _start_gateway_housekeeping(
for every, label, fn in chores:
if tick_count % every == 0:
_housekeeping_chore(label, fn)
- stop_event.wait(timeout=interval)
+ wait_for_next_tick(stop_event, interval, queue_watch, _housekeeping_chore)
logger.info("Gateway housekeeping stopped")
diff --git a/gateway/run_delivery_queue_watch.py b/gateway/run_delivery_queue_watch.py
new file mode 100644
index 00000000000..f32be1b6118
--- /dev/null
+++ b/gateway/run_delivery_queue_watch.py
@@ -0,0 +1,78 @@
+"""Wake the restart-safe cron delivery drain when a worker writes the queue (#117307).
+
+A restart-safe worker runs its job outside the gateway, queues the final send in
+``cron/deliveries.db`` and polls that row once a second; the gateway drained the
+queue only on its housekeeping tick, so a turn that ended in 8 s reached the user
+a minute later. Between ticks the housekeeping thread now stats the queue file
+(and its WAL) and drains as soon as either changed. The tick's own drain stays
+as the fallback for anything the stat cannot see.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from pathlib import Path
+from typing import Callable, Iterable, Optional
+
+# How often the housekeeping thread looks at the queue file between its ticks.
+DELIVERY_QUEUE_WATCH_SECONDS = 1.0
+DRAIN_LABEL = "Cron durable delivery queue drain"
+
+
+class DeliveryQueueWatch:
+ """Stamp-compare every served profile's queue file; ``drain`` when a stamp moved.
+
+ The watch never resets itself after draining: the drain's own status writes
+ move the stamp once more and cost one empty pass, after which the stamp is
+ stable, while a worker that enqueued during the drain still moves it again.
+ """
+
+ def __init__(self, homes: Callable[[], Iterable[Optional[Path]]], drain: Callable[[], None]) -> None:
+ self._homes = homes
+ self.drain = drain
+ self._served: list = list(homes())
+ self._seen = self._stamp()
+
+ def refresh_homes(self) -> None:
+ """Re-resolve the served profiles once per tick (a directory read under multiplex),
+ not on every poll; a profile that appears mid-interval is drained by the tick itself."""
+ self._served = list(self._homes())
+
+ def _stamp(self) -> tuple:
+ from cron.delivery_queue import queue_path
+
+ stamps = []
+ for home in self._served:
+ path = queue_path(home)
+ for candidate in (path, path.with_name(path.name + "-wal")):
+ try:
+ info = os.stat(candidate)
+ except OSError:
+ continue
+ stamps.append((str(candidate), info.st_mtime_ns, info.st_size))
+ return tuple(stamps)
+
+ def changed(self) -> bool:
+ current = self._stamp()
+ if current == self._seen:
+ return False
+ self._seen = current
+ return True
+
+
+def wait_for_next_tick(stop_event, interval: float, watch: Optional[DeliveryQueueWatch], chore) -> None:
+ """Sleep one housekeeping interval, draining the worker queue the moment it changes."""
+ if watch is None:
+ stop_event.wait(timeout=interval)
+ return
+ watch.refresh_homes()
+ deadline = time.monotonic() + interval
+ while True:
+ remaining = max(0.0, deadline - time.monotonic())
+ if stop_event.wait(timeout=min(remaining, DELIVERY_QUEUE_WATCH_SECONDS)):
+ return
+ if watch.changed():
+ chore(DRAIN_LABEL, watch.drain)
+ if time.monotonic() >= deadline:
+ return
diff --git a/tests/gateway/test_cron_delivery_housekeeping.py b/tests/gateway/test_cron_delivery_housekeeping.py
index 5bea1f10120..84b9c81d3a9 100644
--- a/tests/gateway/test_cron_delivery_housekeeping.py
+++ b/tests/gateway/test_cron_delivery_housekeeping.py
@@ -226,3 +226,70 @@ def test_primary_drain_delivers_credentialless_satellite_queue_row_through_prima
reset_hermes_home_override(token)
assert row["status"] == "delivered", row
assert sent == ["C1"] and standalone == []
+
+
+def test_a_queued_worker_delivery_is_drained_before_the_next_housekeeping_tick(tmp_path, monkeypatch):
+ """Regression for #117307: the worker's send waited for the 60 s tick. With the queue
+ file watched between ticks it is drained within seconds of the enqueue."""
+ import threading
+ import time
+
+ from cron import delivery_queue
+
+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "deliveries.db")
+ drained = threading.Event()
+ drains = []
+
+ def record_drain(live_adapters, live_loop):
+ drains.append(time.monotonic())
+ drained.set()
+
+ monkeypatch.setattr(scheduler, "drain_delivery_queue", record_drain)
+ stop = threading.Event()
+ thread = threading.Thread(
+ target=gateway_run._start_gateway_housekeeping,
+ args=(stop,), kwargs={"adapters": {"slack": object()}, "loop": object(), "interval": 60},
+ daemon=True)
+ thread.start()
+ try:
+ assert drained.wait(5.0), "the tick's own drain did not run"
+ drained.clear()
+ queued_at = time.monotonic()
+ delivery_queue.enqueue("exec-117307", {"id": "job", "name": "reminder"}, "hello")
+ assert drained.wait(5.0), "the queued delivery waited for the next tick"
+ assert drains[-1] - queued_at < 5.0
+ finally:
+ stop.set()
+ thread.join(timeout=5.0)
+ assert not thread.is_alive()
+
+
+def test_the_watch_settles_after_the_drain_wrote_its_outcome(tmp_path, monkeypatch):
+ """The drain's own status write wakes exactly one more (empty) pass; a stable queue
+ never wakes it again, so the housekeeping thread does not spin on its own writes."""
+ from cron import delivery_queue
+ from gateway.run_delivery_queue_watch import DeliveryQueueWatch
+
+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "deliveries.db")
+ passes = []
+ watch = DeliveryQueueWatch(
+ lambda: [None],
+ lambda: passes.append(delivery_queue.drain(lambda job, content, for_failure: None)))
+ assert watch.changed() is False, "no queue file, nothing to wake on"
+
+ delivery_queue.enqueue("exec-1", {"id": "job"}, "hello")
+ assert watch.changed() is True
+ watch.drain()
+ assert passes == [1]
+ status = delivery_queue.get_status("exec-1")
+ assert status is not None and status["status"] == "delivered"
+
+ assert watch.changed() is True, "the delivered status was written to the queue"
+ watch.drain()
+ assert passes == [1, 0]
+ assert watch.changed() is False, "an empty pass writes nothing"
+ assert watch.changed() is False
+
+ # Hosts whose SQLite runs the queue in WAL mode write to the -wal file first.
+ (tmp_path / "deliveries.db-wal").write_bytes(b"frame")
+ assert watch.changed() is True