TensorRT-LLM icon indicating copy to clipboard operation
TensorRT-LLM copied to clipboard

[Bug]: etcd watch callback cancels discovery watch under asyncio debug mode

Open codebreaker77 opened this issue 1 month ago • 2 comments

On main 46d9966b54d9d11998b712e732fb20f64d4d35c0, a real etcd notification can cancel a live watch and leave its asyncio reader blocked when debug mode is enabled. Re-requesting the same prefix returns the cached dead handle.

Reproduction

With a dedicated etcd 3.5 server and a matching TensorRT-LLM Python environment:

import asyncio
import uuid
from tensorrt_llm.serve.cluster_storage import Etcd3ClusterStorage

async def main():
    storage = Etcd3ClusterStorage("etcd://127.0.0.1:2379", "repro")
    prefix = "watch-repro/" + uuid.uuid4().hex + "/"
    watch = await storage.watch(prefix)
    pending = asyncio.create_task(watch.drain())
    await asyncio.sleep(0)  # reader waits before the SDK thread delivers
    assert await storage.set(prefix + "worker", "registered")
    print("key:", await storage.get(prefix + "worker"), flush=True)
    print(await pending, flush=True)

asyncio.run(main(), debug=True)

Run under an external process timeout: the failed wakeup can leave an orphaned reader, so an asyncio timeout is not a sufficient whole-process safety bound. Setting debug=False is the successful control.

Observed

Three independent runs against real etcd all produced:

  • Debug off: event delivered; SDK watch stays active.
  • Debug on: logs Non-thread-safe operation invoked on an event loop other than the current one; no event delivered; key still readable; SDK watch removed.
  • After recording failure and repairing the orphaned wakeup for test cleanup, disabling debug and calling watch(prefix) returns the same cached handle; a second etcd write produces no notification.

This could make a discovery consumer stop receiving worker changes. No router state, model-serving traffic or GPU effects were measured. Production-mode controls passed; the established runtime failure is under asyncio debug.

Cause / proposed scope

Etcd3WatchEventQueue.add_events_from_resp mutates an asyncio queue directly on the etcd SDK callback thread. Its later call_soon_threadsafe(lambda: None) is too late to make that queue operation safe. The exception handler then cancels the watch, while storage keeps its cached handle.

Capture the owning event loop and enqueue events on that loop using call_soon_threadsafe, with focused threaded-delivery and pending-reader tests. The unsafe pattern was already flagged in an old review: https://github.com/NVIDIA/TensorRT-LLM/pull/8210#discussion_r2415560025 I found no dedicated issue or current fix through searches for etcd/thread, debug, watch/reconnect and the queue class name. This report adds runtime evidence rather than claiming the pattern was previously unknown.

Validation boundary

Real etcd-sdk-python 0.0.7 with Docker etcd 3.5.21. Full unchanged storage/logger source modules loaded while bypassing TensorRT/native package initialization. Windows Python 3.10 client with real-server I/O; supplementary actual-thread and SDK-event checks also reproduce on Linux Python 3.12. The normal-package snippet above and model serving were not executed locally. This is separate from the expired-lease failure in #20529.

Proposed patch and follow-up validation

A focused fix is available on my fork, commit 819f5c8f. It captures the owning event loop and schedules queue insertion onto that loop, removing the private queue-loop wakeup. It does not include the separate lease recovery work from #20529.

The nine new CPU cases produce 5 failures / 4 passes on unchanged source and 9 passes with the fix. The full existing storage suite plus these cases passes 62 tests on Linux Python 3.12. Six real-etcd runs with the fix (three each with debug on/off) deliver two successive notifications and keep the watch active. The same native-bootstrap isolation described above applies; no full-package, model-serving or GPU validation is claimed. Applicable formatting/lint checks pass. The branch is prepared for issue triage; no upstream PR has been opened.

codebreaker77 avatar Oct 20 '26 15:10 codebreaker77

Hi! I'm interested in contributing to TensorRT-LLM and investigated this asyncio watch issue. I noticed you have a prepared fix on your fork. Would independent testing or any additional work be helpful, or would you recommend I pick up a separate issue?

navenavelimargam avatar Oct 22 '26 08:10 navenavelimargam

One repo-grounded data point in favour of the call_soon_threadsafe fix on your fork, since I hit the same class of queue/loop handoff in the executor stats path:

The existing wakeup in Etcd3WatchEventQueue.add_events_from_resp is if self.events._loop: self.events._loop.call_soon_threadsafe(lambda: None). On Python 3.10+ asyncio.Queue binds its loop lazily (_LoopBoundMixin._get_loop() runs on the first await get()/put() that has to block), so _loop is None until a reader is actually waiting, and put_nowait never sets it (checked on 3.10: _loop is still None after put_nowait). So today the wakeup is skipped exactly in the "reader not yet waiting" case, and in the "reader waiting" case the put_nowait from the SDK thread is the non-thread-safe call debug mode catches. Scheduling the put_nowait itself onto the owning loop, as your commit does, removes both at once and drops the dependence on the private _loop attribute.

Capturing asyncio.get_running_loop() in __init__ is safe here because the only constructor call is inside async def watch() (cluster_storage.py). The one behavioural edge is a callback arriving after the loop is closed: call_soon_threadsafe raises RuntimeError, which your except turns into cancel_event(), and your test_late_callback_after_loop_shutdown_cancels_watch pins that, which seems like the right outcome.

If you open the PR I am happy to review it; the fix looks ready as is.

lonexreb avatar Oct 25 '26 07:10 lonexreb