Run async UDFs on a dedicated event-loop thread#124
Conversation
2f24109 to
53e6c9a
Compare
53e6c9a to
78a96f8
Compare
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.
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>
018db7a to
1669fb2
Compare
1669fb2 to
0a7a0a9
Compare
There was a problem hiding this comment.
Pull request overview
This PR moves async UDF execution off the request event loop and onto a process-wide dedicated event-loop thread to improve concurrency and allow reuse of loop-bound async resources across requests (e.g., HTTP client pools). It also updates cancellation behavior to work across threads and increases the default uvicorn keep-alive timeout for managed Python UDF servers to reduce connection churn under load.
Changes:
- Add a singleton dedicated async-dispatch event loop running in a daemon thread, and route async UDF invocations through it.
- Implement cross-thread cancellation via a
threading.Eventpolled from the dispatch loop, and wire cancellation signaling into the invoke path. - Increase managed UDF server keep-alive timeout via
SINGLESTOREDB_UDF_KEEPALIVE_TIMEOUTand add tests covering dispatch concurrency/routing/cancellation.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| singlestoredb/functions/ext/asgi.py | Introduces the shared async-dispatch loop/thread and updates the UDF invoke path to dispatch async UDFs there with cross-thread cancellation. |
| singlestoredb/apps/_python_udfs.py | Wires a configurable uvicorn timeout_keep_alive with a higher default to reduce idle connection churn. |
| singlestoredb/tests/test_udf_event_loop.py | Adds unit/integration tests for dispatch loop behavior, cancellation helper, and Application routing between async/sync UDF execution paths. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
kesmit13
left a comment
There was a problem hiding this comment.
I had Copilot do a review. Can you just check over the comments and see if there is anything that still needs addressing? If it looks ok, I'll merge it.
|
@kesmit13 one was good catch. rest were improvements. Good to go now. |

Note
Medium Risk
Changes core UDF invoke concurrency and cancellation semantics on a shared global loop; mitigated by extensive new tests but still affects production request handling under load.
Overview
Moves async UDF execution off the uvicorn/ASGI request loop onto a singleton daemon thread with its own event loop, so heavy or blocking async work is less likely to prevent the server from accepting new connections. Concurrent async invocations are scheduled on that loop via
run_coroutine_threadsafe(with contextvars copied across the thread boundary); sync UDFs still run in a worker thread with a per-callasyncio.runso they cannot block the shared dispatch loop.Adds
_cancellable_runto honorcancel_eventfor work on the dispatch loop (polling because request-loop task cancel does not reach it), prefers a completed result when cancel races with success, and tightens invoke-path cancellation (cancel_event.set()when the func task is still pending and infinally).Managed UDF uvicorn startup now sets
timeout_keep_aliveto 120s by default (override viaSINGLESTOREDB_UDF_KEEPALIVE_TIMEOUT, with invalid values warned and ignored). Newtest_udf_event_loop.pycovers cancellation, dispatch concurrency, routing, and Application integration.Reviewed by Cursor Bugbot for commit 77c75a6. Bugbot is set up for automated code reviews on this repo. Configure here.
We have seen that UDFs can block the event loop and stop uvicorn from accepting new connections. In this PR I have moved the execution of async UDFs to a dedicated daemon thread.
I have tested this in preview by rolling out the Nova Image.