Skip to content

fix(llm): avoid asyncio.run crash in Codex complete inside active eve…#6928

Closed
AkshathaaRk wants to merge 1 commit intoaden-hive:mainfrom
AkshathaaRk:fix/codex-complete-event-loop-crash
Closed

fix(llm): avoid asyncio.run crash in Codex complete inside active eve…#6928
AkshathaaRk wants to merge 1 commit intoaden-hive:mainfrom
AkshathaaRk:fix/codex-complete-event-loop-crash

Conversation

@AkshathaaRk
Copy link
Copy Markdown

@AkshathaaRk AkshathaaRk commented Apr 3, 2026

Description

Brief description of the changes in this PR.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

Changes Made

  • Change 1
  • Change 2
  • Change 3

Required changes

-Fixes #6929

Testing

Describe the tests you ran to verify your changes:

  • Unit tests pass (cd core && pytest tests/)
  • Lint passes (cd core && ruff check .)
  • Manual testing performed

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Screenshots (if applicable)

Add screenshots to demonstrate UI changes.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved event loop handling in the LiteLLM provider to prevent conflicts when the completion function is called from within an existing event loop, ensuring reliable operation in more scenarios.

…nt loop

LiteLLMProvider.complete used asyncio.run on the Codex backend path, which crashes with RuntimeError when called from async contexts (notebooks, FastAPI, running event loops).

Fix: route Codex complete through a sync bridge helper. If no running loop exists, use asyncio.run normally. If a running loop exists, execute the coroutine in a worker thread.

Tests added: test_complete_codex_backend_in_sync_context and test_complete_codex_backend_in_running_event_loop. Verified with uv run pytest tests/test_litellm_provider.py -k codex_backend -q and uv run pytest tests/test_litellm_provider.py -q.
Copilot AI review requested due to automatic review settings April 3, 2026 12:22
@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 3, 2026

PR Requirements Warning

This PR does not meet the contribution requirements.
If the issue is not fixed within ~24 hours, it may be automatically closed.

Missing: No linked issue found.

To fix:

  1. Create or find an existing issue for this work
  2. Assign yourself to the issue
  3. Re-open this PR and add Fixes #123 in the description

Exception: To bypass this requirement, you can:

  • Add the micro-fix label or include micro-fix in your PR title for trivial fixes
  • Add the documentation label or include doc/docs in your PR title for documentation changes

Micro-fix requirements (must meet ALL):

Qualifies Disqualifies
< 20 lines changed Any functional bug fix
Typos & Documentation & Linting Refactoring for "clean code"
No logic/API/DB changes New features (even tiny ones)

Why is this required? See #472 for details.

@github-actions github-actions bot added the pr-requirements-warning PR doesn't follow contribution guidelines. Please fix or it will be auto-closed. label Apr 3, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 3, 2026

📝 Walkthrough

Walkthrough

Updated LiteLLMProvider.complete() to handle the Codex backend sync path by introducing _run_coro_from_sync(). This wrapper detects whether an event loop is already running and uses asyncio.run() directly or offloads it to a worker thread via ThreadPoolExecutor as needed. Added test validation for both contexts.

Changes

Cohort / File(s) Summary
Event Loop Handling
core/framework/llm/litellm.py
Added _run_coro_from_sync() static method that detects and handles event loop conflicts by switching to ThreadPoolExecutor when an event loop is already running. Updated complete() Codex backend path to route through this wrapper.
Test Coverage
core/tests/test_litellm_provider.py
Added two test cases: test_complete_codex_backend_in_sync_context() and test_complete_codex_backend_in_running_event_loop() to validate complete() behavior in both sync and running event loop contexts.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop, skip, and jump through loops we go,
When async dares to steal the show,
A thread pool springs to save the day,
No event loop shall block the way!
With tests to guard our clever trick,
The rabbit's code is fast and slick. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main fix: avoiding asyncio.run crashes in Codex complete when an event loop is already active. It directly reflects the core change in the PR.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes LiteLLMProvider.complete() crashing in async contexts when using the Codex backend by avoiding direct asyncio.run() calls from threads with an active event loop.

Changes:

  • Route Codex-backend complete() calls through a sync bridge helper that can execute coroutines even when an event loop is already running.
  • Add tests covering Codex backend completion from both sync callers and from within a running event loop.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
core/framework/llm/litellm.py Replaces asyncio.run(self.acomplete(...)) on the Codex path with a helper that runs the coroutine safely when an event loop is active.
core/tests/test_litellm_provider.py Adds regression tests for Codex backend complete() in sync and async (running loop) contexts.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +795 to +804
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro_factory())

def _run_in_worker() -> Any:
return asyncio.run(coro_factory())

with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
return executor.submit(_run_in_worker).result()
Copy link

Copilot AI Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a running event loop is detected, this offloads the coroutine to a worker thread but does not propagate contextvars into that thread. This can drop trace/execution context in logs/headers produced inside acomplete()/stream() (the codebase elsewhere explicitly copies context before running work in a thread). Consider wrapping the worker call with contextvars.copy_context() (e.g., submit ctx.run(...)) so observability context is preserved.

Copilot uses AI. Check for mistakes.
@AkshathaaRk
Copy link
Copy Markdown
Author

Maintainer help needed: I cannot assign myself on issue #6929 due to permission limits. Could someone assign @AkshathaaRk on issue #6929 so this PR can pass the contribution requirement?

@AkshathaaRk
Copy link
Copy Markdown
Author

cc @claude @fermano

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 5, 2026

Closing PR because the contribution requirements were not resolved within the 24-hour grace period.
If this was closed in error, feel free to reopen the PR after fixing the requirements.

@github-actions github-actions bot closed this Apr 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-requirements-warning PR doesn't follow contribution guidelines. Please fix or it will be auto-closed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: LiteLLMProvider.complete crashes in async context on Codex path due to asyncio.run

2 participants