EventLoopMonitor reads every sampled frame's source file on the event loop thread when it formats a report
Bug Description
The watchdog samples the loop thread with lookup_lines=False, and the comment says lines "load lazily when a report is formatted":
https://github.com/livekit/agents/blob/e684c2379e1c385afe8edcd1f02ea422051b035f/livekit-agents/livekit/agents/telemetry/loop_monitor.py#L586-L590
The report is formatted by the heartbeat, _on_tick -> _build_report -> _format_frames, and that runs on the loop thread, right after the block ends:
https://github.com/livekit/agents/blob/e684c2379e1c385afe8edcd1f02ea422051b035f/livekit-agents/livekit/agents/telemetry/loop_monitor.py#L326 https://github.com/livekit/agents/blob/e684c2379e1c385afe8edcd1f02ea422051b035f/livekit-agents/livekit/agents/telemetry/loop_monitor.py#L656-L683
_format_frames calls traceback.format_list([f]) for each frame (L680). format_list reads FrameSummary.line, which reads the frame's source file through linecache the first time that file is seen. So the monitor adds file reads to the loop it is reporting on, after a stall. It also formats every frame before it keeps the last MAX_STACK_FRAMES (L683), so it reads files for frames that are not in the report.
linecache reads and splits the file in Python code, so with other threads running Python the read is also slowed by GIL contention. On our staging worker (many job loops as threads of one process), the read was itself a 133 ms block of the loop.
The repro samples a real stack that runs through 20 generated modules of about 3,000 lines each (the sample is taken on another thread, as the watchdog does), clears linecache, and runs the real _on_tick. On livekit-agents 1.8.4 and on main (96341b0):
| Other threads running Python | _on_tick on the loop thread, median of 10 |
max |
|---|---|---|
| 0 | 20.8 ms | 43.9 ms |
| 1 | 600.2 ms | 758.4 ms |
linecache holds all 20 files afterwards, read during _on_tick.
Expected Behavior
Formatting a report does no file I/O on the loop thread. A report of a 200 ms stall should not add a second stall of 20 to 600 ms to the same loop.
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 (one other busy thread)
# uv run --python 3.12 --with 'livekit-agents==1.8.4' python repro.py 0 (no other thread)
# 3. "FAIL: the heartbeat read 20 source files on the loop thread" shows the defect.
"""EventLoopMonitor reads every sampled frame's source file on the loop thread.
The watchdog samples with lookup_lines=False, but the report is formatted by
the heartbeat (_on_tick -> _build_report -> _format_frames ->
traceback.format_list), which runs on the loop thread that just unblocked, and
format_list reads each frame's line through linecache.
The sampled stack runs through 20 generated modules of about 3,000 lines each,
like a call path through library code. linecache starts cold, as for a stack
whose files were never formatted before in the process. Usage:
repro.py [busy_threads] (default 1: one other thread running Python code)
"""
import asyncio
import linecache
import sys
import tempfile
import threading
import time
from pathlib import Path
from livekit.agents.telemetry.loop_monitor import BlockedReport, EventLoopMonitor, _Incident
DEPTH = 20
CONTENDERS = int(sys.argv[1]) if len(sys.argv) > 1 else 1
d = Path(tempfile.mkdtemp())
for i in range(DEPTH):
body = "x = 1\n" * 3000
tail = (f"import m{i + 1}\ndef f(block):\n return m{i + 1}.f(block)\n" if i < DEPTH - 1
else "def f(block):\n return block()\n")
(d / f"m{i}.py").write_text(body + tail)
sys.path.insert(0, str(d))
import m0 # noqa: E402
stop = False
def busy() -> None:
while not stop:
pass
for _ in range(CONTENDERS):
threading.Thread(target=busy, daemon=True).start()
def sampled_by_watchdog(mon):
"""The real sampler, run on another thread while this (loop) thread waits."""
out = []
t = threading.Thread(target=lambda: out.append(mon._sample_loop_thread(0.15)))
t.start()
t.join()
return out[0]
async def main() -> None:
loop = asyncio.get_running_loop()
mon = EventLoopMonitor(loop, warn_threshold=0.1, error_threshold=5.0,
tick_interval=0.02, emit_spans=False)
reports: list[BlockedReport] = []
mon._on_report = reports.append
mon._loop_thread_ident = threading.get_ident()
times = []
for _ in range(10):
sample = m0.f(lambda: sampled_by_watchdog(mon)) # the loop thread, 20 modules deep
linecache.clearcache()
mon._incident = _Incident(tick_seq=mon._tick_seq, samples=[sample])
mon._last_tick_at = time.monotonic() - 0.22 # this tick ends a 200 ms block
mon._watchdog_last_wake = time.monotonic() # the watchdog thread is healthy
t = time.perf_counter()
mon._on_tick() # what the loop runs when the block ends
times.append((time.perf_counter() - t) * 1000)
if mon._timer is not None:
mon._timer.cancel()
await asyncio.sleep(0.05)
mon.stop()
read = sorted(Path(p).name for p in linecache.cache if p.startswith(str(d)))
times.sort()
print(f"report frames: {sum('File ' in ln for ln in reports[-1].stacks[0].splitlines())}, "
f"first line: {reports[-1].stacks[0].splitlines()[1].strip()!r}")
print(f"source files read by linecache during _on_tick: {len(read)} ({', '.join(read[:3])}, ...)")
print(f"_on_tick on the loop thread, {CONTENDERS} busy thread(s): "
f"median {times[5]:.1f}ms, max {times[-1]:.1f}ms")
print(f"{'PASS' if not read else 'FAIL'}: the heartbeat read {len(read)} source files "
f"on the loop thread to format one report")
asyncio.run(main())
stop = True
# 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):
report frames: 20, first line: 'File "/var/folders/01/rcssw2m57739sznyp_jfhfcc0000gp/T/tmpikc07ys0/m5.py", line 3003, in f'
source files read by linecache during _on_tick: 20 (m0.py, m1.py, m10.py, ...)
_on_tick on the loop thread, 1 busy thread(s): median 600.2ms, max 758.4ms
FAIL: the heartbeat read 20 source files on the loop thread to format one report
$ uv run --python 3.12 --with 'livekit-agents==1.8.4' python repro.py 0
report frames: 20, first line: 'File "/var/folders/01/rcssw2m57739sznyp_jfhfcc0000gp/T/tmpfljst8z9/m5.py", line 3003, in f'
source files read by linecache during _on_tick: 20 (m0.py, m1.py, m10.py, ...)
_on_tick on the loop thread, 0 busy thread(s): median 20.8ms, max 43.9ms
FAIL: the heartbeat read 20 source files on the loop thread to format one report
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
# Keep file, line and function, and never look up the source text. In _sample_loop_thread
# (runs on the watchdog thread), after the frames are extracted:
frames = [
traceback.FrameSummary(f.filename, f.lineno, f.name, lookup_line=False, line="")
for f in frames
]
# Alternatively, format " File {filename!r}, line {lineno}, in {name}" directly in
# _format_frames instead of traceback.format_list, and only for the frames that survive
# the MAX_STACK_FRAMES cut.
Additional Context
We run the first variant as a local patch. With it the same repro prints PASS: the heartbeat read 0 source files and _on_tick takes 0.1 ms median (one busy thread). The report keeps File "...", line N, in f for every frame; only the source text line is gone.
I used an AI assistant to trace this and draft the report; I verified the reproduction myself.
Screenshots and Recordings
N/A