fix(python): start background event loop lazily (#5111)

## Summary

Importing `lancedb` currently starts a daemon thread running a private
asyncio loop, even when the process never performs a synchronous
database operation.

Start that loop on the first actual coroutine submission instead.
Concurrent first callers share one initialization, and a forked child
resets the singleton to the unstarted state without touching the
inherited thread or lock, then starts fresh work lazily on first use.

The Rust-side runtime and the existing fork/reopen contracts are
unchanged.

## Validation

- New import, first-use, concurrent first-use, and fork parent/child
coverage passes.
- Existing import, debugger-inspection, cancellation, and remote fork
tests pass.
- `ruff format --check .` and `ruff check .` pass.
This commit is contained in:
Xuanwo
2026-11-20 20:24:15 +08:00
committed by GitHub
parent 28e9ebb3dd
commit 164aec1753
3 changed files with 285 additions and 19 deletions
+47 -15
View File
@@ -13,22 +13,51 @@ class BackgroundEventLoop:
A background event loop that can run futures.
Used to bridge sync and async code, without messing with users event loops.
The loop and its thread are created by the first call to :meth:`run`, not
by constructing this object, so importing lancedb does not leave an idle
background thread behind.
"""
def __init__(self):
self._start()
self.loop: asyncio.AbstractEventLoop | None = None
self.thread: threading.Thread | None = None
self._start_lock = threading.Lock()
def _start(self):
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(
target=self.loop.run_forever,
name="LanceDBBackgroundEventLoop",
daemon=True,
)
self.thread.start()
def _start(self) -> asyncio.AbstractEventLoop:
loop = self.loop
if loop is not None:
return loop
with self._start_lock:
loop = self.loop
if loop is not None:
return loop
loop = asyncio.new_event_loop()
thread = threading.Thread(
target=loop.run_forever,
name="LanceDBBackgroundEventLoop",
daemon=True,
)
thread.start()
# Publish the loop first and the thread last. Callers that reach
# _start while this is in progress wait on _start_lock, so they
# cannot observe a half-initialized loop/thread pair.
self.loop = loop
self.thread = thread
return loop
def _reset_after_fork(self):
# Threads do not survive fork(). Reset to the unstarted state without
# calling into the inherited loop or thread: the thread is gone, and
# it may have held _start_lock when the fork happened. A fresh lock
# lets the child start a new loop on its first run().
self.loop = None
self.thread = None
self._start_lock = threading.Lock()
def run(self, future):
concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop)
loop = self._start()
concurrent_future = asyncio.run_coroutine_threadsafe(future, loop)
try:
return concurrent_future.result()
except BaseException:
@@ -60,12 +89,15 @@ _FORK_WARNED = False
def _reset_after_fork():
# Threads do not survive fork(), so the asyncio loop in LOOP.thread is
# dead in the child. Re-initialize the singleton in place so existing
# Threads do not survive fork(), so the loop in LOOP.thread is dead in
# the child. Reset the singleton in place so existing
# `from .background_loop import LOOP` references in other modules see
# the new state. The Rust-side tokio runtime is reset analogously by a
# pthread_atfork hook installed in the _lancedb extension.
LOOP._start()
# the unstarted state and create a fresh loop on their first run(). Do
# not restart it here: the child may never use LanceDB, and the at-fork
# handler must not touch the vanished thread or acquire inherited locks.
# The Rust-side tokio runtime is reset analogously by a pthread_atfork
# hook installed in the _lancedb extension.
LOOP._reset_after_fork()
# The embedding executor's worker threads are dead in the child as well.
# Replace it with a fresh pool (threads are spawned lazily, so this is
# cheap); we don't shut down the old one, since joining its dead workers
+236
View File
@@ -0,0 +1,236 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import multiprocessing as mp
import os
import subprocess
import sys
import textwrap
import traceback
import pytest
BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
def _run_in_subprocess(code: str) -> subprocess.CompletedProcess:
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
return subprocess.run(
[sys.executable, "-c", textwrap.dedent(code)],
check=False,
capture_output=True,
text=True,
env=env,
timeout=30,
)
def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None:
assert result.returncode == 0, result.stderr or result.stdout
def test_import_and_inspection_do_not_start_background_loop():
result = _run_in_subprocess(
f"""
import threading
import lancedb
from lancedb.background_loop import BackgroundEventLoop, LOOP
def background_threads():
return [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert LOOP.thread is None
assert LOOP.loop is None
assert background_threads() == []
# Inspecting a fresh instance is also side-effect free.
loop = BackgroundEventLoop()
assert loop.thread is None
assert loop.loop is None
assert background_threads() == []
"""
)
_assert_subprocess_ok(result)
def test_first_sync_call_starts_one_daemon_thread():
result = _run_in_subprocess(
f"""
import threading
import lancedb
from lancedb.background_loop import LOOP
def background_threads():
return [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert LOOP.thread is None
assert LOOP.loop is None
db = lancedb.connect("memory://")
assert db.table_names() == []
worker = LOOP.thread
assert worker is not None
assert worker is background_threads()[0]
assert len(background_threads()) == 1
assert worker.daemon
assert worker.is_alive()
assert LOOP.loop is not None
"""
)
_assert_subprocess_ok(result)
def test_concurrent_first_use_initializes_one_background_thread():
result = _run_in_subprocess(
f"""
import asyncio
import threading
from lancedb.background_loop import LOOP
worker_count = 8
barrier = threading.Barrier(worker_count)
results = []
errors = []
results_lock = threading.Lock()
def submit(index):
try:
barrier.wait(timeout=10)
value = LOOP.run(asyncio.sleep(0.05, result=index))
with results_lock:
results.append(value)
except BaseException as exc:
with results_lock:
errors.append(repr(exc))
threads = [
threading.Thread(target=submit, args=(index,))
for index in range(worker_count)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=20)
assert all(not thread.is_alive() for thread in threads)
assert errors == []
assert sorted(results) == list(range(worker_count))
background_threads = [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert len(background_threads) == 1
assert background_threads[0].daemon
"""
)
_assert_subprocess_ok(result)
def _fork_child_starts_lazily(queue):
def background_threads():
import threading
return [
thread
for thread in threading.enumerate()
if thread.name == BACKGROUND_THREAD_NAME
]
try:
from lancedb.background_loop import LOOP
inherited_thread_is_none = LOOP.thread is None
inherited_loop_is_none = LOOP.loop is None
background_threads_before = [thread.name for thread in background_threads()]
import lancedb
db = lancedb.connect("memory://")
tables = db.table_names()
worker = LOOP.thread
queue.put(
{
"error": None,
"inherited_thread_is_none": inherited_thread_is_none,
"inherited_loop_is_none": inherited_loop_is_none,
"background_threads_before": background_threads_before,
"tables": tables,
"thread_alive": False if worker is None else worker.is_alive(),
"thread_daemon": False if worker is None else worker.daemon,
"background_thread_count": len(background_threads()),
}
)
except BaseException:
queue.put({"error": traceback.format_exc()})
@pytest.mark.skipif(
sys.platform != "linux",
reason=(
"fork() is unavailable on Windows and unsafe on macOS "
"(Apple frameworks/TLS are not fork-safe)"
),
)
def test_forked_child_starts_background_loop_lazily():
import asyncio
from lancedb.background_loop import LOOP
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
parent_thread = LOOP.thread
assert parent_thread is not None
ctx = mp.get_context("fork")
queue = ctx.Queue()
# Simulate forking while another thread held the initialization lock. The
# child must replace the inherited lock instead of trying to acquire it.
LOOP._start_lock.acquire()
try:
proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,))
proc.start()
finally:
LOOP._start_lock.release()
proc.join(timeout=20)
if proc.is_alive():
proc.terminate()
proc.join(timeout=5)
if proc.is_alive():
proc.kill()
proc.join()
pytest.fail("Forked child hung starting the background loop")
assert proc.exitcode == 0, f"child exited with code {proc.exitcode}"
payload = queue.get(timeout=5)
queue.close()
assert payload["error"] is None, payload["error"]
assert payload["inherited_thread_is_none"] is True
assert payload["inherited_loop_is_none"] is True
assert payload["background_threads_before"] == []
assert payload["tables"] == []
assert payload["thread_alive"] is True
assert payload["thread_daemon"] is True
assert payload["background_thread_count"] == 1
# The child's reset must not disturb the parent's loop.
assert LOOP.thread is parent_thread
assert parent_thread.is_alive()
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
+2 -4
View File
@@ -5370,12 +5370,10 @@ def test_background_loop_cancellation(exception):
mock_future = MagicMock()
mock_future.result.side_effect = exception()
with (
patch.object(BackgroundEventLoop, "__init__", return_value=None),
patch("asyncio.run_coroutine_threadsafe", return_value=mock_future),
):
with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future):
loop = BackgroundEventLoop()
loop.loop = MagicMock()
loop.thread = MagicMock()
with pytest.raises(exception):
loop.run(None)
mock_future.cancel.assert_called_once()