Run each async udf in its own thread#124
Conversation
2f24109 to
53e6c9a
Compare
53e6c9a to
78a96f8
Compare
Async UDFs were running directly in uvicorn's event loop via asyncio.create_task, competing with connection handling under heavy concurrent load. This caused unresponsiveness when running from Jupyter notebooks where the event loop is shared. The fix introduces a dedicated event loop in a background thread for async UDF execution. Coroutines are submitted via run_coroutine_threadsafe() and awaited from the server loop, isolating UDF work from HTTP I/O while preserving cooperative async scheduling between UDFs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Cancel the concurrent.futures.Future in the UDF loop on disconnect/timeout so the coroutine is interrupted promptly, not just at the next cancel_on_event row check. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ture asyncio.create_task() requires a coroutine but asyncio.wrap_future() returns a Future. Use asyncio.ensure_future() which accepts both. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Prevents UDF event loop thread leaks when run_udf_app() is called repeatedly in Jupyter notebooks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Cancel udf_future when func_task is in pending set after asyncio.wait - Cancel udf_future in finally block to ensure cleanup on any exit path - Wrap post-construction code in try/except to call app.shutdown() if validation, config, or registration fails after Application is created Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Move udf_future initialization before input_handler['load']() to prevent NameError in finally block if parsing raises - Lazily create UDF event loop on first async UDF invocation instead of unconditionally in __init__, avoiding wasted resources for sync-only or metadata-only usage - Guard shutdown() against None loop/thread Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
After stopping the event loop and joining the thread, set both _udf_loop and _udf_thread back to None so that _get_udf_loop() can safely recreate them if called after shutdown. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The dedicated shared event loop still caused starvation under concurrent async UDF calls. Switch to the same model used by sync UDFs: each request gets its own thread with asyncio.run(), eliminating loop contention. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Wraps the inner coroutine in _cancellable_run which polls cancel_event and raises CancelledError at the next await (~100ms), ensuring vector UDFs respect disconnect/timeout signals without waiting for completion. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace asyncio.run() with _run_with_graceful_shutdown() that drains pending callbacks before closing the loop, preventing RuntimeError from httpx/anyio TLS cleanup in async UDFs calling OpenAI/LangChain APIs. Add 17 unit tests covering graceful shutdown, cancellation timing, exception propagation, context variable isolation, and concurrent safety. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
4c8958b to
f27488e
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 018db7a. Configure here.
| if cancel_check in done: | ||
| task.cancel() | ||
| raise asyncio.CancelledError() | ||
| return task.result() |
There was a problem hiding this comment.
Cancel races successful UDF
High Severity
In _cancellable_run, when cancel_event is set at the same time the UDF coroutine finishes, asyncio.wait can place both the work task and _poll_cancel in done. The handler always treats a finished cancel poll as cancellation and raises CancelledError, even if the UDF task already completed successfully, so timeouts/disconnects can win over a valid result.
Reviewed by Cursor Bugbot for commit 018db7a. Configure here.
| 'SINGLESTOREDB_EMBEDDINGS_POOL_TIMEOUT', '10', | ||
| ), | ||
| ), | ||
| ) |
There was a problem hiding this comment.
Sync timeouts ignored async client
Medium Severity
SingleStoreEmbeddingsFactory parses connect_timeout and read_timeout from the optional sync http_client for Bedrock, but the new default httpx.AsyncClient for OpenAI embeddings only uses env defaults (60s read). Callers who configure timeouts via http_client get different limits on async embedding HTTP than they expect.
Reviewed by Cursor Bugbot for commit 018db7a. Configure here.


Note
High Risk
Changes core UDF concurrency, cancellation, and embeddings HTTP behavior under load; misconfiguration or regressions could affect timeouts, pooling, and concurrent EMBED_TEXT-style workloads.
Overview
Reworks Python UDF / external-function execution so async calls run on a single dedicated asyncio dispatch thread (fixing loop-bound resource reuse for
httpxpools and enabling concurrent async requests), while sync UDFs use persistent per-worker-thread event loops instead ofasyncio.runper request. Adds_cancellable_runwiththreading.Eventcancellation, offloads heavy parse/serialize to the executor, and tightens cancel signaling on timeout/disconnect.Embeddings get a default
httpx.AsyncClientwith env-tunable timeouts, keep-alive pooling, optional transport IP pin, andTracingAsyncTransportplushttp_trace_idfor correlated HTTP stage logging. Managed UDF apps set uvicorntimeout_keep_alive=120to reduce upstream proxy connect timeouts.Bumps package version to
1.16.11rc1+byasainiand addstest_udf_event_loop.pycovering dispatch, cancellation, and Application routing.Reviewed by Cursor Bugbot for commit 018db7a. Bugbot is set up for automated code reviews on this repo. Configure here.