agents icon indicating copy to clipboard operation
agents copied to clipboard

EventLoopMonitor drops the stack sample when the heartbeat tick runs during _watchdog_check

Open zdurm opened this issue 1 month ago • 2 comments

Bug Description

EventLoopMonitor._watchdog_check reads the tick state and takes its stack sample outside self._lock:

https://github.com/livekit/agents/blob/e684c2379e1c385afe8edcd1f02ea422051b035f/livekit-agents/livekit/agents/telemetry/loop_monitor.py#L531-L553

The block ends when the late tick runs on the loop thread, and the tick races the watchdog in two ways. Both lose the sample, and the report says # no sample: the block ended before the watchdog looked although the watchdog did sample the block.

Case A: the tick runs while the watchdog samples. The watchdog creates the incident under the lock, releases it, and calls _sample_loop_thread (L548). If the block ends then, _on_tick takes the incident with no samples (L317 to L324) and reports. The watchdog then finds self._incident is not incident (L550) and throws the sample away. Sampling is Python code (a stack walk and StackSummary.extract), so with other threads contending for the GIL the watchdog can be switched out in the middle of it, and the loop thread can finish the block meanwhile.

Case B: the watchdog reads the tick's state half updated. _on_tick advances _tick_seq and then writes _last_tick_at (L310 to L312). _watchdog_check reads them in the same order without the lock (L534 to L535). If it runs between the tick's two writes, it reads the new sequence with the old time, so the lag looks as long as the whole block. It then finds that the incident (which already holds the sample of the block that is ending) has a different tick_seq, and replaces it with an empty incident for the new sequence (L541 to L542). The tick then finds an incident for the wrong sequence and reports the block without its sample. The comment at L532 to L533 says a torn read "can only make the lag look smaller", but this order makes it look larger.

The repro drives the real _watchdog_check and the real _on_tick. A trace function pauses one thread at the exact point (Case A: right after _sample_loop_thread returns on the watchdog thread; Case B: on the line self._last_tick_at = now in _on_tick) and runs the other side there, so both cases fail on every run, on livekit-agents 1.8.4 and on main (96341b0).

Expected Behavior

A sample the watchdog took of a block appears in that block's report. In both cases the report's first stack should start with # loop thread sampled ..., not # no sample: the block ended before the watchdog looked.

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. "case A: FAIL" and "case B: FAIL" show the two races; both are deterministic.

"""EventLoopMonitor._watchdog_check loses the stack sample when a tick runs
concurrently with it.

Both cases run the real _watchdog_check and the real _on_tick. A trace function
pauses one thread at a chosen point of the stock code and runs the other
side there, so the interleaving is exact on every run.

Case A: the tick runs after the watchdog has built its sample and before it
stores it (between the two `with self._lock:` blocks of _watchdog_check).
Case B: the watchdog runs while the tick is between `self._tick_seq += 1` and
`self._last_tick_at = now` in _on_tick.
"""

import asyncio
import inspect
import sys
import threading
import time

from livekit.agents.telemetry.loop_monitor import BlockedReport, EventLoopMonitor

WARN, TICK = 0.1, 0.02


def line_of(func, text: str, occurrence: int = 1) -> int:
    lines, first = inspect.getsourcelines(func)
    hits = [first + i for i, ln in enumerate(lines) if ln.strip() == text]
    return hits[occurrence - 1]


def run_paused(func, lineno: int, at_line, *args):
    """Run func(*args) on this thread; call at_line() once when it reaches lineno."""
    fired = False

    def local(frame, event, arg):
        nonlocal fired
        if event == "line" and frame.f_lineno == lineno and not fired:
            fired = True
            at_line()
        return local

    def tracer(frame, event, arg):
        return local if frame.f_code is func.__code__ else None

    sys.settrace(tracer)
    try:
        func(*args)
    finally:
        sys.settrace(None)
    assert fired, f"never reached line {lineno}"


def on_watchdog_thread(fn) -> None:
    t = threading.Thread(target=fn)
    t.start()
    t.join()


def new_monitor():
    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()  # this thread is the loop thread
    return loop, mon, reports


def case_a() -> bool:
    loop, mon, reports = new_monitor()
    mon._last_tick_at = time.monotonic() - 0.15  # the loop has been blocked 130 ms
    sampled = threading.Event()
    tick_done = threading.Event()

    def watchdog():
        # pause the watchdog right after _sample_loop_thread returns its sample
        def local(frame, event, arg):
            if event == "return":
                sampled.set()
                # a monitor that holds its lock here makes the tick wait instead,
                # so give up after 1 s
                tick_done.wait(1.0)
            return local

        def tracer(frame, event, arg):
            return local if frame.f_code is EventLoopMonitor._sample_loop_thread.__code__ else None

        sys.settrace(tracer)
        try:
            mon._watchdog_check()
        finally:
            sys.settrace(None)

    w = threading.Thread(target=watchdog)
    w.start()
    assert sampled.wait(5)
    mon._on_tick()  # the block ends: the tick reports
    tick_done.set()
    w.join()

    stacks = reports[0].stacks
    print(f"case A: report stacks = {stacks}")
    ok = stacks[0].startswith("# loop thread sampled")
    print(f"case A: {'PASS' if ok else 'FAIL'}: the watchdog took a sample of this block, "
          f"the report {'has' if ok else 'does not have'} it")
    mon.stop()
    loop.close()
    return ok


def case_b() -> bool:
    loop, mon, reports = new_monitor()
    mon._last_tick_at = time.monotonic() - 0.15
    on_watchdog_thread(mon._watchdog_check)  # the watchdog samples block 0 (tick_seq 0)
    assert mon._incident is not None and mon._incident.samples
    time.sleep(0.05)  # block 0 lasts 180 ms in total

    between = line_of(EventLoopMonitor._on_tick, "self._last_tick_at = now")
    run_paused(EventLoopMonitor._on_tick, between,
               lambda: on_watchdog_thread(mon._watchdog_check), mon)

    stacks = reports[0].stacks
    print(f"case B: report stacks = {stacks}")
    ok = stacks[0].startswith("# loop thread sampled")
    print(f"case B: {'PASS' if ok else 'FAIL'}: the watchdog sampled block 0 before the tick, "
          f"the report for block 0 {'has' if ok else 'does not have'} the sample")
    mon.stop()
    loop.close()
    return ok


if __name__ == "__main__":
    case_a()
    case_b()

# 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):

case A: report stacks = ['# no sample: the block ended before the watchdog looked']
case A: FAIL: the watchdog took a sample of this block, the report does not have it
case B: report stacks = ['# no sample: the block ended before the watchdog looked']
case B: FAIL: the watchdog sampled block 0 before the tick, the report for block 0 does not have the sample

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

# Read the tick state and take the sample under the lock. The tick writes its sequence
# and time before it takes the lock, so under the lock either both are written or the
# tick has not yet taken the incident. A tick that ends the block waits for the sample
# instead of reporting without it.
def _watchdog_check(self) -> None:
    with self._lock:
        seq = self._tick_seq
        lag = time.monotonic() - (self._last_tick_at + self._tick)
        if lag < self._first_sample_lag:
            return
        incident = self._incident
        if incident is not None and incident.tick_seq != seq:
            return  # the tick ending that block is running and will take it
        if incident is None:
            incident = self._incident = _Incident(tick_seq=seq)
        want_first = not incident.samples
        want_late = not incident.late_sampled and lag >= self._warn * _LATE_SAMPLE_FACTOR
        if not (want_first or want_late):
            return
        incident.samples.append(self._sample_loop_thread(lag))
        if want_late:
            incident.late_sampled = True

Additional Context

We run this change as a local patch; with it both cases print PASS. The cost is that a tick which ends a block while the watchdog is sampling waits for the sample (a stack walk without source lookup) before it reports.

I used an AI assistant to trace this and draft the report; I verified the reproduction myself.

Screenshots and Recordings

N/A

zdurm avatar Oct 03 '26 14:10 zdurm

Hi, I'm Himanshu, looking for a scoped contribution. I saw #7606 and #7618. Could I help compare both reported races using controlled thread barriers: tick during sampling and a partially observed tick update? I'd avoid timing-only tests and coordinate with whichever approach maintainers prefer.

I haven't run this reproduction or the candidate PR's tests yet; this is an offer to investigate, not a claim that the gap is confirmed.

himanshumehta avatar Oct 25 '26 04:10 himanshumehta

Following up on my Oct 25 offer with a run. I used your deterministic repro.py instead of building new barriers, since it already pins both interleavings with a trace function. I ran it on current main (c2b2f5cbd, which includes livekit-agents 1.8.10; loop_monitor.py is unchanged on today's main) and with each open PR's diff applied: #7606, #7618 and #8199.

EventLoopMonitor races: main vs #7606 vs #7618 vs #8199

code your repro, case A / B lock-tolerant repro, A / B watchdog holds _lock during the stack walk PR's own tests: main code → PR code
main FAIL / FAIL FAIL / FAIL — —
#7606 (b255f88d6) PASS / PASS PASS / PASS no 4 failed, 37 passed → 41 passed
#7618 (6f429dedb) PASS / hang PASS / PASS yes 2 failed, 37 passed → 39 passed
#8199 (ed8b21455) PASS / PASS PASS / PASS yes 2 failed, 37 passed → 39 passed

What the run shows:

  • 1.8.10 / main still loses the sample in both cases, as you reported on 1.8.4.

  • All three PRs keep the sample in both cases.

  • The #7618 "hang" comes from the script, not the PR. #7618 moves self._last_tick_at = now inside with self._lock:. Case B pauses the tick on that line, so it pauses while holding the lock, then joins a watchdog thread that needs the lock. The "lock-tolerant" column is your script with one change: on_watchdog_thread joins with a 1 s timeout and lets the paused tick finish first. Case A already does that, per your comment in it. With that change #7618 passes, and main, #7606 and #8199 give the same results as with your original script.

  • The design difference:

    • #7618 and #8199 take the sample while holding _lock. #8199 is your proposed solution almost verbatim. A tick that ends the block waits for the sample.
    • #7606 keeps the stack walk outside the lock, with a samples_in_flight counter and a deferred report. Its code comment gives the reason: _on_tick must not be sampled while blocked on the monitor's own lock.

    I did not measure whether that case happens in practice.

Not covered:

  • Timing under real GIL contention: both repros pin the interleaving.
  • The event_loop_blocked span path.
  • Python versions other than 3.12.
Reproduce
git clone https://github.com/livekit/agents && cd agents && uv sync --all-extras --dev
uv run python repro.py          # the script from this issue
uv run python repro_fair.py     # same, watchdog join with a 1 s timeout in case B
for n in 7606 7618 8199; do
  gh pr diff $n -R livekit/agents > /tmp/$n.diff && git apply --exclude='tests/*' /tmp/$n.diff
  uv run python repro.py; uv run python repro_fair.py; git checkout -q -- .
done

Scripts: repro_fair.py, demo-7599.sh

himanshumehta avatar Nov 05 '26 06:11 himanshumehta