EventLoopMonitor reports a GIL wait as "the block ended before the watchdog looked" when the watchdog last ran inside the tick window
Bug Description
EventLoopMonitor._consume_watchdog_gap measures how long the watchdog thread was kept from running during a stall. It counts the time since the watchdog's last wake only when that wake came before the window opened (the last on-time tick):
https://github.com/livekit/agents/blob/e684c2379e1c385afe8edcd1f02ea422051b035f/livekit-agents/livekit/agents/telemetry/loop_monitor.py#L500-L513
if self._watchdog_last_wake < window_start:
gap = max(gap, now - self._watchdog_last_wake - self._tick)
The watchdog wakes every tick_interval. If it woke a few milliseconds after the window opened and then could not run for the rest of the stall, watchdog_gap is 0. The _watchdog_late path does not catch it either, because a watchdog that cannot run has not yet woken to record that it is late.
This is what happens when another thread holds the GIL. The loop thread and the watchdog both wait for it, and when the loop thread gets the GIL first, the late tick runs before the watchdog has woken. _build_report then sees watchdog_gap=0, decides the watchdog was not starved, and writes # no sample: the block ended before the watchdog looked. The report blames code on the loop for a stall that was a GIL wait, and it has no stack to point at.
The repro below shows it two ways on livekit-agents 1.8.4 and on main (96341b0):
- Deterministic: the monitor is put in the state a GIL wait leaves it in (last tick 220 ms ago, watchdog last woke 10 ms after it, loop thread used no CPU) and the real
_on_tickruns. The watchdog was idle for 210 ms, more than 10 of its ticks, and the report sayswatchdog_gap=0ms. - Live: a real monitor on a real loop thread while another thread runs
sorted()on 2M floats, which holds the GIL for about 260 ms. In 3 runs of 10 stalls each, 2, 6 and 2 stalls were reported as "the block ended before the watchdog looked" withwatchdog_gapof 3 to 5 ms. The rest of the same stalls gotwatchdog_gapof 230 to 260 ms.
In our production worker every job's loop is a thread of one process (THREAD executor), so another job's thread holding the GIL stalls this loop, and this branch hides that cause.
Expected Behavior
A watchdog that has not run for longer than one tick, at any point in the window, counts as starved. In part 1 the report should carry watchdog_gap of about 190 ms (210 ms idle minus one 20 ms tick), and the stall should be classified the same way as the other runs of the same GIL hold in part 2.
Reproduction Steps
# 1. Save the script below as repro.py (standalone, no server, no network).
# 2. uv run --python 3.12 --with 'livekit-agents==1.8.4' python repro.py
# 3. "part 1: FAIL" shows the defect deterministically; part 2 counts it on live threads.
"""EventLoopMonitor._consume_watchdog_gap ignores a watchdog that was starved
after it woke inside the tick's window.
Part 1 (deterministic): put the monitor in the state a GIL wait leaves it in
and run the real heartbeat (_on_tick). Part 2: a real monitor on a real loop
thread while a third thread holds the GIL for 300 ms (list.sort on ints never
releases it), repeated, counting how each stall is classified.
"""
import asyncio
import random
import threading
import time
from livekit.agents.telemetry.loop_monitor import BlockedReport, EventLoopMonitor
WARN, TICK = 0.1, 0.02
def part1() -> bool:
loop = asyncio.new_event_loop()
mon = EventLoopMonitor(loop, warn_threshold=WARN, error_threshold=5.0,
tick_interval=TICK, emit_spans=False)
reports: list[BlockedReport] = []
mon._on_report = reports.append
mon._loop_thread_ident = threading.get_ident()
now = time.monotonic()
# the last on-time tick was 220 ms ago, so this tick is 200 ms late
mon._last_tick_at = now - 0.22
# the watchdog last woke 10 ms after that tick and has not run since
# (210 ms, about 10 of its 20 ms ticks); it never saw its own late wake-up
mon._watchdog_last_wake = mon._last_tick_at + 0.01
mon._watchdog_late = None
# the loop thread burned no CPU: it was waiting for the GIL
mon._last_thread_cpu = time.thread_time()
mon._on_tick()
mon.stop()
loop.close()
r = reports[0]
print(f"part 1: lag={r.duration * 1000:.0f}ms watchdog_gap={r.watchdog_gap * 1000:.0f}ms "
f"cpu_time={r.cpu_time * 1000:.0f}ms process_descheduled={r.process_descheduled}")
print(f"part 1: stacks={r.stacks}")
ok = r.watchdog_gap > 0.1
print(f"part 1: {'PASS' if ok else 'FAIL'}: watchdog idle for "
f"{(now - mon._watchdog_last_wake) * 1000:.0f}ms (one tick is {TICK * 1000:.0f}ms), "
f"reported watchdog_gap={r.watchdog_gap * 1000:.0f}ms")
return ok
def part2(runs: int = 10) -> None:
big = [random.random() for _ in range(2_000_000)]
t = time.perf_counter()
sorted(big)
hold = time.perf_counter() - t
print(f"part 2: sorted() holds the GIL for {hold * 1000:.0f}ms per call")
loop = asyncio.new_event_loop()
thread = threading.Thread(target=loop.run_forever, daemon=True)
thread.start()
mon = EventLoopMonitor(loop, warn_threshold=WARN, error_threshold=5.0,
tick_interval=TICK, emit_spans=False)
reports: list[BlockedReport] = []
mon._on_report = reports.append
mon.start()
time.sleep(0.3)
for _ in range(runs):
h = threading.Thread(target=sorted, args=(big,))
h.start()
h.join()
time.sleep(0.3)
mon.stop()
loop.call_soon_threadsafe(loop.stop)
thread.join()
loop.close()
blamed = [r for r in reports if "the block ended before the watchdog looked" in "".join(r.stacks)]
for r in reports:
label = r.stacks[0].splitlines()[0][:70] if r.stacks else "(descheduled, no stack)"
print(f"part 2: lag={r.duration * 1000:4.0f}ms gap={r.watchdog_gap * 1000:4.0f}ms "
f"cpu={r.cpu_time * 1000:3.0f}ms {label}")
print(f"part 2: {len(blamed)} of {len(reports)} GIL waits reported as "
f"'the block ended before the watchdog looked' with watchdog_gap=0")
if __name__ == "__main__":
part1()
part2()
# Output on livekit-agents 1.8.4 (main at 96341b0db2d0224403a36612cb04a1e38d60d405 gives the same result; the monitor's own "event loop blocked" log lines are filtered out):
part 1: lag=200ms watchdog_gap=0ms cpu_time=0ms process_descheduled=False
part 1: stacks=['# no sample: the block ended before the watchdog looked']
part 1: FAIL: watchdog idle for 210ms (one tick is 20ms), reported watchdog_gap=0ms
part 2: sorted() holds the GIL for 260ms per call
part 2: lag= 241ms gap= 4ms cpu= 0ms # no sample: the block ended before the watchdog looked
part 2: lag= 247ms gap= 232ms cpu= 0ms # loop thread sampled 247ms into the stall
part 2: lag= 250ms gap= 252ms cpu= 0ms (descheduled, no stack)
part 2: lag= 245ms gap= 249ms cpu= 0ms (descheduled, no stack)
part 2: lag= 243ms gap= 243ms cpu= 0ms (descheduled, no stack)
part 2: lag= 249ms gap= 4ms cpu= 0ms # no sample: the block ended before the watchdog looked
part 2: lag= 249ms gap= 240ms cpu= 0ms (descheduled, no stack)
part 2: lag= 277ms gap= 248ms cpu= 24ms (descheduled, no stack)
part 2: lag= 245ms gap= 236ms cpu= 0ms (descheduled, no stack)
part 2: lag= 243ms gap= 241ms cpu= 0ms (descheduled, no stack)
part 2: 2 of 10 GIL waits reported as 'the block ended before the watchdog looked' with watchdog_gap=0
Operating System
macOS 26.5.1 (arm64) for the repro; Linux (Kubernetes, 2 CPU pods) in production
Models Used
Not model related (telemetry, livekit/agents/telemetry/loop_monitor.py)
Package Versions
livekit-agents==1.8.4 (also main at 96341b0db2d0224403a36612cb04a1e38d60d405)
livekit==1.1.20
Python 3.12.12
Production: livekit-agents==1.8.2, livekit==1.1.18 (same loop_monitor.py)
Session/Room/Call IDs
N/A (reproduces without a server)
Proposed Solution
# The watchdog wakes every tick, so any wait longer than one tick since its last wake
# is starvation, wherever in the window that wake fell.
def _consume_watchdog_gap(self, now: float, *, window_start: float) -> float:
late, self._watchdog_late = self._watchdog_late, None
gap = late[1] if late is not None and late[0] >= window_start else 0.0
return max(gap, now - self._watchdog_last_wake - self._tick, 0.0)
Additional Context
We run this change as a local patch. With it, part 1 prints PASS ... reported watchdog_gap=190ms and part 2 reports 0 of 10 stalls as "the block ended before the watchdog looked".
I used an AI assistant to trace this and draft the report; I verified the reproduction myself.
Screenshots and Recordings
N/A