Skip to content

The agent that grows with you

refactor(agent): one _requeue for the three heappush sites; timing test asserts ordering, not a 0.3 s bound

kshitijk4poor2369606f98b7
diff --git a/agent/periodic_scheduler.py b/agent/periodic_scheduler.py
index ae5d73ed0a3..6495172b4a4 100644
--- a/agent/periodic_scheduler.py
+++ b/agent/periodic_scheduler.py
@@ -17,10 +17,6 @@ itself; a body that raises is logged at debug and rescheduled — one bad
callback must never kill the shared thread. A handle never overlaps itself:
it is re-queued only once its in-flight run has returned. A worker-start
failure never retires the handle: it is re-queued and logged at warning.
-
-Prior art: per-handle-worker isolation follows #102458 (jfreshpicks);
-bounded-pool alternatives #102615/#102657/#104488 were rejected for
-preserving a shared starvation domain; originates from #102030.
"""
from __future__ import annotations
@@ -71,7 +67,7 @@ class PeriodicScheduler:
def schedule(self, fn: Callable[[], object], interval: float) -> ScheduledHandle:
handle = ScheduledHandle(self, fn, float(interval))
with self._cond:
- heapq.heappush(self._heap, (time.monotonic() + handle._interval, next(self._seq), handle))
+ self._requeue(handle)
if self._thread is None or not self._thread.is_alive():
self._thread = threading.Thread(target=self._run, name=_THREAD_NAME, daemon=True)
self._thread.start()
@@ -107,11 +103,12 @@ class PeriodicScheduler:
exc_info=True,
)
if not handle._cancelled:
- heapq.heappush(
- self._heap,
- (time.monotonic() + handle._interval, next(self._seq), handle),
- )
- self._cond.notify_all()
+ self._requeue(handle)
+ self._cond.notify()
+
+ def _requeue(self, handle: ScheduledHandle) -> None:
+ """Push ``handle``'s next due time (``_cond`` held)."""
+ heapq.heappush(self._heap, (time.monotonic() + handle._interval, next(self._seq), handle))
def _run_callback(self, handle: ScheduledHandle) -> None:
stop = False
@@ -125,11 +122,8 @@ class PeriodicScheduler:
if stop:
handle._cancelled = True
elif not handle._cancelled:
- heapq.heappush(
- self._heap,
- (time.monotonic() + handle._interval, next(self._seq), handle),
- )
- self._cond.notify_all()
+ self._requeue(handle)
+ self._cond.notify()
def _run(self) -> None:
while True:
diff --git a/tests/agent/test_periodic_scheduler.py b/tests/agent/test_periodic_scheduler.py
index 883311838bd..839af9b8059 100644
--- a/tests/agent/test_periodic_scheduler.py
+++ b/tests/agent/test_periodic_scheduler.py
@@ -101,7 +101,7 @@ def test_blocked_callback_does_not_stall_due_sibling(monkeypatch):
def blocker():
blocker_entered.set()
- release_blocker.wait(2.0)
+ release_blocker.wait(5.0)
return False
def sibling():
@@ -109,10 +109,12 @@ def test_blocked_callback_does_not_stall_due_sibling(monkeypatch):
return False
blocker_handle = schedule(blocker, 0.01)
- assert blocker_entered.wait(1.0)
+ assert blocker_entered.wait(2.0)
sibling_handle = schedule(sibling, 0.01)
try:
- assert sibling_ran.wait(0.30), (
+ # Ordering, not a wall-clock bound: the sibling must fire WHILE the blocker still holds
+ # its worker. On main the sibling only runs after the blocker's 5 s wait expires.
+ assert sibling_ran.wait(2.0) and not release_blocker.is_set(), (
"a blocked periodic callback stalled an unrelated due callback"
)
finally:
@@ -121,34 +123,6 @@ def test_blocked_callback_does_not_stall_due_sibling(monkeypatch):
sibling_handle.cancel(wait=1.0)
-def test_slow_callback_never_overlaps_itself():
- sched = PeriodicScheduler()
- lock = threading.Lock()
- two_runs = threading.Event()
- running = 0
- peak_running = 0
- completed = 0
-
- def slow():
- nonlocal running, peak_running, completed
- with lock:
- running += 1
- peak_running = max(peak_running, running)
- time.sleep(0.05)
- with lock:
- running -= 1
- completed += 1
- if completed >= 2:
- two_runs.set()
-
- handle = sched.schedule(slow, 0.01)
- try:
- assert two_runs.wait(2.0)
- assert peak_running == 1, "a handle ran concurrently with itself"
- finally:
- handle.cancel(wait=2.0)
-
-
def test_worker_start_failure_keeps_timer(monkeypatch):
sched = PeriodicScheduler()
fired: list = []
@@ -156,8 +130,9 @@ def test_worker_start_failure_keeps_timer(monkeypatch):
attempts = {"n": 0}
def flaky(*args, **kwargs):
- name = kwargs.get("name", "")
- if name.startswith(periodic_scheduler._CALLBACK_THREAD_PREFIX) and attempts["n"] == 0:
+ # Only this scheduler's own callback worker fails, once; a leaked handle on the shared
+ # _DEFAULT scheduler must not be the one that consumes the single Boom.
+ if kwargs.get("target") is sched._run_callback and attempts["n"] == 0:
attempts["n"] += 1
class Boom:
@@ -165,7 +140,6 @@ def test_worker_start_failure_keeps_timer(monkeypatch):
raise RuntimeError("no threads")
return Boom()
- attempts["n"] += 1
return real_thread(*args, **kwargs)
monkeypatch.setattr(periodic_scheduler.threading, "Thread", flaky)